/*
 * Author: Yanan Chen
 * Created Date: 02/08/2022
 * Purpose: Utility class for describe layouts
 * Test Class: NewAndEditAddressController
 * History: 
 *      02/08/2022 - Yanan Chen - Initial Code.
 * 
 * */
global without sharing class NewAndEditAddressController {
    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 = 'Address__c';
    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 String CurrentUserId{private set; get;}
    // public String CurrentUserName{private set; get;}
    public NewAndEditAddressController(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('Address__c').getDescribe().fields.getMap().keyset());  
        // Add fields to controller. This is to avoid the SOQL error in visualforce page
        if (!Test.isRunningTest()) { 
            controller.addFields(fieldList);
        }
        Map<string,string> mso = ApexPages.currentPage().getParameters();
        if(mso != null && mso.containsKey('newclone')){
            isCloneMode = true;
        }
        SObject obj = controller.getRecord();        
        if(obj.Id != null){
            //更新
            isNewMode = false;
            Address__c addressData = [select Id, RecordTypeId, AWS_Data_Id__c, Contacts__r.Id, Contacts__r.AWS_Data_Id__c from Address__c where id =: obj.Id];
            rtTypeId = addressData.RecordTypeId;
            AWSDataId = addressData.AWS_Data_Id__c;
            Map<String,String> sfIdToAWSIdMap = new Map<String,String>();
            // if(addressData.Contacts__r.Id != null){
            //     sfIdToAWSIdMap.put(String.valueof(addressData.Contacts__r.Id).subString(0,15),addressData.Contacts__r.AWS_Data_Id__c);
            // }
            sfIdToAWSIdMap.put(String.valueof(addressData.Contacts__r.Id).subString(0,15),addressData.Contacts__r.AWS_Data_Id__c);
            contactsInfo = JSON.serialize(sfIdToAWSIdMap);
        }else{
            //新建
            rtTypeId = ApexPages.currentPage().getParameters().get('RecordType');
        }
        LayoutDescriberHelper.LayoutWrapper LayoutWrapperValue = LayoutDescriberHelper.describeSectionWithFieldsWrapper(rtTypeId, 'Address__c','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('Address__c');
        staticResource = JSON.serialize(piIntegration);
        staticResourceContact = JSON.serialize(PIHelper.getPIIntegrationInfo('Contact'));
        encryptedAPIList = piIntegration.PIFields;
        sobjectPrefix = piIntegration.sobjectPrefix;
        layoutSectionsStr = JSON.serialize(layoutSections);
        // CurrentUserName = UserInfo.getName();
        // CurrentUserId = UserInfo.getUserId();
    }
    
    global class Response{
        public String recordId{set;get;}
        public String message{set;get;}
        public String status{set;get;}
    }

    @RemoteAction
    global static Response saveAddress(String addressJson,String transId,Boolean isNew) {
        System.debug('Address Info:' + JSON.serialize(addressJson));
        //1. Prepare the payload for  Address
        Schema.SObjectType addressSchema = schemaMap.get(sobjectTypeValue);
        Map<String, Schema.SObjectField> fieldAPIToTypeMap = addressSchema.getDescribe().fields.getMap();
        Map<String,Object> fieldValueMap = (Map<String,Object>)JSON.deserializeUntyped(addressJson);
        Address__c addressInfo = new Address__c();
        //自定义格式转换
        for (String fieldAPI: fieldValueMap.keySet()) {
            system.debug('field API'+fieldAPI);
            Schema.DisplayType fielddataType = fieldAPIToTypeMap.get(fieldAPI).getDescribe().getType();  
            String fieldValue = String.valueOf(fieldValueMap.get(fieldAPI)); 
            if(!fieldAPIToTypeMap.containskey(fieldAPI)){
                continue;
            }
            if(String.valueOf(fielddataType)=='DATE'){
                addressInfo.put(fieldAPI,(String.isBlank(fieldValue)||String.isEmpty(fieldValue))? null:Date.valueOf(fieldValue.replace('/', '-')));              
            }else if(String.valueOf(fielddataType)=='DATETIME'){
                String dt = String.valueOf(fieldValueMap.get(fieldAPI));
                if(String.isNotBlank(dt)&&dt.contains('T')){
                    dt = dt.replace('T',' ');
                    addressInfo.put(fieldAPI, Datetime.valueOfGmt(dt));
                }else if(String.isNotBlank(fieldValue))  {
                    fieldValue = fieldValue.replace('/', '-') + ':00';
                    addressInfo.put(fieldAPI, Datetime.valueOf(fieldValue));
                }else{
                    addressInfo.put(fieldAPI,fieldValue);
                }             
            }else if(String.valueOf(fielddataType)=='Number'||String.valueOf(fielddataType)=='DOUBLE' ){
                addressInfo.put(fieldAPI, (String.isBlank(fieldValue)||String.isEmpty(fieldValue))?null:Decimal.valueOf(fieldValue.replace(',', ''))); 
            } else if(String.valueof(fielddataType)=='BOOLEAN'){
                addressInfo.put(fieldAPI, fieldValueMap.get(fieldAPI));
            }else {
                addressInfo.put(fieldAPI, String.valueOf(fieldValueMap.get(fieldAPI)));
            }                  
        }

        //2. Save Record Process
        String status = 'success';    
        Response resp = new Response();
        Savepoint sp = Database.setSavepoint();
        Boolean isClone = false;
        // String rid = '';
        String awsDataId = '';
        try{
            System.debug('abcde');
            awsDataId = (String)addressInfo.get('AWS_Data_Id__c');
            System.debug('awsDataId = ' + awsDataId);
            Address__c[] addresses = [select id from Address__c where AWS_Data_Id__c =:awsDataId];
            if(!isNew){
                isClone = addresses.size() == 0;
            }
            System.debug('isClone---------'+isClone);
            if(isNew || isClone){
                System.debug('addressInfoNancy = ' + addressInfo);
                insert addressInfo;
            }else{
                System.debug('into update');
                // awsDataId = (String)addressInfo.get('AWS_Data_Id__c');
                // System.debug('awsDataId = ' + awsDataId);
                // Address__c[] addresses = [select id from Address__c where AWS_Data_Id__c =:awsDataId];
                System.debug('addresses[0].id = ' + addresses[0].id);
                addressInfo.put('Id',addresses[0].id);//For testing;
                update addressInfo;
            }
            // rid=addressInfo.Id;
            resp.recordId = addressInfo.Id;
            // resp.message = 'success saveAddress';
            resp.status = status;
            PIHelper.saveTransLog(sobjectTypeValue, awsDataId, addressInfo.Id, transId, addressJson , 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, awsDataId, addressInfo.Id, transId, addressJson, status, e.getMessage()+e.getStackTraceString());
            return resp;
            
        }catch(Exception e) {
            System.debug('into catch'+e.getMessage());
            Database.rollback(sp);
            // status = 'Exception';     
            // resp.status = status;
            resp.status = 'Exception';
            resp.message = e.getMessage()+e.getStackTraceString();       
            PIHelper.saveTransLog(sobjectTypeValue, awsDataId, addressInfo.Id, transId, addressJson, status, resp.message);
            // PIHelper.saveTransLog(sobjectTypeValue,(String)addressInfo.get('AWS_Data_Id__c'),rid,transId,addressJson,status,e.getMessage());
            return resp;
        }
    }
}