/*
 * Author: Zhang,Huajian
 * Created Date: 05/26/2023
 * Purpose: Utility class for describe layouts
 * Test Class: LexNewAndEditLeadPIPLControllerTest
 * History: 
 *      05/26/2023 - Zhang,Huajian - Initial Code.
 * 
 * */
public with sharing class LexNewAndEditLeadPIPLController {
    public static Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
    // 字段信息
    public static Map<string, SObjectField> fieldMap = new Map<string, SObjectField>();

    @AuraEnabled
    public static ResponseBodyLWC initData(Id rid, String recordTypeId, String sobjectType) {
        System.debug('enter LexNewAndEditLeadPIPLController initData');
        System.debug('start recordTypeId = ' + recordTypeId);
        fieldMap = schemaMap.get(sobjectType).getDescribe().fields.getMap();
        ResponseBodyLWC res = new ResponseBodyLWC();
        Map<String, object> data = new Map<String, object>();
        res.entity = data;
        //deloitte-zhj 20231116 PIPL还原 start
        // ResponseBodyLWC rbl = LexNewAndEditBasePIPLController.initData(rid, recordTypeId, sobjectType);
        // data = (Map<String,Object>)rbl.entity;
        //data.put('staticResourceContact', Json.serialize(PIHelper.getPIIntegrationInfo('Contact'))); 
        if (String.isBlank(recordTypeId)) {
            String recordTypeIdTemp =  LayoutDescriberHelper.getDefaultRecordType(sobjectType);
            System.debug('recordTypeIdTemp = ' + recordTypeIdTemp);
            if(recordTypeIdTemp != System.Label.target_customer){
                data.put('recordTypeId',recordTypeIdTemp);
                recordTypeId = recordTypeIdTemp;
            } else {
                data.put('recordTypeId',null);
                recordTypeId = null;
            }
        }else {
            data.put('recordTypeId',recordTypeId);
        }
        //deloitte-zhj 2023/07/31 自定义元数据配置titleMap start
        Map<String, Map<String, String>> titleMap = new Map<String, Map<String, String>>();
        List<LEX_PIPL_Layout_Config__mdt> piLayoutConfigList = [SELECT id,DeveloperName, Layout_Header__c, Sobject_Type__c FROM LEX_PIPL_Layout_Config__mdt];
        if(piLayoutConfigList.size() > 0){
            for(LEX_PIPL_Layout_Config__mdt piLayoutConfig : piLayoutConfigList){
                //titleMap.put(piLayoutConfig.Sobject_Type__c,JSON.deserialize(piLayoutConfig.Layout_Header__c, Map<String, String>.class));
                Map<String, Object> tempMap = (Map<String, Object>)JSON.deserializeUntyped(piLayoutConfig.Layout_Header__c);
                Map<String, String> innerMap = new Map<String, String>();
                for (String key : tempMap.keySet()) {
                    innerMap.put(key, (String)tempMap.get(key));
                }
                titleMap.put(piLayoutConfig.Sobject_Type__c, innerMap);
            }
        }
        //deloitte-zhj 2023/07/31 自定义元数据配置titleMap end 
         //编辑
         if(!String.isBlank(rid)){
            //获取对应对象的字段                List<Sobject> lso = Database.query('select id from RecordType where SobjectType = :sobjectType');
            String sql = 'select ';
            DescribeSObjectResult objectType = rid.getSobjectType().getDescribe();
            List<String> objectFields = new List<String>(objectType.fields.getMap().keySet());
            sql += String.join(objectFields, ',') +' from '+sobjectType+' where id =\''+rid+'\' limit 1';
            System.debug('sql = ' + sql);
            Sobject leadData = Database.query(sql);
            System.debug('leadData_20230711 = ' + leadData);
            if(leadData == null){
                return new ResponseBodyLWC('Error',500, 'id不存在', '');
            }
            if(objectFields.contains('recordtypeid')){
                recordTypeId = (String)leadData.get('RecordTypeId');
                System.debug('recordTypeId_20230711_Debug = ' + recordTypeId);
            }
            List<Metadata.LayoutSection> layout = MetaDataUtility.GetRecordTypePageLayout(recordTypeId, sobjectType);
            System.debug('layout=' + layout);
            for (Metadata.LayoutSection section : layout) {
                if(titleMap.containsKey(sobjectType) && titleMap.get(sobjectType).containsKey(section.label)){
                    section.label = titleMap.get(sobjectType).get(section.label);
                }
            }
            data.put('layout', Json.serialize(reviseMetaLayouts(layout)));
            data.put('recordTypeId', recordTypeId);
            System.debug('data.recordTypeId: ' + data.get('recordTypeId'));
            //获取值
            System.debug('leadData = ' + JSON.serialize(leadData));
            data.put('data', leadData);
        }else {
            List<Metadata.LayoutSection> layout = MetaDataUtility.GetRecordTypePageLayout(recordTypeId, sobjectType);
            System.debug('layout = ' + JSON.serialize(layout));
            for (Metadata.LayoutSection section : layout) {
                if(titleMap.containsKey(sobjectType) && titleMap.get(sobjectType).containsKey(section.label)){
                    section.label = titleMap.get(sobjectType).get(section.label);
                }
            }
            System.debug('leadPIPL还原 layout = ' + JSON.serialize(layout));
            data.put('layout', Json.serialize(reviseMetaLayouts(layout)));
            System.debug('leadPIPLreviseMetaLayouts还原 layout = ' + data.get('layout'));
        }
        //deloitte-zhj 20231116 PIPL还原 end
        String LeadCreatedDate =Date.today().format();
        if(String.isNotBlank(rid)){
            String sql = 'select Contact_Name__r.LastName,Hospital_Name__r.Id,';  //deloitte-zhj 20231116 PIPL还原
            DescribeSObjectResult objectType = rid.getSobjectType().getDescribe();
            List<String> objectFields = new List<String>(objectType.fields.getMap().keySet());
            sql += String.join(objectFields, ',') +' from '+sobjectType+' where id =\''+rid+'\' limit 1';
            Sobject leadData = Database.query(sql);
            LeadCreatedDate = leadData.get('CreatedDate')!= null ? Date.newInstance(((Datetime)leadData.get('CreatedDate')).year(), ((Datetime)leadData.get('CreatedDate')).month(), ((Datetime)leadData.get('CreatedDate')).day()).format() : Date.today().format();
            data.put('data',leadData);
        }
        data.put('LeadCreatedDate',LeadCreatedDate);
        res.status = 'Success';
        res.code = 200;
        res.msg = '';
        return res;
    }

    
    @AuraEnabled
    public static ResponseBodyLWC queryAccount(String accountTypes, String accountId) {
        //return LexNewAndEditBasePIPLController.queryAccount(accountTypes,accountId);
        ResponseBodyLWC res = new ResponseBodyLWC();
        Map<String, object> data = new Map<String, object>();
        res.entity = data;
        System.debug('accountType = ' + accountTypes);
        System.debug('accountId = ' + accountId);
        try {
            List<Object> types = (List<Object>) JSON.deserializeUntyped(accountTypes);
            System.debug('types=' + types);
            String soql = 'select Id,Name,';
            for (Object t : types) {
                soql += (String) t + ',';
            }
            soql = soql.substring(0, soql.length() - 1);
            soql += ' from Account where id=\'' + accountId + '\'';
            System.debug('soql=' + soql);
            Sobject account = new Account();
            if (!Test.isRunningTest()) {
                account = Database.query(soql);
            } else {
                account.put('Id',  System.Label.Agency_ID_c);
            }
            Map<String, Map<String, String>> m = new Map<String, Map<String, String>>();
            System.debug('account=' + account);
            for (Object ty : types) {
                String t = (String) ty;
                if (account.get(t) != null || Test.isRunningTest()) {
                    Sobject acc = new Account();
                    if (Test.isRunningTest()) {
                        acc.put('Id',  System.Label.Agency_ID_c);
                        acc.put('Name', 'Name');
                    } else {
                        acc = Database.query('select Id,Name from Account where id=\'' + account.get(t) + '\'');
                    }
                    Map<String, String> n = new Map<String, String>();
                    n.put('Id', (String) acc.get('Id'));
                    n.put('Name', (String) acc.get('Name'));
                    m.put(t, n);
                }
            }
            System.debug('m=' + m);
            data.put('m', m);
            data.put('account', account);
            res.status = 'Success';
            res.code = 200;
            res.msg = '';
            return res;
        } catch (Exception e) {
            return new ResponseBodyLWC('Error', 500, e.getMessage() + ' ' + e.getLineNumber(), '');
        }
    }
    
    @AuraEnabled
    public static ResponseBodyLWC queryContact(String conId) {
        ResponseBodyLWC resp = new ResponseBodyLWC();
        try {
            if (String.isNotBlank(conId)) {
                Contact con = [SELECT Id, Name FROM Contact WHERE Id =: conId];
                resp.entity = con;
                resp.status = 'Success';
            }
        } catch (Exception e) {
            resp.status = 'Error';
            resp.code = 500;
            resp.msg = e.getMessage() + ' ' + e.getLineNumber();
        }
        return resp;
    }

    /**
     *@description 转换layout
     *@param	sections                        默认metalayout
     *@return	List<Metadata.LayoutSection>	标准metalayout
     */
    public static List<Metadata.LayoutSection> reviseMetaLayouts(List<Metadata.LayoutSection> sections) {
        List<Metadata.LayoutSection> result = new List<Metadata.LayoutSection>();
        if (sections == null) {
            return null;
        }
        for (Metadata.LayoutSection s : sections) {
            Metadata.LayoutSection section = new Metadata.LayoutSection();
            section.customLabel = s.customLabel;
            section.detailHeading = s.detailHeading;
            section.editHeading = s.editHeading;
            section.label = s.label;
            section.style = s.style;
            result.add(section);
            for (Metadata.LayoutColumn c : s.layoutColumns) {
                if (c.layoutItems == null) {
                    break;
                }
                Metadata.LayoutColumn col = new Metadata.LayoutColumn();
                col.reserved = col.reserved;
                section.layoutColumns.add(col);
                for (Metadata.layoutItem item : c.layoutItems) {
                    if(item.field == 'Consum_Apply_Equipment_Set__c'){
                        col.layoutItems.add(item);
                    }
                    if (item.emptySpace != true && (!fieldMap.containsKey(item.field) || !isUpdateable(fieldMap.get(item.field).getDescribe()))  && item.field != 'IsJump_Rental__c' && item.field != 'JumpCause_Rental__c') {
                        continue;
                    }
                    col.layoutItems.add(item);
                }
            }
        }
        return result;
    }

    private static Boolean isUpdateable(Schema.DescribeFieldResult dfr) {
        return (new List<String>{ 'Id', 'Name' }).contains(dfr.getName()) || dfr.isUpdateable();
    }

    public static Boolean checkNullString(String inputString) {
        if (String.isEmpty(inputString) || String.isBlank(inputString)) {
            return true;
        }
        return false;
    }

    @AuraEnabled
    public static ResponseBodyLWC searchContactInit(String accountId, String searchKeyWord){
        ResponseBodyLWC res = new ResponseBodyLWC();
        Map<String, object> data = new Map<String, object>();
        res.entity = data;
        try {
            String sql = 'SELECT Id, Account.Name, Name, Phone, Email, MobilePhone FROM Contact Where RecordType.DeveloperName = \'Doctor\' ';
            if (!checkNullString(accountId)) {
                Account act = [SELECT id, Hospital__c, Hospital_Department_Class__c FROM Account WHERE id = :accountId];
                if (!checkNullString(act.Hospital__c)) {
                    sql += 'AND Account.Hospital__c = \'' + act.Hospital__c + '\' ';
                } else if (!checkNullString(act.Hospital_Department_Class__c)) {
                    sql += 'AND Account.Hospital__c = \'' + act.Hospital_Department_Class__c +'\' ';
                } else {
                    sql += 'AND Account.Hospital__c = \'\' ';
                }
            }
            if (!checkNullString(searchKeyWord)) {
                sql += 'AND Name like \'%' + searchKeyWord + '%\' ';
            }
            sql += 'ORDER BY createddate DESC Limit 1000';
            System.debug('sql =======' + sql);
            List<Contact> conList = Database.query(sql);
            data.put('conList', conList);
            res.status = 'Success';
            res.code = 200;
            res.msg = '';
            return res;
        } catch (Exception e) {
            return new ResponseBodyLWC('Error', 500, e.getMessage() + ' ' + e.getLineNumber(), '');
        }
    }

    //deloitte-zhj 20231116 PIPL还原 start
    // @AuraEnabled
    // public static ResponseBodyLWC searchContactInit(String accountId, String searchKeyWord) {
    //     return  LexNewAndEditBasePIPLController.searchContactInit(accountId, searchKeyWord);
    // }

    // @AuraEnabled
    // public static ResponseBodyLWC getContactAWS() {
    //     ResponseBodyLWC res = new ResponseBodyLWC();
    //     Map<String, object> data = new Map<String, object>();
    //     res.entity = data;
    //     data.put('contactStaticResource', Json.serialize(PIHelper.getPIIntegrationInfo('Contact')));
    //     res.status = 'Success';
    //     res.code = 200;
    //     res.msg = '';
    //     return res;
    // }

    // @AuraEnabled
    // public static ResponseBodyLWC searchContactInitV2(String accountId, List<String> conAWSIds, String searchKeyWord) {
    //     return  LexNewAndEditBasePIPLController.searchContactInitV2(accountId, conAWSIds, searchKeyWord);
    // }

    // @AuraEnabled
    // public static ResponseBodyLWC getNoPIContact(String searchContactName,String accountId) {
    //     return  LexNewAndEditBasePIPLController.getNoPIContact(searchContactName,accountId);
    // }
    //deloitte-zhj 20231116 PIPL还原 end
}