/**********************************************************************
 * 
 *
 * @url: /services/apexrest/NFM624RestAbout
 * @data:
 *  {
        
    }
*************************************************************************/
 
@RestResource(urlMapping = '/NFM624About/*')
global with sharing class NFM624RestAbout {
    
    private static final String LOG_TYPE = 'NFM624About';

    global class GeDatas {
        public NFMUtil.Monitoring Monitoring;
        public GeData[] GeData;
      }
  global class GeData{

         public String PersonManagementCode; //人员管理编码 
        public String HospitalManagementCode2; //医院平台编码  平台编码 PlatformCode__c
        public String DepartmentManagementCode2; //科室平台编码  平台编码 PlatformCode__c
        //public String Name; //姓名
        public String NameEncrypted;//姓名密文 add 20220215 
        public String RelatedHospital; //关联SFDC医院 客户管理编码(手写) AgentCode_Ext__c
        public String DepartmentClass; //战略科室
        public String DepartmentName; //所属科室
        public String RelatedDepartment; //关联SFDC科室 客户管理编码(手写) AgentCode_Ext__c
        //public Boolean AgentFlag; //经销商标识
      public String dataId;
        public String AccountName; //医院名
        public String MobileEncrypted; //电话密文 add 20220519 thh
    }



    global class Response {
        public List<ResponseDetail> ResponseDetails {get;set;}
    }
   
    global class ResponseDetail{
      public String  dataId;
      public String  awsDataId; //=CONTACT.AWS_Data_Id__c
      public String  sfId;
    }  
 
    @HttpPost
    global static void execute() {
 
        // 取得接口传输内容
        String strData = RestContext.request.requestBody.toString();
        GeDatas ges = (GeDatas) JSON.deserializeStrict(strData, GeDatas.class);
        system.debug('ges---'+JSON.serialize(ges) );
 
        if (ges == null) {
            return;
        }
 
        NFMUtil.Monitoring Monitoring = ges.Monitoring;
        if (Monitoring == null) {
            system.debug('monitoring62');
            return;
        }
        
        String result;
        try {
            BatchIF_Log__c rowData = NFMUtil.saveRowData(Monitoring, LOG_TYPE, ges.GeData);
            system.debug('rowData = '+rowData);
            system.debug('String.isBlank(rowData.Log__c) == false?');
            if (String.isBlank(rowData.Log__c) == false) {
             System.debug('进入if方法，成功调用executefuture');
                result = JSON.serialize(main(rowData.Id));
                system.debug('result'+result);
             // result main(rowData.Id);
            }
        } catch (Exception ex) {
            System.debug(Logginglevel.ERROR, LOG_TYPE + ':' + ex.getMessage());
            System.debug(Logginglevel.ERROR, LOG_TYPE + ':' + ex.getStackTraceString());
        }
        // BatchIF_Log__c rowData = NFMUtil.saveRowData(Monitoring, LOG_TYPE, ges.GeData);
        
 
        // JSONを戻す
        RestResponse res = RestContext.response;
        res.addHeader('Content-Type', 'application/json');
        res.statusCode = 200;
        //  NFMUtil.NFMResponse result = NFMUtil.getNFMResponse();
        //  result.SFStatus=SFStatus;
        //  result.SFMessage=SFMessage;
        String jsonResponse = result;
        //for test sushanhu 20220401 start
        //ResponseDetail red =new ResponseDetail();
        // red.dataId =ges.[0].dataId;
        //red.awsDataId ='959174215334887424';
        //red.sfId ='0031m00000N7leyAAB';
        // Response resp =new Response();
        // List<ResponseDetail> listName = new List<ResponseDetail>();
        // listName.add(red);
        // resp= (Response)listName;
        //for test sushanhu 20220401 end
        //String jsonResponse = '{"dataID": ""}';        
        //system.debug('result---'+jsonResponse);
        res.responseBody = blob.valueOf(jsonResponse);//need
        //String resp ='{"ResponseDetails":[{"dataId":"959573117074669568","awsDataId":"959174215334887424","sfId":"0031m00000N7leyAAB"}]}';
        //res.responseBody = blob.valueOf(resp);
        

         //updata response toAWS 20220225 sushanhu end
        return;
    }
 
 
    @future
    global static void executefuture(String rowData_Id) {
        system.debug('进入executefuture方法' + rowData_Id);
        main(rowData_Id);
    }
 
    global static Response main(String rowData_Id) {
        Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
        BatchIF_Log__c rowData = [Select Id, Name, Log__c,Is_Error__c, ErrorLog__c, Log2__c, Log3__c, Log4__c, Log5__c, Log6__c, Log7__c, Log8__c, Log9__c, Log10__c, Log11__c, Log12__c, MessageGroupNumber__c, retry_cnt__c,NFM624_Secondary_processing__c  from BatchIF_Log__c where RowDataFlg__c = true and Id =: rowData_Id];
        String logstr = rowData.MessageGroupNumber__c + ' start\n';
        BatchIF_Log__c iflog = new BatchIF_Log__c();
        iflog.Type__c = LOG_TYPE;
        iflog.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
        iflog.Log__c = logstr;
        iflog.ErrorLog__c = '';
        insert iflog;
        String rowDataStr = NFMUtil.getRowDataStr(rowData);
        List < GeData > GeDataList = (List < GeData > ) JSON.deserialize(rowDataStr, List < GeData > .class);
        // if (GeDataList == null || GeDataList.size() == 0) {
        //     return null;
        // }
        Savepoint sp = Database.setSavepoint();
        List < string > PersonManagementCodeList = new List < String > (); //人员管理编码List
        List < String > SFDCCodeList = new List < String > (); 
        List < String > ManagementList = new List < String > (); //医院、科室平台编码List
        List < String > NameList = new List < String >();
        Response responseList = new Response();//返回体List
        ResponseDetail red = new ResponseDetail();
        responseList.ResponseDetails = new List<ResponseDetail>(); 
        try { 
        //根据传过来的管理编码查询如果可以查询得到结果则更新，查询不到则新增
        // for(GeData gedata : GeDataList){
        //     ResponseDetail temp = new ResponseDetail();
        //     temp.dataID = gedata.dataID;
        //     temp.awsDataId = null;
        //     temp.sfId = null;
        //     responseList.ResponseDetails.add(temp);
        // }
             //根据传过来的管理编码查询如果可以查询得到结果则更新，查询不到则新增
             List < Gedata > newGeDataList = new List < Gedata > ();
             for (Gedata gedata: GeDataList) {
                system.debug('gedata.NameEncrypted'+gedata.NameEncrypted);
                red.dataID = gedata.dataID;
                red.awsDataId = null;
                red.sfid = null;
                 if(string.isnotblank(gedata.HospitalManagementCode2)){
                     ManagementList.add(gedata.HospitalManagementCode2);
                 }
                 if(string.isnotblank(gedata.DepartmentManagementCode2)){
                     ManagementList.add(gedata.DepartmentManagementCode2);
                 }
                 if (string.isnotblank(gedata.RelatedHospital)) {
                     SFDCCodeList.add(gedata.RelatedHospital);
                 }
                 if (string.isnotblank(gedata.RelatedDepartment)) {
                     SFDCCodeList.add(gedata.RelatedDepartment);
                 }
                 if (string.isnotblank(gedata.PersonManagementCode)) {
                     PersonManagementCodeList.add(gedata.PersonManagementCode);
                 }
                if(String.isnotBlank(gedata.NameEncrypted)){
                   NameList.add(gedata.NameEncrypted);
                }
                 newGeDataList.add(gedata);
                 System.debug('ManagementList'+ManagementList);
                 System.debug('SFDCCodeList'+SFDCCodeList);
             }
             if (newGeDataList.size() > 0){
                 system.debug('newGeDataList.size()'+newGeDataList.size());
                 //查询联系人
                 Map < String, Map < String, Contact >> nameMap = new Map < String, Map < String, Contact >> (); //外层战略科室，内层科室名+联系人名
                 List < Contact > peopleList = [select Id, 
                                                       Account.Name, 
                                                       //Department__c, 
                                                       Account.parent.Name, 
                                                       UnifiedI_Contact_ID__c,
                                                       //Account.PlatformCode__c, 
                                                       Account.Management_Code__c, 
                                                       //Account.parent.Department_Class_Label__c, 
                                                       Name,LastName_Encrypted__c,
                                                       //Account.Parent_Management_Code__c, 
                                                       //Account.Parent_PlatformCode__c, 
                                                       CManageCode__c,AWS_Data_Id__c,
                                                       // 通过姓名+手机号判断人员是否重复 thh 20220518 start
                                                       MobilePhone_Encrypted__c
                                                       // 通过姓名+手机号判断人员是否重复 thh 20220518 end
                                                       //AccountId 
                                                       from Contact 
                                                       where CManageCode__c IN: PersonManagementCodeList 
                                                      OR (Account.Parent_PlatformCode__c IN: ManagementList AND LastName_Encrypted__c IN:NameList AND UnifiedI_Contact_ID__c = null)
                                                      OR (Account.Parent_Management_Code__c IN: SFDCCodeList AND LastName_Encrypted__c IN:NameList AND UnifiedI_Contact_ID__c = null)
                                                      ORDER BY  MobilePhone ASC,CManageCode__c ASC]; //根据人员管理编码检索联系人
                 Map < String, Contact > peopleMap = new Map < String, Contact > (); //联系人
                 system.debug('peopleList  '+peopleList);
                 for (Contact ct: peopleList) {
                     if (string.isnotblank(ct.Account.parent.Name)) {
                         Map < String, Contact > snameMap = new Map < String, Contact > ();
                         string namekey;
                         string nameKey2;
                         string nameKey3;
                         if(String.isBlank(ct.MobilePhone_Encrypted__c)){
                            namekey = ct.Account.Name + ' ' + ct.LastName_Encrypted__c.trim();
                            nameKey2 = ct.Account.Management_Code__c + ' ' + ct.LastName_Encrypted__c.trim();
                            nameKey3 = ct.LastName_Encrypted__c.trim();
                         } else{
                            namekey = ct.Account.Name + ' ' + ct.LastName_Encrypted__c.trim() + ' ' + ct.MobilePhone_Encrypted__c.trim();
                            nameKey2 = ct.Account.Management_Code__c + ' ' + ct.LastName_Encrypted__c.trim() + ' ' + ct.MobilePhone_Encrypted__c.trim();
                            nameKey3 = ct.LastName_Encrypted__c.trim() + ' ' + ct.MobilePhone_Encrypted__c.trim();
                         }
                         snameMap.put(namekey,ct);
                         if (nameMap.containsKey(ct.Account.parent.Name)) {
                             snameMap = nameMap.get(ct.Account.parent.Name);
                         }
                         snameMap.put(nameKey2,ct); 
                         snameMap.put(namekey, ct);
                         snameMap.put(namekey3, ct);
                         // // 通过姓名+手机号判断人员是否重复 thh 20220518 start
                         // System.System.debug('ct.MobilePhone_Encrypted__c1:' + ct.MobilePhone_Encrypted__c);
                         // if(String.isBlank(ct.MobilePhone_Encrypted__c)){
                         //    snameMap.put(ct.LastName_Encrypted__c.trim(), ct);
                         // }else{
                         //    snameMap.put(ct.LastName_Encrypted__c.trim() + ct.MobilePhone_Encrypted__c.trim(), ct);
                         // }
                         // System.System.debug('ct.MobilePhone_Encrypted__c2:' + ct.MobilePhone_Encrypted__c);
                         // // 通过姓名+手机号判断人员是否重复 thh 20220518 end
                         nameMap.put(ct.Account.parent.Name, snameMap);
                         system.debug('snameMap'+snameMap.keyset());
                     }
                     peopleMap.put(ct.CManageCode__c, ct);
                     System.debug('peopleMap'+peopleMap);
                     System.debug('nameMap111'+nameMap);
                 }
                 for (Gedata gedata: newGeDataList) {
                     String personCode = gedata.PersonManagementCode;
                     string DepartmentClasskey = gedata.AccountName + ' ' + gedata.DepartmentClass;
                     if(string.isnotblank(personCode)){//判断有人员管理编码
                         //有人员管理编码
                         system.debug('有人员管理编码');
                         if (peopleMap.containsKey(personCode)) {
                            system.debug('有人员管理编码取到值');
                            peopleMap.get(personCode);
                            //red.dataID = gedata.dataID;
                            red.awsDataId = peopleMap.get(personCode).AWS_Data_Id__c;
                            red.sfid = peopleMap.get(personCode).id;
                         }else{
                            system.debug('有人员管理编码未取到值');
                            // red.dataID = gedata.dataID;
                            // red.awsDataId = null;
                            // red.sfid = null;
                         }
                         system.debug('red----------->'+red);
                         responseList.ResponseDetails.add(red);
                     }else{
                        //无人员管理编码
                        string namekey = gedata.RelatedDepartment + ' ' + gedata.NameEncrypted + ' ' + gedata.MobileEncrypted;
                        string namekey1 = gedata.RelatedDepartment + ' ' + gedata.NameEncrypted;
                        string namekey2 = gedata.NameEncrypted + ' ' + gedata.MobileEncrypted;
                        string namekey3 = gedata.NameEncrypted;
                        system.debug('DepartmentClasskey     =    '+DepartmentClasskey);
                        system.debug('nameMap22222222    '+nameMap);
                        if (nameMap.containskey(DepartmentClasskey)) { 
                            system.debug('nameMap.containskey(DepartmentClasskey'+nameMap.containskey(DepartmentClasskey));
                             Map < String, Contact > sMap = nameMap.get(DepartmentClasskey);
                             System.debug('sMap'+sMap);
                             System.debug('sMap.containsKey(namekey)'+sMap.containsKey(namekey));
                             System.debug('Namekey'+namekey);
                             if (sMap.containsKey(namekey) && sMap.get(namekey).UnifiedI_Contact_ID__c == null) {
                                system.debug('根据名字匹配存在');
                                red.awsDataId = sMap.get(namekey).AWS_Data_Id__c;
                                red.sfid = sMap.get(namekey).id;
                            } else if(sMap.containsKey(namekey1) && sMap.get(namekey1).UnifiedI_Contact_ID__c == null) {
                                red.awsDataId = sMap.get(namekey1).AWS_Data_Id__c;
                                red.sfid = sMap.get(namekey1).id;
                                
                            // // 通过姓名+手机号判断人员是否重复 thh 20220518 start
                            } else if(sMap.containsKey(namekey2) && sMap.get(namekey2).UnifiedI_Contact_ID__c == null){
                                system.debug('战略科室存在科室为空电话有值');
                                red.awsDataId = sMap.get(namekey2).AWS_Data_Id__c;
                                red.sfid = sMap.get(namekey2).id;
                            }else if(sMap.containsKey(namekey3) && sMap.get(namekey3).UnifiedI_Contact_ID__c == null){
                                system.debug('战略科室存在科室为空电话无值');
                                red.awsDataId = sMap.get(namekey3).AWS_Data_Id__c;
                                red.sfid = sMap.get(namekey3).id;
                            // // 通过姓名+手机号判断人员是否重复 thh 20220518 end
                            }else { // 7 完成
                                system.debug('根据名字匹配不存在');
                                //red.dataID = gedata.dataID;
                                //red.awsDataId = null;
                                //red.sfid = null;
                                for ( Integer i = 0; i < peopleList.size(); i++) {
                                    if (peopleList[i].Account.parent.Name !=DepartmentClasskey && peopleList[i].MobilePhone_Encrypted__c ==null) {
                                        red.awsDataId =peopleList[i].AWS_Data_Id__c;
                                        red.sfid =peopleList[i].id;
                                    }
                                }
                            }
                            system.debug('red----------->'+red);
                            //responseList.ResponseDetails.add(red);
                            system.debug('responseList.ResponseDetails'+responseList.ResponseDetails);
                        }else{
                            system.debug('战略科室不存在');
                            for ( Integer i = 0; i < peopleList.size(); i++) {
                                if (peopleList[i].MobilePhone_Encrypted__c ==null) {
                                    red.awsDataId =peopleList[i].AWS_Data_Id__c;
                                    red.sfid =peopleList[i].id;
                                }
                            }
                            //responseList.ResponseDetails.add(red);
                        }
                        responseList.ResponseDetails.add(red);
                    }    
                }
            }
            rowData.retry_cnt__c = 0;
            if (System.Test.isRunningTest()) {
                throw new ControllerUtil.myException('aaa');
            }
    }catch (Exception ex) {
            // エラーが発生した場合
           
            logstr += ex.getMessage();
            iflog.ErrorLog__c += ex.getMessage() + '\n';
            iflog.ErrorLog__c += ex.getStackTraceString() + '\n';
        }
        update rowData;
        system.debug('Rowdata'+rowData);   
        logstr += responseList +'\n';
        logstr += 'end';
        iflog.Log__c = logstr;
        update iflog;
        system.debug('responseList.ResponseDetails'+responseList.ResponseDetails);
        return responseList;  
    }
}