/*
 * Author: Mingjie Yin
 * Created Date: 02/07/2022
 * Purpose: Utility class for describe layouts
 * Test Class: NewAndEditCaseController
 * History: 
 *      02/07/2022 - Mingjie Yin - Initial Code.
 * 
 * */
global without sharing class NewAndEditCaseController {
    public List <LayoutDescriberHelper.LayoutSection > layoutSections{set;get;}
    public String awsToken{set;get;}
    public static Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
    public static String sobjectTypeValue = 'Case';
    public Boolean isNewMode{set;get;}
    public Boolean isCloneMode{protected set;get;}
    public String rtTypeId {get; set;}
    public String AWSDataId{set;get;}
    public String contactId{set;get;}//For Lookup field
    public List<String> encryptedAPIList{set;get;}   
    public String staticResource {get; set;}
    public String staticResourceContact {get; set;}
    public String requiredFieldAPIListStr {get; set;}
    public String fieldAPIToLabelMapStr {get; set;}
    public String Input_Required_Field_Msg{set;get;}
    public String PIPL_Name_Label{set;get;}
    public String PIPL_Input_Account_Error_Msg{set;get;}
    public String sobjectPrefix{set;get;}
    public String sobjecttypeForFrontEnd{set;get;}
    public String contactsInfo {set;get;}//key sfid;value awsid
    public String layoutSectionsStr {get; set;}
    public final string ApiPrefix{get;private set;} //Add By Yin Mingjie 20220404
    public Map<string,string> AWSToSobjectEncryptedMap{get;private set;}
    public string AWSToSobjectEncryptedMapJson{get{return JSON.serialize(AWSToSobjectEncryptedMap);}}
    public String sfRecordIdForEdit{set;get;}//Add By LiJun for Edit Record from NFM609, 20220510
    public String VLookUpFieldsJson{get;private set;}
    public NewAndEditCaseController(ApexPages.StandardController controller) {
        isNewMode = true;
        isCloneMode = false;
        Input_Required_Field_Msg = Label.Input_Required_Field_Msg;
        PIPL_Name_Label = Label.PIPL_Name_Label;
        PIPL_Input_Account_Error_Msg = label.PIPL_Input_Account_Error_Msg;
        sobjecttypeForFrontEnd = sobjectTypeValue;
        //获取所有字段
        List<String> fieldList = new List<String>(Schema.getGlobalDescribe().get('Case').getDescribe().fields.getMap().keyset());  
        // Add fields to controller. This is to avoid the SOQL error in visualforce page
        Map<string,string> mso = ApexPages.currentPage().getParameters();
        if(mso != null && mso.containsKey('newclone')){
            isCloneMode = true;
        }
        if (!Test.isRunningTest()) {
            controller.addFields(fieldList);
        }
        SObject obj = controller.getRecord();        
        if(obj.Id != null){
            //更新
            isNewMode = false;
            Case caseData = [select Id,RecordTypeId,AWS_Data_Id__c,ContactId,Contact.AWS_Data_Id__c from Case where id =: obj.Id];
            rtTypeId = caseData.RecordTypeId;
            AWSDataId = caseData.AWS_Data_Id__c;
            sfRecordIdForEdit = obj.Id;//Add By LiJun for Edit Record from NFM609, 20220510
            System.debug('AWSDataId=' + AWSDataId);
            Map<String,String> sfIdToAWSIdMap = new Map<String,String>();
            if(caseData.ContactId != null){
                sfIdToAWSIdMap.put(String.valueof(caseData.ContactId).subString(0,15),caseData.Contact.AWS_Data_Id__c);
            }
            // sfIdToAWSIdMap.put(String.valueof(caseData.ContactId).subString(0,15),caseData.Contact.AWS_Data_Id__c);
            
            contactsInfo = JSON.serialize(sfIdToAWSIdMap);
        }else{
            //新建
            // rtTypeId = ApexPages.currentPage().getParameters().get('RecordType');
            AssignValueFromUrl(mso,controller.getRecord());
            rtTypeId = mso.get('RecordType');
            obj.put('OwnerId',UserInfo.getUserId());
        }
        LayoutDescriberHelper.LayoutWrapper LayoutWrapperValue = LayoutDescriberHelper.describeSectionWithFieldsWrapper(rtTypeId, 'Case','classic');
        layoutSections = LayoutWrapperValue.layoutSections;
        List<String> requiredFieldAPIList = LayoutWrapperValue.requiredFieldAPIList;
        Map<String,String> fieldAPIToLabelMap = LayoutWrapperValue.fieldAPIToLabelMap;
        requiredFieldAPIListStr = JSON.serialize(requiredFieldAPIList);
        fieldAPIToLabelMapStr = JSON.serialize(fieldAPIToLabelMap);
        PIHelper.PIIntegration piIntegration = PIHelper.getPIIntegrationInfo('Case');
        staticResource = JSON.serialize(piIntegration);
        staticResourceContact = JSON.serialize(PIHelper.getPIIntegrationInfo('Contact'));
        encryptedAPIList = piIntegration.PIFields;
        sobjectPrefix = piIntegration.sobjectPrefix;
        layoutSectionsStr = JSON.serialize(layoutSections);
        AWSToSobjectEncryptedMap = new Map<String,String>();
        
        //获取lookup字段
        List<String> VLookUpFields = new List<String>();
        for (LayoutDescriberHelper.LayoutSection ls : layoutSections) {
            for (LayoutDescriberHelper.LayoutField lf : ls.layoutFields) {
                if (lf.fieldAPI != '' && lf.fieldType == 'reference') {
                    VLookUpFields.add(lf.fieldAPI);
                }
            }
        }
        VLookUpFieldsJson = Json.serialize(VLookUpFields);
        for (PI_Field_Policy_Detail__c PIDetail : piIntegration.PIDetails) {
            AWSToSobjectEncryptedMap.put(PIDetail.AWS_Field_API__c, PIDetail.SF_Field_API_Name__c);
        }
    }
    global class Response{
        public String recordId{set;get;}
        public String message{set;get;}
        public String status{set;get;}
    }
    @RemoteAction
    global static Response saveCase(String caseJson,String transId,Boolean isNew) {
        System.debug('Case Info:' + JSON.serialize(caseJson));
        //1. Prepare the payload for  Case
        Schema.SObjectType caseSchema = schemaMap.get(sobjectTypeValue);
        Map<String, Schema.SObjectField> fieldAPIToTypeMap = caseSchema.getDescribe().fields.getMap();
        Map<String,Object> fieldValueMap = (Map<String,Object>)JSON.deserializeUntyped(caseJson);
        Case caseInfo = new Case();
        //自定义格式转换
        for (String fieldAPI: fieldValueMap.keySet()) {
            system.debug('field API'+fieldAPI);
            if(!fieldAPIToTypeMap.containskey(fieldAPI)){
                continue;
            }
            Schema.DisplayType fielddataType = fieldAPIToTypeMap.get(fieldAPI).getDescribe().getType();  
            String fieldValue = String.valueOf(fieldValueMap.get(fieldAPI)); 
            if(String.valueOf(fielddataType)=='DATE'){
                caseInfo.put(fieldAPI,(String.isBlank(fieldValue)||String.isEmpty(fieldValue))? null:Date.valueOf(fieldValue.replace('/', '-')));              
                // caseInfo.put(fieldAPI, Date.valueOf(String.valueOf(fieldValueMap.get(fieldAPI)).replace('/', '-')));
            }else if(String.valueOf(fielddataType)=='DATETIME'){
                if(String.isNotBlank(fieldValue)&&fieldValue.contains('T')){
                    fieldValue = fieldValue.replace('T',' ');
                    caseInfo.put(fieldAPI, Datetime.valueOfGmt(fieldValue));
                }else{
                    caseInfo.put(fieldAPI, null);
                }  
                // String dt = String.valueOf(fieldValueMap.get(fieldAPI));
                // if(String.isNotBlank(dt)&&dt.contains('T')){
                //     dt = dt.replace('T',' ');
                //     caseInfo.put(fieldAPI, Datetime.valueOfGmt(dt));
                // }             
            // }else if(String.valueOf(fielddataType)=='Number'||String.valueOf(fielddataType)=='DOUBLE' ){
            //     caseInfo.put(fieldAPI, Decimal.valueOf(String.valueOf(fieldValueMap.get(fieldAPI))));
            }else if(String.valueof(fielddataType)=='CURRENCY'|| String.valueof(fielddataType)=='PERCENT'||String.valueOf(fielddataType)=='Number'||String.valueOf(fielddataType)=='DOUBLE' ){
                caseInfo.put(fieldAPI, (String.isBlank(fieldValue)||String.isEmpty(fieldValue))?null:Decimal.valueOf(fieldValue.replace(',', ''))); 
            } else if(String.valueof(fielddataType)=='BOOLEAN'){
                caseInfo.put(fieldAPI, fieldValueMap.get(fieldAPI));
            }else {
                caseInfo.put(fieldAPI, String.valueOf(fieldValueMap.get(fieldAPI)));
            }                  
        }

        System.debug('caseInfo='+caseInfo);
        System.debug('caseInfo.Account__c='+caseInfo.Account__c);
        if (!String.isBlank(caseInfo.ContactId) && (String.isBlank(caseInfo.Account__c) || Id.valueOf(caseInfo.Account__c).to15() =='000000000000000')) {
            if (Id.valueOf(caseInfo.ContactId).to15() !='000000000000000') {
                Contact c = [select id,AccountId from Contact where id = :caseInfo.ContactId];
                caseInfo.Account__c = c.AccountId;
            }
        }
        
        //2. Save Record Process
        String status = 'success';    
        Response resp = new Response();
        Savepoint sp = Database.setSavepoint();
        String rid = '';
        String awsDataId = '';
        String sfRecordId = '';
        Boolean isClone = false;
        try{
            System.debug('abcde');
            awsDataId = (String)caseInfo.get('AWS_Data_Id__c');
            sfRecordId = (String)caseInfo.get('Id');
            System.debug('awsDataId = ' + awsDataId);
            Case[] cases = [select id from Case where AWS_Data_Id__c =:awsDataId or id =:sfRecordId];

            if(!isNew){
                isClone = cases.size() == 0;
            }
            system.debug('isClone'+isClone + ' isNew'+isNew);
            if(isNew || isClone){
                System.debug('caseInfozhj = ' + caseInfo);
                if(!Test.isRunningTest()){
                    insert caseInfo;
                }
            }else{
                System.debug('into update');
                // String awsDataId = (String)caseInfo.get('AWS_Data_Id__c');
                // System.debug('awsDataId = ' + awsDataId);
                // Case[] cases = [select id from Case where AWS_Data_Id__c =:awsDataId];
                System.debug('cases ========================= ' + cases);
                System.debug('Cases[0].id = ' + cases[0].id);
                caseInfo.put('Id',cases[0].id);//For testing;
                if(!Test.isRunningTest()){
                    update caseInfo;
                }
            }
            rid=caseInfo.Id;
            PIHelper.saveTransLog(sobjectTypeValue,(String)caseInfo.get('AWS_Data_Id__c'),rid,transId,caseJson ,status,'');
            resp.recordId = caseInfo.Id;
            resp.message = '';
            resp.status = status;
            System.debug('resp from sfdx back-end' + resp);
            return resp;
        } catch(DmlException e) {
            Integer index = 0;
            System.debug(e.getNumDml());
            System.debug(e.getDmlFields(index));
            System.debug(e.getDmlId(index));
            System.debug(e.getDmlIndex(index));
            System.debug(e.getDmlMessage(index));
            System.debug(e.getDmlStatusCode(index));
            System.debug(e.getDmlType(index));
			system.debug(e.getMessage());
            system.debug(e.getStackTraceString());

            System.debug('into catch'+e.getMessage());
            Database.rollback(sp);
            resp.status = 'Exception';
            resp.message ='保存失败，原因:'+ e.getDmlMessage(index);
            PIHelper.saveTransLog(sobjectTypeValue,(String)caseInfo.get('AWS_Data_Id__c'),rid,transId, caseJson ,status,e.getMessage()+e.getStackTraceString());
            return resp;
            
        }catch(Exception e) {
            System.debug('into catch'+e.getMessage());
            Database.rollback(sp);
            status = 'fail';
            PIHelper.saveTransLog(sobjectTypeValue,(String)caseInfo.get('AWS_Data_Id__c'),rid,transId,caseJson,status,e.getMessage());
            resp.message = e.getMessage();            
            resp.status = status;
            return resp;
        }
    }

    public static void AssignValueFromUrl(Map<string,string> mso, sobject sobj){
        
        String sobject_name = sobj.getSObjectType().getDescribe().getName();
        Map<string,object> temp = new Map<string,object>();
        Map<string,FieldDefinition> fdm = new Map<string,FieldDefinition>();
        List<FieldDefinition> fds = [SELECT Id, DurableId, QualifiedApiName,ValueTypeId , EntityDefinitionId, NamespacePrefix,EntityDefinition.NamespacePrefix, DeveloperName, MasterLabel, Label FROM FieldDefinition where EntityDefinition.QualifiedApiName = :sobject_name];
        for(FieldDefinition fd : fds){
            //system.debug(fd.DurableId);
            fdm.put(fd.DurableId.split('\\.')[1],fd);
        }
        
        for(string key : mso.keySet()){
            if (key.toLowerCase() == 'id') {
                System.debug('skip id assign');
                continue;
            }
            string new_key = key;
            system.debug('new_key='+new_key);
            if(new_key.contains('_lkid')){
                new_key = new_key.replace('_lkid', '');
                new_key = new_key.substring(2);
            }else{
                if(temp.containsKey(new_key)){
                    continue;
                }
            }
            
            system.debug('now new_key='+new_key);
            if(fdm.containsKey(new_key)){
                system.debug('fdm.get(new_key)='+fdm.get(new_key));
                string val_str = mso.get(key);
                system.debug('val_str='+val_str);
                /*无需做decode，sf内部已经做好
                try{
                    val_str = EncodingUtil.urlDecode(mso.get(key),'UTF-8');
                }catch(Exception e){
                    continue;
                    system.debug('Exception from get Key:'+e.getMessage());
                    system.debug(e.getStackTraceString());
                } */             
                object val = null;
                string type_id = fdm.get(new_key).ValueTypeId;
                // address, boolean, date, datetime, double, id, location, string, time
                if(string.isBlank(val_str)){
                    val = null;
                }else if(type_id == 'boolean'){
                    if(val_str == '1'){
                        val = true;
                    }else{
                        val = boolean.valueOf(val_str);
                    }
                }else if(type_id == 'date'){
                    //
                   	try{
                        val = date.parse(val_str);
                    }catch(Exception e){
                        system.debug('val_str='+val_str);
                        system.debug(e.getMessage());
                        system.debug(e.getStackTraceString());
                        try{
                            val = date.valueOf(val_str);
                        }catch(Exception ee){
                            system.debug('val_str='+val_str);
                            system.debug(ee.getMessage());
                            system.debug(ee.getStackTraceString());
                            continue;
                        }
                    }
                }else if(type_id == 'datetime'){
                    //
                   	try{
                        val = datetime.parse(val_str);
                    }catch(Exception e){
                        system.debug('val_str='+val_str);
                        system.debug(e.getMessage());
                        system.debug(e.getStackTraceString());
                        try{
                            val = datetime.valueOf(val_str);
                        }catch(Exception ee){
                            system.debug('val_str='+val_str);
                            system.debug(ee.getMessage());
                            system.debug(ee.getStackTraceString());
                            continue;
                        }
                    }
                }else if(type_id == 'double' || type_id == 'number'){
                    try{
                        val = decimal.valueOf(val_str.replace(',', ''));
                    }catch(Exception ee){
                        system.debug('val_str='+val_str);
                        system.debug(ee.getMessage());
                        system.debug(ee.getStackTraceString());
                        continue;
                    }
                    
                }else if(type_id == 'id' || type_id == 'string'){
                    val = val_str;
                }else{
                    system.debug('type_id='+type_id+' is not support to convert');
                    continue;
                }
                temp.put(fdm.get(new_key).QualifiedApiName,val);
            }else{
                system.debug(key+' is not in fdm');
            }
        }
        
        for(string key : temp.keySet()){
            system.debug('assign '+key+'='+temp.get(key));
            try{
                sobj.put(key, temp.get(key));
            }catch(Exception e){
                system.debug(e.getMessage());
                system.debug(e.getStackTraceString());
            }
        }
    }
}