/**
 * 2023-04-14  
 * Lightning new Repair
 */
public with sharing class lexNewRepairAuraController {
    public static String sobjectTypeValue = 'Repair__c';
    //查询Repair数据  修理对象的new和update 
    @AuraEnabled
    public static ReturnData init(String recordId,String urlStr) {
        ReturnData res = new ReturnData();
        String sobjectId = [SELECT CustomObjectId,CustomObjectName  FROM CustomObjectUserLicenseMetrics   where CustomObjectName ='Repair' limit 1].CustomObjectId;
        String Input_Required_Field_Msg = Label.Input_Required_Field_Msg;
        String PIPL_Name_Label = Label.PIPL_Name_Label;
        String PIPL_Input_Account_Error_Msg = label.PIPL_Input_Account_Error_Msg;
        Map<string,string> mso = (Map<string,string>)JSON.deserialize(urlStr, Map<string,string>.class);
        system.debug('mso='+mso);
        if (recordId != null) {
            res.recordTypeId = [SELECT Id,RecordTypeId FROM Repair__c WHERE Id = :recordId].RecordTypeId;
            res.status = true;
        }
        String RepairSubOrderAWSDataId;
            // AssignValueFromUrl(mso,controller.getRecord());
            //通过id查      问题
            //PIPL zhj 2022-11-11 start
            //从报修子单过来00N10000009H1rR
        if (mso.containsKey('CF00N10000009H1rR_lkid')) {
            String repairSubOrderId = mso.get('CF00N10000009H1rR_lkid');
            System.debug('repairSubOrderId = ' + repairSubOrderId);
            //查询AWSDataId
            List<RepairSubOrder__c> rso = [select AWS_Data_Id__c from RepairSubOrder__c where Id=:repairSubOrderId];
            if(rso.size() > 0){
                //todo 从报修子单过来，需要解密报修人  lwc是否需要进行解密处理？
               RepairSubOrderAWSDataId = rso[0].AWS_Data_Id__c;
               res.AWS_Data_Id = rso[0].AWS_Data_Id__c;
               res.status = true;
            }
        }
        //PIPL zhj 2022-11-11 end
        List<Repair__c> rc = new List<Repair__c>();
        system.debug('retURL=' + mso.containsKey('retURL'));
        if (mso.containsKey('retURL')) {
            String RepairId = mso.get('retURL').substring(1);
            System.debug('RepairId = ' + RepairId);
            rc = [select Hospital__c,Department_Class__c,Account__c,Dealer__c,Incharge_Staff_Contact__c,Incharge_Staff__c,  RepairSubOrder__c,On_Call_ID__c,QIS_ID__c,  InsReport__c,Rental_Apply_Equipment_Set_Detail__c from Repair__c where id =:RepairId ];
            System.debug('rc = ' + rc);
            if(rc.size() > 0){
                //已有数据赋值
                 //医院
                res.Hospital = rc[0].Hospital__c;
                //战略科室分类
                res.Department_Class = rc[0].Department_Class__c;
                //科室
                res.Account = rc[0].Account__c;
                //经销商名
                res.Dealer = rc[0].Dealer__c;
                //修理委托者（员工）
                res.Incharge_Staff_Contact = rc[0].Incharge_Staff_Contact__c;
                //修理委托者(FSE)
                res.Incharge_Staff = rc[0].Incharge_Staff__c;
                //报修子单RepairSubOrder__c
                res.RepairSubOrder = rc[0].RepairSubOrder__c;
                //查询AWSDataId
                List<RepairSubOrder__c> rso = [select AWS_Data_Id__c from RepairSubOrder__c where Id=:rc[0].RepairSubOrder__c];
                if(rso.size() > 0){
                    RepairSubOrderAWSDataId = rso[0].AWS_Data_Id__c;
                    res.AWS_Data_Id = rso[0].AWS_Data_Id__c;
                }
                //On-Call号码On_Call_ID__c
                res.On_Call_ID = rc[0].On_Call_ID__c;
                //QIS号码QIS_ID__c
                res.QIS_ID = rc[0].QIS_ID__c;
                //点检报告书InsReport__c
                res.InsReport = rc[0].InsReport__c;
                //借出备品配套一览明细Rental_Apply_Equipment_Set_Detail__c
                res.Rental_Apply_Equipment_Set_Detail = rc[0].Rental_Apply_Equipment_Set_Detail__c;

                res.status = true;
            }
           
        }
        //2023/04/23  lwc的保存并新建 保存后刷新页面
        // PIHelper.PIIntegration piIntegration = PIHelper.getPIIntegrationInfo('Repair__c');
        // PIHelper.PIIntegration piIntegrationAddress = PIHelper.getPIIntegrationInfo('Address__c');
        // PIHelper.PIIntegration piIntegrationContact = PIHelper.getPIIntegrationInfo('Contact');
        // PIHelper.PIIntegration piIntegrationRepairSubOrder = PIHelper.getPIIntegrationInfo('RepairSubOrder__c');
        // String staticResource = JSON.serialize(piIntegration);
        // //zhj MEBG新方案改造 2022-11-29 start
        // String staticResourceV2 = JSON.serialize(PIHelper.getPIIntegrationInfo('Repair__cV2'));
        // //zhj MEBG新方案改造 2022-11-29 end
        // String staticResourceAddress = JSON.serialize(piIntegrationAddress);
        // String staticResourceContact = JSON.serialize(piIntegrationContact);
        // String staticResourceRepairSubOrder = JSON.serialize(piIntegrationRepairSubOrder);
        // List<String> encryptedAPIList = piIntegration.PIFields;
        // String sobjectPrefix = piIntegration.sobjectPrefix;

        //save and new url   page处保存并新建跳转地址：new?recordTypeId=01210000000QmS9&additionalParams=retURL%3D%252Fa0J%252Fo%26&count=1
        // String newUrl = '/setup/ui/recordtypeselect.jsp?ent=' + sobjectId + '&retURL=/' + sobjectPrefix + '/o&save_new_url=/' + sobjectPrefix + '/e?retURL=%2F' + sobjectPrefix + '%2Fo';
        // res.newUrl = newUrl;

        return res;
    }

    public static String getAllFieldNames(String objName){
        Map <String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
        List<Schema.sObjectField> fields = schemaMap.get(objName).getDescribe().fields.getMap().values();
        
        String fieldString = '';
        for( Schema.sObjectField field : fields ){
            fieldString += field + ',';
        }
        fieldString = fieldString.removeEnd(',');
        
        return fieldString;
    }

    // @AuraEnabled
    public static List <LayoutDescriberHelper.LayoutSection > init1(String recordId,String urlStr) {
        String sobjectId = [SELECT CustomObjectId,CustomObjectName  FROM CustomObjectUserLicenseMetrics   where CustomObjectName ='Repair' limit 1].CustomObjectId;
        Boolean isNewMode = true;
        String Input_Required_Field_Msg = Label.Input_Required_Field_Msg;
        String PIPL_Name_Label = Label.PIPL_Name_Label;
        String PIPL_Input_Account_Error_Msg = label.PIPL_Input_Account_Error_Msg;
        String rtTypeId;
        // String sobjecttypeForFrontEnd = sobjectTypeValue;
        //获取所有字段
        // List<String> fieldList = new List<String>(Schema.getGlobalDescribe().get('Repair__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);  
        // }
        // SObject obj = controller.getRecord();        
        if(recordId == ''){
            //更新  页面判断
            // isNewMode = false;
            Repair__c repairData = [select Id,RecordTypeId,AWS_Data_Id__c,Address_AWS_Data_Id__c,Contact_AWS_Data_Id__c,Address_Contacts_Encrypt__c,Address_Contacts_Name_Encrypt__c,Address_Telephone_Encrypt__c,Address_ZipCode_Encrypt__c,Detailed_Address_Encrypt__c from Repair__c where id =: recordId];
            rtTypeId = repairData.RecordTypeId;
            String AWSDataId = repairData.AWS_Data_Id__c;
            String DecryptAWSDataId = String.valueOf(repairData.Address_AWS_Data_Id__c);
            String ContactAWSDataId = String.valueOf(repairData.Contact_AWS_Data_Id__c);
        }else{
            //get url 参数
            // Map<string,string> mso = ApexPages.currentPage().getParameters();
            Map<string,string> mso = (Map<string,string>)JSON.deserialize(urlStr, Map<string,string>.class);
            system.debug('mso='+mso);
            // AssignValueFromUrl(mso,controller.getRecord());
            //通过id查      问题
            //PIPL zhj 2022-11-11 start
            //从报修子单过来00N10000009H1rR
            if (mso.containsKey('CF00N10000009H1rR_lkid')) {
                String repairSubOrderId = mso.get('CF00N10000009H1rR_lkid');
                System.debug('repairSubOrderId = ' + repairSubOrderId);
                //查询AWSDataId
                List<RepairSubOrder__c> rso = [select AWS_Data_Id__c from RepairSubOrder__c where Id=:repairSubOrderId];
                if(rso.size() > 0){
                   String RepairSubOrderAWSDataId = rso[0].AWS_Data_Id__c;
                }
            }
            //PIPL zhj 2022-11-11 end
            List<Repair__c> rc = new List<Repair__c>();
            system.debug('retURL=' + mso.containsKey('retURL'));
            if (mso.containsKey('retURL')) {
                String RepairId = mso.get('retURL').substring(1);
                System.debug('RepairId = ' + RepairId);
                rc = [select Hospital__c,Department_Class__c,Account__c,Dealer__c,Incharge_Staff_Contact__c,Incharge_Staff__c,  RepairSubOrder__c,On_Call_ID__c,QIS_ID__c,  InsReport__c,Rental_Apply_Equipment_Set_Detail__c from Repair__c where id =:RepairId ];
                System.debug('rc = ' + rc);
                if(rc.size() > 0){
                    //已有数据赋值  defaultValue
                     /*//医院
                    controller.getRecord().put('Hospital__c',rc[0].Hospital__c);
                    //战略科室分类
                    controller.getRecord().put('Department_Class__c',rc[0].Department_Class__c);
                    //科室
                    controller.getRecord().put('Account__c',rc[0].Account__c);
                    //经销商名
                    controller.getRecord().put('Dealer__c',rc[0].Dealer__c);
                    //修理委托者（员工）
                    controller.getRecord().put('Incharge_Staff_Contact__c',rc[0].Incharge_Staff_Contact__c);
                    //修理委托者(FSE)
                    controller.getRecord().put('Incharge_Staff__c',rc[0].Incharge_Staff__c);
                    //报修子单RepairSubOrder__c
                    controller.getRecord().put('RepairSubOrder__c',rc[0].RepairSubOrder__c);
                    //查询AWSDataId
                    List<RepairSubOrder__c> rso = [select AWS_Data_Id__c from RepairSubOrder__c where Id=:rc[0].RepairSubOrder__c];
                    if(rso.size() > 0){
                        RepairSubOrderAWSDataId = rso[0].AWS_Data_Id__c;
                    }
                    //On-Call号码On_Call_ID__c
                    controller.getRecord().put('On_Call_ID__c',rc[0].On_Call_ID__c);
                    //QIS号码QIS_ID__c
                    controller.getRecord().put('QIS_ID__c',rc[0].QIS_ID__c);
                    //点检报告书InsReport__c
                    controller.getRecord().put('InsReport__c',rc[0].InsReport__c);
                    //借出备品配套一览明细Rental_Apply_Equipment_Set_Detail__c
                    controller.getRecord().put('Rental_Apply_Equipment_Set_Detail__c',rc[0].Rental_Apply_Equipment_Set_Detail__c);*/
                }
               
            }
            
            // rtTypeId = ApexPages.currentPage().getParameters().get('RecordType');
            rtTypeId = mso.get('RecordType');
            if(String.isBlank(rtTypeId)||String.isEmpty(rtTypeId)){
                List<RecordType> rtList = new List<RecordType>([select Id,DeveloperName from RecordType  where SobjectType ='Repair__c' and DeveloperName ='Repair']);
                rtTypeId = rtList[0].Id;
            }
        }
        LayoutDescriberHelper.LayoutWrapper LayoutWrapperValue = LayoutDescriberHelper.describeSectionWithFieldsWrapper(rtTypeId, 'Repair__c','classic');
        List <LayoutDescriberHelper.LayoutSection > layoutSections = LayoutWrapperValue.layoutSections;
        String layoutSectionsStr = JSON.serialize(layoutSections); //for dynamic add readonly attribute
        List<String> requiredFieldAPIList = LayoutWrapperValue.requiredFieldAPIList;
        Map<String,String> fieldAPIToLabelMap = LayoutWrapperValue.fieldAPIToLabelMap;
        String requiredFieldAPIListStr = JSON.serialize(requiredFieldAPIList);
        String fieldAPIToLabelMapStr = JSON.serialize(fieldAPIToLabelMap);
        PIHelper.PIIntegration piIntegration = PIHelper.getPIIntegrationInfo('Repair__c');
        PIHelper.PIIntegration piIntegrationAddress = PIHelper.getPIIntegrationInfo('Address__c');
        PIHelper.PIIntegration piIntegrationContact = PIHelper.getPIIntegrationInfo('Contact');
        PIHelper.PIIntegration piIntegrationRepairSubOrder = PIHelper.getPIIntegrationInfo('RepairSubOrder__c');
        String staticResource = JSON.serialize(piIntegration);
        //zhj MEBG新方案改造 2022-11-29 start
        String staticResourceV2 = JSON.serialize(PIHelper.getPIIntegrationInfo('Repair__cV2'));
        //zhj MEBG新方案改造 2022-11-29 end
        String staticResourceAddress = JSON.serialize(piIntegrationAddress);
        String staticResourceContact = JSON.serialize(piIntegrationContact);
        String staticResourceRepairSubOrder = JSON.serialize(piIntegrationRepairSubOrder);
        List<String> encryptedAPIList = piIntegration.PIFields;
        String sobjectPrefix = piIntegration.sobjectPrefix;
        //获取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);
                }
            }
        }
        String VLookUpFieldsJson = Json.serialize(VLookUpFields);
        System.debug(LoggingLevel.INFO, '*** layoutSectionsLWC: ' + layoutSections);
        return layoutSections;
    }

    // 从url参数赋值到当前页面
    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());
            }
        }
    }

    public class RetrievalData {
        @AuraEnabled
        public String Status1;
        @AuraEnabled
        public String Status2;
        @AuraEnabled
        public String RepairName;
        @AuraEnabled
        public String SAPRepairNo;
        @AuraEnabled
        public String SerialNumber;
        @AuraEnabled
        public String onSiteRepair;
        @AuraEnabled
        public String workLocationSelect;
        @AuraEnabled
        public String State_Hospital;
        @AuraEnabled
        public String HospitalName;
        @AuraEnabled
        public Repair__c repair;

        public RetrievalData(){
            repair = new Repair__c();
        }
    }

    public class RepairData {
        @AuraEnabled
        public Boolean IFCheck;
        @AuraEnabled
        public Repair__c repair;
        public RepairData(Repair__c RepairInfo){
            IFCheck = null;
            repair = RepairInfo;
        }
    }
    //2023/04/18 返回查询结果和状态
    public class ReturnData {
        //判断是否有Repair的默认值
        @AuraEnabled
        public Boolean status;
        // @AuraEnabled
        // public Repair__c repair;
        //todo 报修人
        @AuraEnabled
        public String AWS_Data_Id;
        //医院
        @AuraEnabled
        public String Hospital;
        @AuraEnabled
        public String Department_Class;
        @AuraEnabled
        public String Account;
        @AuraEnabled
        public String Dealer;
        @AuraEnabled
        public String Incharge_Staff_Contact;
        @AuraEnabled
        public String Incharge_Staff;
        @AuraEnabled
        public String RepairSubOrder;
        @AuraEnabled
        public String On_Call_ID;
        @AuraEnabled
        public String QIS_ID;
        @AuraEnabled
        public String InsReport;
        @AuraEnabled
        public String Rental_Apply_Equipment_Set_Detail;
        @AuraEnabled
        public String recordTypeId;
        // @AuraEnabled
        // public String newUrl;

        public ReturnData(){
            this.status = false;
        }
    }
}