@RestResource(urlMapping = '/NFM203/*')
global with sharing class NFM203Rest {
    //add Response to aws 20220221 add sushanhu
   
    static Boolean SFStatus=true;
    static String SFMessage='';
    global class GeDatas {
        public NFMUtil.Monitoring Monitoring;
        public GeData[] Partners;
    }
    //合作伙伴抬头层级
    global class GeData {
        public License_Info[] License_Info;
        public Consignee_Info[] Consignee_Info;
        public Contract_Info[] Contract_Info;
        public Authorized_Info[] Authorized_Info;

        public String CompanyCode;                //公司代码
        public String BPCode;                     //合作伙伴代码
        public String BPType;                     //合作伙伴类型
        public String AgentType;                  //经销商分类
        public String CompanyName;                //企业名称
        public String RegisterAddress;            //住所(等同注册地址)
        public String RegionName;                 //省别
        public String City;                       //市
        public String Phone;                      //合作伙伴电话
        public String Postal;                     //合作伙伴邮编
        public String Fax;                        //合作伙伴传真
        public String Region;                     //省别(SPO传SAP,SFDC只接收不保存)
        public String ApplyType;                  //为‘1’时,契约:将契约的禁用日期赋值为当前日期.医院:解锁
        //"6":"协议变更","7":"证照变更",,"8":"收货地址变更"
        public String Incorporator;               //法定代表人(医院)
        public String AgentValidFrom;
        public String AgentValidTo;
        public String TaxNo;
        public String BankName;
        public String BankCode;
        public String Agreement1;
        public String Agreement2;
        public String Agreement3;
        public String Agreement4;
        public String Remark;
        public String Z3PLAuthorizedNo;
        public String AuthorizedScope;
        public String AuthorizedVF;
        public String AuthorizedVT;
        public String CNTag;
        public String Z3PLQualityAgrNo;
        public String QualityAgrNoVF;
        public String QualityAgrNoVT;
        public String Z3PLTransAgrNo;
        public String TransAgrVF;
        public String TransAgrVT;
        public String ServiceType;
        public String CustomerService;
        public String OperationProject;
        public String Approver;
        public String ApproveDate;
        public String Comment;
        //HWAG-BMC6WW  XHL 2020-03-03-Start
        public String BillingType;          //专票/普票
        public String BillingTelephone;     //开票联系电话
        public String BillingAddress;       //开票地址
        //HWAG-BMC6WW  XHL 2020-03-03-End
        public String other1;
        public String other2;
        public String other3;
        // public String IsCanSave;//20200807 ljh 是否具有存储资质
    }

    // 证照层级
    global class License_Info {

        public String LicenseType;              //证照类型
        public String BusLicenseNo;             //证照号
        public String ValidFrom;                //期限效期从
        public String ValidTo;                  //期限效期至
        public String DiagnosisScope;           //诊疗科目
        public String BusinessType;             //经营方式
        public String Principal;                //企业负责人
        public String BusinessAddress;          //经营场所（等同办公地址）
        //WLIG-CA48WC pk start 2022-1-7
        public String RegisterAddress;          //住所地址
        //WLIG-CA48WC pk end 2022-1-7       
        public String WarehouseAddress;         //库房地址
        public String BusinessScope;            //经营二类范围
        public String BusinessScope1;           //经营三类范围
        public string IssueAuthority;           //发证机关
        public String Exclusive;                //二类经营范围排除子分类
        public String Exclusive1;             //三类经营范围排除子分类
        public String other4;
        public String other5;
        public String other6;
    }

    // 收货人层级
    global class Consignee_Info {
        public String ContactName;
        public String ContactNameEncrypted;//add 20220221
        public String ContactPhone;
        public String ContactPhoneEncrypted;//add 20220221 
        public String PostalCode;
        public String PostalCodeEncrypted;//add 20220221
        public String ContactAddress;
        public String ContactAddressEncrypted;//add 20220221
        public String ContactCity; //有效收货人城市
        public String ContactDataId;// add  20220221 CONTACT aws 存储id
        public String AddressDataId;// add 2020221 adress aws 存储id
    }

    // 销售人层级
    global class Authorized_Info {
        public String SalesAuthorizedNo;
        public String SalesMan;
        public String SalesAuthorizedVF;
        public String SalesAuthorizedVT;
    }

    // 合同层级
    global class Contract_Info {
        //契约需要的字段
        public String TermContractNo;             //本期协议编号
        public String ContractOwner;              //客户所有人
        public String ContractDecideStartDate;    //允许报价期间(开始日)
        public String ContractDecideEndDate;      //允许报价期间(结束日)
        public String BusinessAssistant;          //营业助理
        public String SalesState;                 //申请省
        public String SalesShopClass;             //经销商合同分类
        public String ContractDepartmentClass;    //担当科室分类
        public String ContractStartDate;          //合同开始日
        public String ContractEndDate;            //合同结束日
        public String AgencyApplicationDay;       //特约经销商申请日
        public String AgencyApplicationNo;        //特约经销商申请编码
        public String SalesSection;               //申请销售课
        public String SelableProduct;             //担当产品
        public String AimPrice;                   //目标金额
        public Double AimPriceAreaET;             //ET目标金额
        public Double AimPriceAreaSP;             //SP耗材目标金额
        public Double AimPriceAreaENG;            //ENG目标金额
        public Double AimPriceAH;                 //奥辉目标金额
        public Double AimPriceSP;                 //SP目标金额
        public Double AimPriceGIR;                //GIR目标金额
        public Double DealerdiscountET;           //经销商折扣ET
        public Double DealerdiscountENG;          //经销商折扣ENG
        public Double DealerdiscountSP;           //经销商折扣SP
        public Double DealerdiscountAH;           //经销商折扣奥辉
        public Double DealerdiscountBF;           //经销商折扣BF
        public Double DealerdiscountENF;          //经销商折扣ENF
        public Double DealerdiscountGI;           //经销商折扣GI
        public Double DealerdiscountGS;           //经销商折扣GS
        public Double DealerdiscountGYN;          //经销商折扣GYN
        public Double DealerdiscountOTH;          //经销商折扣OTH
        public Double DealerdiscountURO;          //经销商折扣URO
        public Double DealerdiscountZF;           //经销商折扣政府项目
        public String AimDivision;                //目标区分
        //HWAG-BMC6WW  XHL 2020-03-03-Start
        public String SalesCity;                  //负责市
        //HWAG-BMC6WW  XHL 2020-03-03-End
    }

    @HttpPost
    global static void execute() {
        // 取得接口传输内容
        String strData = RestContext.request.requestBody.toString();
        GeDatas ges = (GeDatas) JSON.deserializeStrict(strData, GeDatas.class);
        NFMUtil.NFMResponse result = NFMUtil.getNFMResponse();

        if (ges == null ) {
            SFMessage+='参数为空';
            system.debug('SFMessage---'+SFMessage);
            return;
        }

        NFMUtil.Monitoring Monitoring = ges.Monitoring;
        if (Monitoring == null) {
            SFMessage+='Monitoring为空';
            system.debug('SFMessage---'+SFMessage);
            return;
        }

        BatchIF_Log__c rowData = NFMUtil.saveRowData(Monitoring, 'NFM203', ges.Partners);
        if (String.isBlank(rowData.Log__c) == false) {
            executefuture(rowData.Id);
        }
        // JSONを戻す
        RestResponse res = RestContext.response;
        res.addHeader('Content-Type', 'application/json');
        res.statusCode = 200;
        //String jsonResponse = '{"status": "Success", "Message":'  + gedata + '}';
        // String jsonResponse = '{"status": "Success", "Message":""}';
        //updata response toAWS
        result.SFStatus=SFStatus;
        result.SFMessage=SFMessage;
        String jsonResponse =JSON.serialize(result);
        system.debug('result---'+jsonResponse);
        res.responseBody = blob.valueOf(jsonResponse);
        return;
    }

    @future
    global static void executefuture(String rowData_Id) {
        main(rowData_Id);
    }

    global static void 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, 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 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 = 'NFM203';
        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;
        }
        // BatchIF転送表 から、コード変換のMapを作成
        Map<String, String> transferMap = new Map<String, String>();
        List<BatchIF_Transfer__c> transferList = [select Table__c,
                                  Column__c,
                                  External_value__c,
                                  Internal_value__c
                                  from BatchIF_Transfer__c
                                  where Dropped_Flag__c = false
                                          and Table__c = 'Account'];
        for (BatchIF_Transfer__c t : transferList) {
            transferMap.put(t.Column__c + t.External_value__c, t.Internal_value__c);
        }
        //证照类型
        Map<String, String> transferLicenseTypeMap = new Map<String, String>();
        List<BatchIF_Transfer__c> transferLicenseTypeList = [select Table__c,
                                  Column__c,
                                  External_value__c,
                                  Internal_value__c
                                  from BatchIF_Transfer__c
                                  where Dropped_Flag__c = false
                                          and Table__c = 'License_Information__c'];
        for (BatchIF_Transfer__c t : transferLicenseTypeList) {
            transferLicenseTypeMap.put(t.Column__c + t.External_value__c, t.Internal_value__c);
        }

        Savepoint sp = Database.setSavepoint();
        try {

            List<String> bPCodeList = new List<String>();
            List<String> tcnList = new List<String>();
            List<String> culList = new List<String>();

            List<String> cityList = new List<String>();
            List<String> regionNameList = new List<String>();
            List<GeData> nfmgd = new List<GeData>();
            //
            List<String> contractOwnerList = new List<String>();

            Map<String, String> applyTypeMap = new Map<String, String>();

            Map<String,List<Consignee_Info>> complianceDataMap  = new Map<String,List<Consignee_Info>>();
            //验证必填字段
            for (GeData gda : geDataList) {

                // 客户类型是代理商并且BPCode不为空 收货人信息 字段验证
                if ('02'.equals(gda.BPType) && String.isNotBlank(gda.BPCode)){
                    complianceDataMap = complianceDatamethod(gda);
                }
                //CHAN-BF259A XHL---20190819---Start
                //收货人信息变更，SFDC只更新联系人与收货地址(全删全增)
                if (gda.ApplyType == '8') {
                    if (complianceDataMap != null && complianceDataMap.size() > 0) {
                        Map<String, Account> accsMap = new Map<String, Account>();
                        insertAddressAndContacts(accsMap,complianceDataMap);
                    }
                    continue;
                }
                //CHAN-BF259A XHL---20190819---End
                //WYAN-BS8B2A -XHL -20200925 -Start
                if (gda.ApplyType == '9') {
                    String result =  ProtocolExtension(gda);

                    if (String.isNotBlank(result.split('/')[0])) {
                        iflog.ErrorLog__c += result.split('/')[0];
                        //add response to aws 2022022 sushanhu start
                        SFMessage=iflog.ErrorLog__c;
                        system.debug('ErrorLog__c--'+iflog.ErrorLog__c);
                        system.debug('SFMessage---'+SFMessage);
                        //add response to aws 20220222 sushanhu end  
                    } else {
                        logstr += result.split('/')[1];
                    }
                    continue;
                }
                //WYAN-BS8B2A -XHL -20200925 -End
                if (String.isBlank(gda.BPType)) {
                    
                  
                    iflog.ErrorLog__c += 'BPCode[ ' + gda.BPCode + ' ] of BPType is required,This data is skipped.\n';
                    //add response to aws 20220221 sushanhu start
                    SFMessage=iflog.ErrorLog__c;
                    system.debug('SFMessage--'+SFMessage);
                    //add response to aws 20220221 sushanhu end    
                    continue;
                }
                if (gda.BPType != '02' && gda.BPType != '03' && gda.BPType != '04' && gda.BPType != '05') {
                    continue;
                }
                if (String.isBlank(gda.BPCode)) {
                    iflog.ErrorLog__c += 'BPCode is required,This data is skipped.\n';
                    //add response to aws 20220221 sushanhu start
                    SFMessage=iflog.ErrorLog__c;
                    system.debug('SFMessage---'+SFMessage);
                    //add response to aws 20220221 sushanhu end  
                    continue;
                }
                if (gda.BPType == '02') {
                    // 经销商的场合
                    if (String.isBlank(gda.CompanyName)) {
                        iflog.ErrorLog__c += 'BPCode[ ' + gda.BPCode + ' ] of CompanyName is required,This data is skipped.\n';
                        //add response to aws 20220221 sushanhu start
                        SFMessage=iflog.ErrorLog__c;
                        system.debug('SFMessage---'+SFMessage);
                        //add response to aws 20220221 sushanhu end  
                        continue;
                    }
                    if (String.isBlank(gda.AgentType)) {
                        iflog.ErrorLog__c += 'BPCode[ ' + gda.BPCode + ' ] of AgentType is required,This data is skipped.\n';
                        //add response to aws 20220221 sushanhu start
                        SFMessage=iflog.ErrorLog__c;
                        system.debug('SFMessage---'+SFMessage);
                        //add response to aws 20220221 sushanhu end  
                        continue;
                    }
                    //当经销商的分类为“特约经销商（区域）”、“特约经销商（产品）”、"特约经销商（区域+产品）"、"集采经销商"时，验证契约的必填字段
                    Boolean flg = false;
                    for (Contract_Info contractInfos : gda.Contract_Info) {
                        //CHAN-BF8CCU ---XHL---updateStart---20190821
                        if (gda.AgentType == '01' || gda.AgentType == '02' || gda.AgentType == '04' || gda.AgentType == '06') {// || gda.AgentType == 'A1'
                            //CHAN-BF8CCU ---XHL---updateEnd---20190821
                            if (String.isBlank(contractInfos.TermContractNo)) {
                                iflog.ErrorLog__c += 'BPCode[ ' + gda.BPCode + ' ] of TermContractNo is required ,This data is skipped.\n';
                               //add response to aws 20220221 sushanhu start
                                SFMessage=iflog.ErrorLog__c;
                                system.debug('SFMessage---'+SFMessage);
                                //add response to aws 20220221 sushanhu end  
                                flg = true;
                                continue;
                            }
                            tcnList.add(contractInfos.TermContractNo);
                        }
                        if (String.isNotBlank(contractInfos.ContractOwner)) {
                            contractOwnerList.add(contractInfos.ContractOwner);
                        }
                    }
                    if (flg) continue;
                }
                if (String.isNotBlank(gda.RegionName)) {
                    regionNameList.add(gda.RegionName);
                }

                if (String.isNotBlank(gda.City)) {
                    cityList.add(gda.City);
                }

                if (gda.ApplyType == '2' || gda.ApplyType == '3' || gda.ApplyType == '4' || gda.ApplyType == '7') {

                    applyTypeMap.put(gda.BPCode, gda.ApplyType);
                }
                //add result message 20220222 sushanhu satrt
                    SFMessage=iflog.ErrorLog__c;
                    system.debug('SFMessage---'+SFMessage);
                //add result message 20220222 sushanhu end

                bPCodeList.add(gda.BPCode);
                nfmgd.add(gda);
            }
            // 经销商和合同的所有人 contractOwner
            List<User> contractOwnerMap = new List<User>([select Id, Employee_No__c from User where Employee_No__c in :contractOwnerList and isActive = true]);


            //根据省级名查找省级ID
            //List<Address_Level__c> address_LevelList = [select Id,Name from Address_Level__c where Name In :regionNameList];
            List<Address_Level__c> address_LevelList = [select Id, Name from Address_Level__c ];
            Map<String, Address_Level__c> regionNameMap = new Map<String, Address_Level__c>();
            for (Address_Level__c level1 : address_LevelList) {
                regionNameMap.put(level1.Name, level1);
            }

            //CHAN-BF8CCU ---XHL---updateStart---20190821
            //根据市级名查找市级ID
            //List<Address_Level2__c> address_Level2List = [select Id,Name from Address_Level2__c where Name In :cityList];
            List<Address_Level2__c> address_Level2List = [select Id, Name from Address_Level2__c];
            Map<String, Address_Level2__c> cityMap = new Map<String, Address_Level2__c>();
            for (Address_Level2__c level2 : address_Level2List) {
                cityMap.put(level2.Name, level2);
            }
            //CHAN-BF8CCU ---XHL---updateEnd---20190821
            //根据BPcode查找客户
            List<Account>  accList = [select Id, Name, Management_FormulaCode__c, State_Master__r.Name, City_Master__r.Name from Account where Management_FormulaCode__c in : bPCodeList];
            Map<String, Account> accsMap = new Map<String, Account>();
            for (Account acc : accList) {
                accsMap.put(acc.Management_FormulaCode__c, acc);
            }

            //CHAN-BF259A XHL---20190819---Start
            //证照变更删除所有相关证照，再重新创建
            List<String> deleteExistLicenseInformationList = new List<String>();
            if ( accsMap.size() > 0 && applyTypeMap.size() > 0) {

                for (String managementCode : accsMap.keySet()) {

                    if ( applyTypeMap.containsKey(managementCode)) {

                        String accountId = accsMap.get(managementCode).Id;

                        deleteExistLicenseInformationList.add(accountId);

                    }
                }
            }
            if ( deleteExistLicenseInformationList.size() > 0 ) {

                List<License_Information__c> deleteLicenseInfoList = [select Id,
                                             Name,
                                             LicenseAndAccount__c
                                             from License_Information__c
                                             where LicenseAndAccount__c  In: deleteExistLicenseInformationList ];

                if (deleteLicenseInfoList.size() > 0) {
                    delete deleteLicenseInfoList;
                }
            }

            //CHAN-BF259A XHL---20190819---End

            //根据“本期协议编号TermContractNo”查找“契约”
            List<Account> contractList = [select Id, Name, City_Master__c, ParentId, Term_Contract_No__c from Account where Term_Contract_No__c in: tcnList];
            Map<String, Account> contractMap = new Map<String, Account>();
            for (Account acc : contractList) {
                contractMap.put(acc.Term_Contract_No__c, acc);
            }

            List<License_Information__c> license_InformationUpsertList = new List<License_Information__c>();
            List<Account> accountUpsertList = new List<Account>();
            Map<String, Account> contractUpsertMap = new Map<String, Account>();
            List<License_Information__c> licenseInfoUpsertList = new List<License_Information__c>();

            for (GeData gda : nfmgd) {

                //"醫院"的场合
                if (gda.BPType == '03' || gda.BPType == '04' || gda.BPType == '05') {
                    //判断BPCode是否已经存在,不存在的话会提示不存在，并且跳过
                    if (!accsMap.containsKey(gda.BPCode)) {
                        iflog.ErrorLog__c += ' This BPCode[' + gda.BPCode + '] is not exist,This data is skipped .\n';
                        //add response to aws 20220221 sushanhu start
                        SFMessage=iflog.ErrorLog__c;
                        system.debug('SFMessage---'+SFMessage);
                        //add response to aws 20220221 sushanhu end  
                        continue;
                    }
                }
                logstr += '管理编码:' + gda.BPCode;
                logstr += '\n客户类型:' + gda.BPType;
                logstr += '\nApplyType:' + gda.ApplyType;
                if (gda.BPType == '02') {
                    logstr += '\n经销商分类:' + gda.AgentType;
                }

                Account accountInfo = New Account();
                //如果是医院解约，更新医院审批状态
                if (gda.ApplyType == '1' && gda.BPType != '02')  {
                    if (accsMap.containsKey(gda.BPCode)) {
                        accountInfo = accsMap.get(gda.BPCode);
                        //if (gda.BPType != '02') {
                        accountInfo.If_Qualifying__c = false;
                        accountInfo.Quolified_Approve_Status__c = 'Reject';
                        //}
                    }
                } else if (gda.ApplyType == '5' && gda.BPType != '02') {
                    // 如果是医院锁定，只更新医院审批状态
                    if (accsMap.containsKey(gda.BPCode)) {
                        accountInfo = accsMap.get(gda.BPCode);
                        //if (gda.BPType != '02') {
                        accountInfo.If_Qualifying__c = true;
                        accountInfo.Quolified_Approve_Status__c = 'submit';
                        //}
                    }

                } else {

                    if (accsMap.containsKey(gda.BPCode)) {
                        accountInfo = accsMap.get(gda.BPCode);
                    } else {
                        accountInfo.AgentCode_Ext__c =  gda.BPCode.leftPad(10, '0');
                    }
                    //经销商
                    if (gda.BPType == '02') {
                        if (contractOwnerMap.size() > 0 && !accsMap.containsKey(gda.BPCode)) {
                            accountInfo.OwnerId = contractOwnerMap[0].Id;
                        }
                        accountInfo.Phone = gda.Phone;
                        accountInfo.Fax = gda.Fax;
                        accountInfo.Postal_Code__c = gda.Postal;
                        //accountInfo.AgentCode_Ext__c = gda.BPCode;
                        accountInfo.RecordTypeId =  System.Label.dealer;
                        accountInfo.Sales_Shop_Class__c = NFMUtil.getMapValue(transferMap, 'Sales_Shop_ClassSPO__c', gda.AgentType, iflog);

                        if (accountInfo.Name != gda.CompanyName) {
                            accountInfo.Sap2sfdcDealers_ModifycationLogo__c = '1';
                        }
                        accountInfo.Name = gda.CompanyName;
                        accountInfo.Ban_On_Use_Date__c = NFMUtil.parseStr2Date(gda.AgentValidTo);
                        accountInfo.Delete_Flag__c = false;
                        accountInfo.Corporation__c = gda.Incorporator;
                        accountInfo.Address_Together__c = gda.RegionName + gda.City + gda.RegisterAddress;
                        // 证照信息初始化
                        if (gda.ApplyType == '2' || gda.ApplyType == '3' || gda.ApplyType == '4' || gda.ApplyType == '7') {
                            accountInfo.Business_Authorization_No__c = null;
                            accountInfo.Business_Paper_Expiration_Date__c = null;
                            accountInfo.Medical_Equipment_Num__c = null;
                            accountInfo.Medical_Equipment_Expiration_Date__c = null;
                            accountInfo.Tax_Practice_No__c = null;
                            accountInfo.Tax_Practice_Expiration_Date__c = null;
                        }
                        //经销商省市保存
                        if (cityMap.containsKey(gda.City)) {
                            accountInfo.City_Master__c = cityMap.get(gda.City).Id;
                        }
                        if (regionNameMap.containsKey(gda.RegionName)) {
                            accountInfo.State_Master__c = regionNameMap.get(gda.RegionName).Id;
                        }
                        //20200807 ljh 是否具有存储资质 add start
                        // if(gda.IsCanSave != null){
                        //     accountInfo.IsCanSave__c = gda.IsCanSave.equals('1')?true:false;
                        // }
                        //20200807 ljh 是否具有存储资质 add end

                    } else {
                        // 证照信息初始化
                        accountInfo.Corporation__c = gda.Incorporator;
                        accountInfo.Business_license_no__c = null;
                        accountInfo.Business_license_valid__c = null;
                        accountInfo.RegistrationNumber__c = null;
                        accountInfo.Quolified_App_Date__c = null;
                        accountInfo.Valid_From__c = null;
                        accountInfo.Valid_To__c = null;
                    }
                }
                if (gda.Contract_Info != null) {
                    accountInfo.SPO_ApplicationNo__c = GetApplicationNo(gda);
                }
                accountUpsertList.add(accountInfo);
                // //add response to aws 20220221 sushanhu start
                // SFMessage=iflog.ErrorLog__c;
                // //add response to aws 20220221 sushanhu end
            }
            // 新建/更新客户主数据
            if (accountUpsertList.size() > 0) {
                ControllerUtil.EscapeNFM001Trigger = true;
                StaticParameter.EscapeNFM001AgencyContractTrigger2 = true;
                upsert accountUpsertList;
            }

            //二次查询主要是为了，当"经销商"不存在而进行新增时，"契约"与"证照"需要"经销商"的某些值。
            //因此，就将"经销商"与"契约"、"证照"分别进行新增，所以，重新查询。
            accList = [select Id, RecordTypeId, Name,
                       Management_FormulaCode__c,
                       Business_Paper_Expiration_Date__c,
                       Medical_Equipment_Expiration_Date__c
                       from Account
                       where Management_FormulaCode__c in : bPCodeList ];

            accsMap = new Map<String, Account>();
            for (Account acc : accList) {
                accsMap.put(acc.Management_FormulaCode__c, acc);
            }

            // 删除系统中的联系人与收货地址 同时 新增 联系人与收货地址
            if (accsMap.size() > 0 && complianceDataMap.size() > 0) {
                insertAddressAndContacts(accsMap,complianceDataMap);
            }
            Map<String, License_Info> geDataDetailsMap = null;
            Map<String, Account> accountUpsertMap = new Map<String, Account>();
            for (GeData gda : nfmgd) {

                geDataDetailsMap = new Map<String, License_Info>();

                // 医院审批终止,解锁数据 医院审批开始，锁定数据 与证照无关，跳过
                if (gda.BPType != '02' && (gda.ApplyType == '1' || gda.ApplyType == '5'))  continue;



                // 经销商的场合 - 契约
                if (gda.BPType == '02' && (gda.ApplyType == '1' || gda.ApplyType == '2' || gda.ApplyType == '3' || gda.ApplyType == '4' || gda.ApplyType == '6') ) {

                    for (Contract_Info contractInfos : gda.Contract_Info) {
                        //CHAN-BF8CCU ---XHL---updateStart---20190821
                        if (gda.AgentType == '01' || gda.AgentType == '02' || gda.AgentType == '04' || gda.AgentType == '06') {//|| gda.AgentType == 'A1'
                            //CHAN-BF8CCU ---XHL---updateEnd---20190821
                            //对"契约"进行赋值
                            Account contractInfoAcc = New Account();
                            if (contractMap.containsKey(contractInfos.TermContractNo)) {
                                contractInfoAcc = contractMap.get(contractInfos.TermContractNo);
                                //契约发往SAPBatch标记(修改为'3')
                                contractInfoAcc.ContractSfdc2SapLog__c = '3';
                                if (contractInfoAcc.ParentId != accsMap.get(gda.BPCode).Id) {
                                    contractInfoAcc.Sap2sfdcDealers_ModifycationLogo__c = '1';
                                }
                                //if (cityMap.containsKey(gda.City)) {
                                //    if (contractInfoAcc.City_Master__c != cityMap.get(gda.City).Id) {
                                //        contractInfoAcc.Sap2sfdcDealers_ModifycationLogo__c = '1';
                                //    }
                                //}
                                //HWAG-BMC6WW  XHL 2020-03-03-Start
                                if (cityMap.containsKey(contractInfos.SalesCity)) {
                                    if (contractInfoAcc.City_Master__c != cityMap.get(contractInfos.SalesCity).Id) {
                                        contractInfoAcc.Sap2sfdcDealers_ModifycationLogo__c = '1';
                                    }
                                }
                                //HWAG-BMC6WW  XHL 2020-03-03-End
                            } else {
                                //契约发往SAPBatch标记(新增为'2')
                                contractInfoAcc.ContractSfdc2SapLog__c = '2';
                                contractInfoAcc.Sap2sfdcDealers_ModifycationLogo__c = '1';
                            }

                            //若ApplyType == '1'则为契约禁用(相当于逻辑删除)，将禁用日期附上当前日期
                            if (gda.ApplyType == '1') {
                                if (contractMap.containsKey(contractInfos.TermContractNo)) {
                                    contractInfoAcc = contractMap.get(contractInfos.TermContractNo);
                                    contractInfoAcc.Ban_On_Use_Date__c = Date.today();
                                    contractInfoAcc.Contract_End_Date__c = Date.today();
                                    //允许报价期间(结束日)
                                    if (String.isNotBlank(contractInfos.ContractDecideEndDate)) {
                                        contractInfoAcc.Contract_Decide_End_Date__c = NFMUtil.parseStr2Date(contractInfos.ContractDecideEndDate);
                                    } 
                                } else {
                                    iflog.ErrorLog__c += 'This Contract[ ' + contractInfos.TermContractNo + ' ] not exist,The Data Not  Cancel';
                                     //add response to aws 20220221 sushanhu start
                                    SFMessage=iflog.ErrorLog__c;
                                    system.debug('SFMessage---'+SFMessage);
                                    //add response to aws 20220221 sushanhu end
                                    continue ;
                                }


                            } else {
                                //
                                if (String.isNotBlank(contractInfos.ContractOwner) && contractOwnerMap.size() > 0 && !contractMap.containsKey(contractInfos.TermContractNo)) {
                                    contractInfoAcc.OwnerId = contractOwnerMap[0].Id;
                                }
                                if (String.isNotBlank(contractInfos.ContractOwner) && contractOwnerMap.size() > 0) {
                                    contractInfoAcc.Business_Assistant__c = contractOwnerMap[0].Id;
                                }

                                contractInfoAcc.Contract_Fiscal_Period__c = contractInfos.TermContractNo.split('-')[0];
                                contractInfoAcc.Agency_Application_Situation__c = '承認済み';
                                contractInfoAcc.Name = contractInfos.TermContractNo + ':' + gda.CompanyName;
                                contractInfoAcc.SpecialDealerName__c = gda.CompanyName;
                                contractInfoAcc.Agent_Ref__c = accsMap.get(gda.BPCode).Id;
                                contractInfoAcc.ParentId = accsMap.get(gda.BPCode).Id;
                                contractInfoAcc.RecordTypeId = System.Label.Contract;
                                contractInfoAcc.Term_Contract_No__c = contractInfos.TermContractNo;
                                contractInfoAcc.Sales_Shop_Contract_Class__c = contractInfos.SalesShopClass;

                                //ContractDecideStartDate不为空赋值本身,否则赋值ContractStartDate
                                if (String.isNotBlank(contractInfos.ContractDecideStartDate)) {
                                    contractInfoAcc.Contract_Decide_Start_Date__c = NFMUtil.parseStr2Date(contractInfos.ContractDecideStartDate);
                                } else {
                                    contractInfoAcc.Contract_Decide_Start_Date__c = NFMUtil.parseStr2Date(contractInfos.ContractStartDate);
                                }
                                //ContractDecideEndDate不为空赋值本身,否则赋值ContractEndDate
                                if (String.isNotBlank(contractInfos.ContractDecideEndDate)) {
                                    contractInfoAcc.Contract_Decide_End_Date__c = NFMUtil.parseStr2Date(contractInfos.ContractDecideEndDate);
                                } else {
                                    contractInfoAcc.Contract_Decide_End_Date__c = NFMUtil.parseStr2Date(contractInfos.ContractEndDate);
                                }
                                //ContractDepartmentClass(担当科室分類),传过来的"BF;ENF;GI;GS;GYN;OTH;URO;政府项目"用分号隔开的值
                                //需要将其转换为对应的汉字,并拼接完成后，进行赋值
                                Map<String, String> cdcMap = new  Map<String, String>();
                                Map<String, String> cdcErrorMap = new  Map<String, String>();
                                cdcMap.put('BF', 'BF'); cdcMap.put('ENF', 'ENF'); cdcMap.put('GI', 'GI'); cdcMap.put('GS', 'GS');
                                cdcMap.put('GYN', 'GYN'); cdcMap.put('OTH', 'OTH'); cdcMap.put('URO', 'URO'); cdcMap.put('政府项目', '政府项目');
                                if (String.isNotBlank(contractInfos.ContractDepartmentClass)) {
                                    contractInfoAcc.Contract_Department_Class__c = '';
                                    contractInfos.ContractDepartmentClass += ';';
                                    for (String cdc : contractInfos.ContractDepartmentClass.split(';')) {
                                        if (cdcMap.containsKey(cdc)) {
                                            contractInfoAcc.Contract_Department_Class__c += NFMUtil.getMapValue(transferMap, 'Contract_Department_Class__c', cdc, iflog) + ';';
                                        } else {
                                            cdcErrorMap.put(cdc, cdc);
                                            continue;
                                        }
                                    }
                                } else {
                                    if (contractInfos.SelableProduct == 'ET') {
                                        contractInfoAcc.Contract_Department_Class__c = 'ET';
                                    }
                                }

                                if (cdcErrorMap.size() > 0) {
                                    iflog.ErrorLog__c += ' This BPCode[' + gda.BPCode + '] of ContractDepartmentClass [' + cdcErrorMap.values() + '] noneffective, [' + cdcErrorMap.values() + '] skipped .\n';
                                     //add response to aws 20220221 sushanhu start
                                    SFMessage=iflog.ErrorLog__c;
                                    //add response to aws 20220221 sushanhu end
                                }
                                contractInfoAcc.Contract_Start_Date__c = NFMUtil.parseStr2Date(contractInfos.ContractStartDate);
                                contractInfoAcc.Contract_End_Date__c = NFMUtil.parseStr2Date(contractInfos.ContractEndDate);
                                contractInfoAcc.Agency_Application_Day__c = NFMUtil.parseStr2Date(contractInfos.AgencyApplicationDay);
                                contractInfoAcc.Agency_Application_No__c = contractInfos.AgencyApplicationNo;
                                contractInfoAcc.Sales_Section__c = contractInfos.SalesSection;

                                contractInfoAcc.Aim_Division__c = contractInfos.AimDivision == '金额' ? '金額' : '数量';
                                //SelableProduct(担当产品),根据传过来的值的不同，来将不同的值进行赋值，因为一次只可以传过来一个值‘ET’或者‘ENG’
                                //故，ET_SP_Dealer__c与ENG_Dealer__c必互斥

                                contractInfoAcc.ENG_Dealer__c = false;
                                contractInfoAcc.ET_SP_Dealer__c = false;
                                contractInfoAcc.SP_DealerContact__c = false;
                                contractInfoAcc.CELON_Dealer__c = false ;
                                contractInfoAcc.ENERGY_Dealer__c = false;
                                contractInfoAcc.TF_Dealer__c = false ;
                                contractInfoAcc.Assiesedo_Dealer__c = false ;
                                if (contractInfos.SelableProduct == 'ET') {
                                    contractInfoAcc.ET_SP_Dealer__c = true;
                                } else if (contractInfos.SelableProduct == '能量主机') {
                                    contractInfoAcc.ENERGY_Dealer__c = true;
                                } else if (contractInfos.SelableProduct == '能量耗材') {
                                    contractInfoAcc.ENG_Dealer__c = true;
                                } else if (contractInfos.SelableProduct == 'SP耗材') {
                                    contractInfoAcc.SP_DealerContact__c = true;
                                } else if (contractInfos.SelableProduct == 'Celon') {
                                    contractInfoAcc.CELON_Dealer__c = true ;
                                    contractInfoAcc.SP_DealerContact__c = true;
                                } else if (contractInfos.SelableProduct == '奥辉') {
                                    contractInfoAcc.TF_Dealer__c = true ;
                                } else if (contractInfos.SelableProduct == '阿西赛多') {
                                    contractInfoAcc.Assiesedo_Dealer__c = true ;
                                } 

                                contractInfoAcc.Selable_Product__c = contractInfos.SelableProduct;
                                contractInfoAcc.Delete_Flag__c = false;

                                //contractInfoAcc.Aim_Price_ET__c = contractInfos.AimPriceAreaET;
                                //contractInfoAcc.Aim_Price_SP__c = contractInfos.AimPriceSP;
                                //contractInfoAcc.Aim_Price_GIR__c = contractInfos.AimPriceGIR;
                                //20190827 SPO2SFDC出现目标金额为非数字，故创建一个字段接收数据，将逻辑修改 Start XHL
                                if (gda.AgentType == '06') {
                                    contractInfoAcc.CentralizedPurchasingDealerAim_Price__c = String.valueOf(contractInfos.AimPrice);
                                } else {
                                    if (String.isNotBlank(contractInfos.AimPrice)) {
                                       contractInfoAcc.Aim_Price__c = Double.valueOf(contractInfos.AimPrice); 
                                    }
                                    // contractInfoAcc.Aim_Price__c = Double.valueOf(contractInfos.AimPrice); //contractInfos.AimPrice;
                                }
                                //20190827 SPO2SFDC出现目标金额为非数字，故创建一个字段接收数据，将逻辑修改 End XHL
                                //contractInfoAcc.Aim_Price__c = contractInfos.AimPrice;
                                contractInfoAcc.Aim_PriceArea_SP__c = contractInfos.AimPriceAreaSP;
                                contractInfoAcc.Aim_PriceArea_ENG__c = contractInfos.AimPriceAreaENG;
                                contractInfoAcc.Aim_Price_AH__c = contractInfos.AimPriceAH;

                                contractInfoAcc.Dealerdiscount_ET__c = contractInfos.DealerdiscountET;
                                contractInfoAcc.Dealerdiscount_ENG__c = contractInfos.DealerdiscountENG;
                                contractInfoAcc.Dealerdiscount_SP__c = contractInfos.DealerdiscountSP;
                                contractInfoAcc.Dealerdiscount_AH__c = contractInfos.DealerdiscountAH;
                                contractInfoAcc.Dealerdiscount_BF__c = contractInfos.DealerdiscountBF;
                                contractInfoAcc.Dealerdiscount_ENF__c = contractInfos.DealerdiscountENF;
                                contractInfoAcc.Dealerdiscount_GI__c = contractInfos.DealerdiscountGI;
                                contractInfoAcc.Dealerdiscount_GS__c = contractInfos.DealerdiscountGS;
                                contractInfoAcc.Dealerdiscount_GYN__c = contractInfos.DealerdiscountGYN;
                                contractInfoAcc.Dealerdiscount_OTH__c = contractInfos.DealerdiscountOTH;
                                contractInfoAcc.Dealerdiscount_URO__c = contractInfos.DealerdiscountURO;
                                contractInfoAcc.Dealerdiscount_ZF__c = contractInfos.DealerdiscountZF;
                                // 经销商折扣
                                if (contractInfos.DealerdiscountET != null) {
                                    contractInfoAcc.Dealer_discount__c = contractInfos.DealerdiscountET;
                                } else if (contractInfos.DealerdiscountENG != null) {
                                    contractInfoAcc.Dealer_discount__c = contractInfos.DealerdiscountENG;
                                } else if (contractInfos.DealerdiscountAH != null) {
                                    contractInfoAcc.Dealer_discount__c = contractInfos.DealerdiscountAH;
                                } else if (contractInfos.DealerdiscountSP != null) {
                                    contractInfoAcc.Dealer_discount__c = contractInfos.DealerdiscountSP;
                                } else if (contractInfos.SelableProduct == '能量耗材' ) {
                                    Double discount = null;
                                    // CHAN-BUZ54C XHL 20201104 Start 【委托】ENG耗材协议折扣取值逻辑变更
                                    // 按这个优先级优先级，1） GS    2） GYN    3） URO  4)ENF  5） OTH，
                                    if (contractInfos.DealerdiscountOTH != null){
                                        discount = contractInfos.DealerdiscountOTH;
                                    }
                                    if (contractInfos.DealerdiscountENF != null){
                                        discount = contractInfos.DealerdiscountENF;
                                    }
                                    if (contractInfos.DealerdiscountURO != null){
                                        discount = contractInfos.DealerdiscountURO;
                                    }
                                    if (contractInfos.DealerdiscountGYN != null){
                                        discount = contractInfos.DealerdiscountGYN;
                                    }
                                    if (contractInfos.DealerdiscountGS != null){
                                        discount = contractInfos.DealerdiscountGS;
                                    }

                                    if (discount != null) {
                                        contractInfoAcc.Dealer_discount__c = discount;
                                    }
                                    // CHAN-BUZ54C XHL 20201104 End 【委托】ENG耗材协议折扣取值逻辑变更
                                }

                                //if (regionNameMap.containsKey(contractInfos.RegionName)) {
                                //  contractInfoAcc.State_Master__c = regionNameMap.get(gda.RegionName).Id;
                                //}
                                //HWAG-BMC6WW  XHL 2020-03-03-Start
                                if (cityMap.containsKey(contractInfos.SalesCity)) {
                                    contractInfoAcc.City_Master__c = cityMap.get(contractInfos.SalesCity).Id;
                                }
                                //HWAG-BMC6WW  XHL 2020-03-03-Start
                                //contractInfoAcc.Street__c = gda.RegisterAddress;
                                //CHAN-BF8CCU ---XHL---updateStart---20190821
                                String salesStatePro = contractInfos.SalesState;
                                String salesStateRear = salesStatePro.endsWith('-能量') ? salesStatePro.split('-')[0] : salesStatePro;
                                contractInfoAcc.Sales_State__c = salesStateRear;
                                system.debug('<---SalesState--->' + salesStateRear);
                                if ( regionNameMap.containsKey(salesStateRear)) {
                                    contractInfoAcc.State_Master__c = regionNameMap.get(salesStateRear).Id;
                                } else {

                                    if (salesStateRear == '黑龙江省') {
                                        contractInfoAcc.State_Master__c = regionNameMap.get('黑龙江').Id;
                                    } else if (salesStateRear == '内蒙古') {
                                        contractInfoAcc.State_Master__c = regionNameMap.get('内蒙古自治区').Id;
                                    } else if (salesStateRear == '沈阳市') {
                                        contractInfoAcc.State_Master__c = regionNameMap.get('辽宁省').Id;
                                        contractInfoAcc.City_Master__c = cityMap.get(salesStateRear).Id;
                                    } else if (salesStateRear == '大连市') {
                                        contractInfoAcc.State_Master__c = regionNameMap.get('辽宁省').Id;
                                        contractInfoAcc.City_Master__c = cityMap.get(salesStateRear).Id;
                                    } else if (salesStateRear == '青岛市') {
                                        contractInfoAcc.State_Master__c = regionNameMap.get('山东省').Id;
                                        contractInfoAcc.City_Master__c = cityMap.get(salesStateRear).Id;
                                    } else if (salesStateRear == '深圳市') {
                                        contractInfoAcc.State_Master__c = regionNameMap.get('广东省').Id;
                                        contractInfoAcc.City_Master__c = cityMap.get(salesStateRear).Id;
                                    }
                                }
                                //CHAN-BF8CCU ---XHL---updateEnd---20190821
                                //if (regionNameMap.containsKey(contractInfos.SalesState)) {
                                //    contractInfoAcc.State_Master__c = regionNameMap.get(contractInfos.SalesState).Id;
                                //}
                                contractInfoAcc.Street__c = '';
                                // contractInfoAcc.City_Master__c = null;
                            }

                            contractUpsertMap.put(contractInfos.TermContractNo, contractInfoAcc);
                        }
                    }
                }
                system.debug('<---ApplyType--AAAA-->' + gda.ApplyType);
                //CHAN-BF259A XHL---20190819---Start
                //新建或证照变更时才会进入否则直接跳过，<---gda.ApplyType = 7--->证照变更
                if ( !String.isBlank(gda.ApplyType) && gda.ApplyType != '2' && gda.ApplyType != '3' && gda.ApplyType != '4' && gda.ApplyType != '7') {
                    continue;
                }
                system.debug('<---ApplyType--->' + gda.ApplyType);
                //CHAN-BF259A XHL---20190819---End

                // 证照
                for (License_Info gdds : gda.License_Info) {

                    if (String.isBlank(gdds.LicenseType)) {
                        iflog.ErrorLog__c += 'BPCode[ ' + gda.BPCode + ' ] of LicenseType is required ,This data is skipped.\n';
                        //add response to aws 20220221 sushanhu start
                        SFMessage=iflog.ErrorLog__c;
                        system.debug('SFMessage---'+SFMessage);
                        //add response to aws 20220221 sushanhu end
                        continue;
                    }
                    if (gdds.LicenseType == '23' || gdds.LicenseType == '24') { //3PL相关证
                        continue;
                    }
                    if (String.isBlank(gdds.BusLicenseNo)) {
                        iflog.ErrorLog__c += 'BPCode[ ' + gda.BPCode + ' ] of BusLicenseNo is required,This data is skipped .\n';
                        //add response to aws 20220221 sushanhu start
                        SFMessage=iflog.ErrorLog__c;
                        system.debug('SFMessage---'+SFMessage);
                        //add response to aws 20220221 sushanhu end
                        continue;
                    }
                    geDataDetailsMap.put(gdds.LicenseType, gdds);
                }

                // 证照
                for (License_Info gdds : geDataDetailsMap.values()) {

                    License_Information__c licenseInfo = new License_Information__c();

                    if (accsMap.containsKey(gda.BPCode)) {
                        //对"主-详细信息(客户)"进行赋值，将"证照"与"客户"进行关联
                        licenseInfo.LicenseAndAccount__c = accsMap.get(gda.BPCode).Id;
                    } else {
                        continue;
                    }
                    licenseInfo.LicenseType__c = NFMUtil.getMapValue(transferLicenseTypeMap, 'LicenseType__c', gdds.LicenseType, iflog);
                    licenseInfo.BusinessLicense__c = gdds.BusLicenseNo;
                    licenseInfo.Name = accsMap.get(gda.BPCode).Name + licenseInfo.LicenseType__c;
                    licenseInfo.ValidFrom__c = NFMUtil.parseStr2Date(gdds.ValidFrom);
                    licenseInfo.ValidTo__c = NFMUtil.parseStr2Date(gdds.ValidTo);
                    licenseInfo.BusinessLeader__c = gdds.Principal;
                    //WLIG-CA48WC pk start 2022-1-7
                    licenseInfo.RegisterAddress__c = gdds.RegisterAddress;
                    //WLIG-CA48WC pk end 2022-1-7
                    licenseInfo.BusinessLocation__c = gdds.BusinessAddress;
                    licenseInfo.StorageAddress__c = gdds.WarehouseAddress;
                    licenseInfo.IssuingOrgan__c = gdds.IssueAuthority;
                    licenseInfo.RunMode__c = gdds.BusinessType;
                    licenseInfo.MedicalSubject__c = gdds.DiagnosisScope;
                    licenseInfo.Exclusive__c = gdds.Exclusive;
                    licenseInfo.Exclusive1__c = gdds.Exclusive1;
                    licenseInfo.IsFromSPO__c = true;
                    licenseInfo.Scope__c = gdds.BusinessScope;
                    licenseInfo.Scope3__c = gdds.BusinessScope1;

                    licenseInfoUpsertList.add(licenseInfo);

                    //对"经销商"主数据中的"营业许可证书状况"的相关字段进行赋值
                    if (gda.BPType == '02') {
                        Account accountInfo = New Account();
                        if (accsMap.containsKey(gda.BPCode)) {
                            accountInfo = accsMap.get(gda.BPCode);
                        }
                        accountUpsertMap.put(gda.BPCode, accountInfo);

                        if (gdds.LicenseType == '01') {
                            //'01'为'营业执照'
                            if (accountUpsertMap.containsKey(gda.BPCode)) {
                                accountInfo.Business_Authorization_No__c = gdds.BusLicenseNo;
                                accountInfo.Business_Paper_Expiration_Date__c = NFMUtil.parseStr2Date(gdds.ValidTo);
                            }
                        } else if (gdds.LicenseType == '05' || gdds.LicenseType == '04') {
                            //'05'为'医疗器械经营许可证','04'为'第二类医疗器械经营备案凭证'
                            if (geDataDetailsMap.containsKey('05') && geDataDetailsMap.containsKey('04')) {
                                Date  validTo05 = NFMUtil.parseStr2Date(geDataDetailsMap.get('05').ValidTo);
                                Date  validTo04 = NFMUtil.parseStr2Date(geDataDetailsMap.get('04').ValidTo);
                                accountInfo.Medical_Equipment_Num__c  = geDataDetailsMap.get('04').BusLicenseNo + '/' + geDataDetailsMap.get('05').BusLicenseNo;
                                if (validTo05 == null || validTo04 == null) {
                                    accountInfo.Medical_Equipment_Expiration_Date__c = validTo04 > validTo05 ? validTo04 : validTo05;
                                } else {
                                    accountInfo.Medical_Equipment_Expiration_Date__c = validTo04 > validTo05 ? validTo05 : validTo04;
                                }

                            } else {
                                accountInfo.Medical_Equipment_Num__c  = geDataDetailsMap.get(gdds.LicenseType).BusLicenseNo;
                                accountInfo.Medical_Equipment_Expiration_Date__c = NFMUtil.parseStr2Date(geDataDetailsMap.get(gdds.LicenseType).ValidTo);
                            }

                        } else if (gdds.LicenseType == '09'){
                            // 20201230 危险化学品经营许可证 XHL AddStart
                            // 转换表里 加了09
                            // 证照类型添加了 危险化学品经营许可证
                            // 客户新增如下字段
                            accountInfo.DGLicenseNo__c = geDataDetailsMap.get(gdds.LicenseType).BusLicenseNo;
                            accountInfo.DGLicenseFrom__c = NFMUtil.parseStr2Date(gdds.ValidFrom);
                            accountInfo.DGLicenseTo__c =  NFMUtil.parseStr2Date(gdds.ValidTo);
                            // String businessTypeStr = gdds.BusinessType;
                            // if (String.isNotBlank(businessTypeStr) && businessTypeStr.contains('存储销售')) {
                            //     accountInfo.DGLicenseInvAllow__c = true;   
                            // }
                            // 20201230 危险化学品经营许可证 XHL AddEnd
                        }
                        
                        if (geDataDetailsMap.containsKey('07')) {
                            //'07'为'税务登记证'
                            if (accountUpsertMap.containsKey(gda.BPCode)) {
                                accountInfo.Tax_Practice_No__c  = geDataDetailsMap.get('07').BusLicenseNo;
                                accountInfo.Tax_Practice_Expiration_Date__c = NFMUtil.parseStr2Date(geDataDetailsMap.get('01').ValidTo);
                            }
                        } else if (geDataDetailsMap.containsKey('01')) {
                            if (accountUpsertMap.containsKey(gda.BPCode)) {
                                accountUpsertMap.get(gda.BPCode).Tax_Practice_No__c = geDataDetailsMap.get('01').BusLicenseNo;
                                accountUpsertMap.get(gda.BPCode).Tax_Practice_Expiration_Date__c = NFMUtil.parseStr2Date(geDataDetailsMap.get('01').ValidTo);
                            }
                        }

                    } else {
                        // 医院主数据的证照信息
                        Account accountInfo = New Account();
                        if (accsMap.containsKey(gda.BPCode)) {
                            accountInfo = accsMap.get(gda.BPCode);
                        }
                        accountUpsertMap.put(gda.BPCode, accountInfo);

                        if (gdds.LicenseType == '01') {
                            //'01'为'营业执照'
                            if (accountUpsertMap.containsKey(gda.BPCode)) {
                                accountInfo.Business_license_no__c = gdds.BusLicenseNo;
                                accountInfo.Business_license_valid__c = NFMUtil.parseStr2Date(gdds.ValidTo);
                            }
                        } else if (gdds.LicenseType == '06') {
                            //'06'为'医疗机构执业许可证'
                            if (accountUpsertMap.containsKey(gda.BPCode)) {
                                accountInfo.RegistrationNumber__c = gdds.BusLicenseNo;
                                accountInfo.Quolified_App_Date__c = Date.today();
                                accountInfo.Valid_From__c = NFMUtil.parseStr2Date(gdds.ValidFrom);
                                accountInfo.Valid_To__c = NFMUtil.parseStr2Date(gdds.ValidTo);
                            }
                        }
                        accountInfo.Quolified_Approve_Status__c = 'Pass';
                        accountInfo.If_Qualifying__c = false;
                    }
                }
            }

            // 客户主数据
            if (accountUpsertMap.size() > 0) {
                //ControllerUtil.EscapeNFM001Trigger = true;
                StaticParameter.EscapeNFM001AgencyContractTrigger2 = true;
                upsert accountUpsertMap.Values();
            }

            // 证照数据
            if (licenseInfoUpsertList.size() > 0 ) {
                ControllerUtil.EscapeNFM001Trigger = true;
                upsert licenseInfoUpsertList;
            }

            // 契约数据
            if (contractUpsertMap.size() > 0) {
                //ControllerUtil.EscapeNFM001Trigger = true;
                StaticParameter.EscapeNFM001AgencyContractTrigger2 = true;
                upsert contractUpsertMap.Values();
            }

            logstr += '\nend';
            rowData.retry_cnt__c = 0;

            //add response to AWS 20220221 start
            SFStatus =true;
            SFMessage+=logstr;
            system.debug('SFMessage---'+SFMessage);
             //add response to AWS 20220221 end
        } catch (Exception ex) {
            Database.rollback(sp);
            System.debug(Logginglevel.ERROR, 'NFM203_' + rowData.MessageGroupNumber__c + ':' + ex.getMessage());
            System.debug(Logginglevel.ERROR, 'NFM203_' + rowData.MessageGroupNumber__c + ':' + ex.getStackTraceString());
            logstr += '\n' + ex.getMessage();
            //add response to AWS 20220221 start
            SFMessage+=ex.getMessage();
            system.debug('SFMessage---'+SFMessage);
            //add response to AWS 20220221 end
            iflog.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + iflog.ErrorLog__c;

            if (rowData.retry_cnt__c == null) rowData.retry_cnt__c = 0;
            if (rowData.retry_cnt__c < batch_retry_max_cnt) {
                rowData.retry_cnt__c++;
                if(!Test.isRunningTest()){
                    LogAutoSendSchedule.assignOneMinute();
                }
            }
            if (rowData.retry_cnt__c >= batch_retry_max_cnt) {
                rowData.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + rowData.ErrorLog__c + '错误次数已经超过自动收信设定的最大次数，请手动收信';
            }
        }
        update rowData;
        iflog.Log__c = logstr;
        if (iflog.Log__c.length() > 131072) {
            iflog.Log__c = iflog.Log__c.subString(0, 131065) + ' ...';
        }
        if (iflog.ErrorLog__c.length() > 32768) {
            iflog.ErrorLog__c = iflog.ErrorLog__c.subString(0, 32760) + ' ...';
        }
        update iflog;
    }
    //获取AgencyApplicationNo(特约经销商申请编码)将其赋值到主数据的"SPO申请单号"
    global static String GetApplicationNo( GeData gda) {
        String result = '';
        for (Contract_Info contractInfo : gda.Contract_Info) {
            result = contractInfo.AgencyApplicationNo;
        }
        return result;
    }
    //WYAN-BS8B2A -XHL -20200925 -Start
    global static String ProtocolExtension(GeData gda) {
        String result = '';
        String logstr = '';
        Map<String,Contract_Info> contractInfoMap = new Map<String,Contract_Info>();
        for (Contract_Info contractInfo : gda.Contract_Info) {

            if (String.isBlank(contractInfo.TermContractNo)) {
                result += 'BPCode[ ' + gda.BPCode + ' ] of TermContractNo is required ,This data is skipped.\n';
                continue;
                
            }
            if (String.isNotBlank(gda.BPCode)) {
                logstr += '管理编码:' + gda.BPCode;
            }
            logstr += '\n本期协议编号:' + contractInfo.TermContractNo;
            logstr += '\nApplyType:' + gda.ApplyType+'(协议延长)';
            contractInfoMap.put(contractInfo.TermContractNo,contractInfo);
            
        }

        if (contractInfoMap != null && contractInfoMap.size() > 0) {

            List<Account> contractList = [select Id, Name, City_Master__c, ParentId, Term_Contract_No__c,Contract_Decide_Start_Date__c,Contract_Decide_End_Date__c from Account where Term_Contract_No__c in: contractInfoMap.keySet()];

            if ( contractList.size() > 0) {
                for (Account acc : contractList) {

                    if (contractInfoMap.containsKey(acc.Term_Contract_No__c)) {
                        Contract_Info contractInfo = contractInfoMap.get(acc.Term_Contract_No__c);
                        //允许报价期间(开始日)
                        
                        if (String.isNotBlank(contractInfo.ContractDecideStartDate)) {
                            logstr += '\n原允许报价期间(开始日)' +acc.Contract_Decide_Start_Date__c;
                            acc.Contract_Decide_Start_Date__c = NFMUtil.parseStr2Date(contractInfo.ContractDecideStartDate);
                            logstr += '\n新允许报价期间(开始日)' +acc.Contract_Decide_Start_Date__c;
                        } 
                        //允许报价期间(结束日)
                        if (String.isNotBlank(contractInfo.ContractDecideEndDate)) {
                            logstr += '\n原允许报价期间(结束日)' +acc.Contract_Decide_End_Date__c;
                            acc.Contract_Decide_End_Date__c = NFMUtil.parseStr2Date(contractInfo.ContractDecideEndDate);
                            logstr += '\n新允许报价期间(结束日)' +acc.Contract_Decide_End_Date__c;
                        } 
                    }
                }

                update contractList;
            } else {
                for (String termContractNo:contractInfoMap.keySet()) {
                    result += 'This Contract[ ' + termContractNo + ' ] not exist,The Data Not  Cancel.\n';
                }
                logstr = '';
            }
            
        }
        result = result + '/' + logstr;
        return result;
    }
    //WYAN-BS8B2A -XHL -20200925 -End
    // 
    /**
     * 收货人层级 信息验证
     * @Author   XHL
     * @DateTime 2021-06-24
     * @param    gda        [接口信息]
     * @return              [通过的收货人信息]
     */
    global static Map<String,List<Consignee_Info>> complianceDatamethod(GeData gda) {

        Map<String,List<Consignee_Info>> result = new Map<String,List<Consignee_Info>>();
            
        for (Consignee_Info consigneeInfo : gda.Consignee_Info) {
            // 联系人名称
            // if (String.isBlank(consigneeInfo.ContactName)) {
            //     continue;
            // }
            // 联系人地址
            if (String.isBlank(consigneeInfo.ContactAddress)) {
                continue;
            }
            List<Consignee_Info> consigneeInfoList = new List<Consignee_Info>();
            if (result.containsKey(gda.BPCode)) {
                consigneeInfoList = result.get(gda.BPCode);
            }
            consigneeInfoList.add(consigneeInfo);
            result.put(gda.BPCode,consigneeInfoList);
        }

        return result;
    }
 
    /**
     * 删除系统中的联系人与收货地址 同时 新增 联系人与收货地址
     * @Author   XHL
     * @DateTime 2021-06-24
     * @param    accountMap        [客户信息]
     * @param    complianceDataMap [收货人信息]
     * @return                     [null]
     */
    global static void insertAddressAndContacts(Map<String, Account> accountMap,Map<String,List<Consignee_Info>> complianceDataMap){
        //本方法 已经兼容传输多个收货人信息 若后面有该需求 可直接进行测试
        Map<String, Account> tempAccountMap = new Map<String, Account>();
        if (accountMap != null && accountMap.size() == 0) {
            // SPO更新收货人信息
            // 1.查找客户
            List<Account> accList = [select Id, RecordTypeId, Name,
                       Management_FormulaCode__c,
                       Business_Paper_Expiration_Date__c,
                       Medical_Equipment_Expiration_Date__c
                       from Account
                       where Management_FormulaCode__c in : complianceDataMap.keySet() ];

            
            for (Account acc : accList) {
                tempAccountMap.put(acc.Management_FormulaCode__c, acc);
            }
        } else  if (accountMap != null && accountMap.size() > 0){
            tempAccountMap =  accountMap;   
        }

        if (tempAccountMap.size() > 0) {
            // 2.查找客户下 SPO发过来的联系人删除
            List<Contact> deleteContactList = [SELECT Id FROM Contact WHERE IsFromSPO__c = true AND Account.Management_FormulaCode__c in : complianceDataMap.keySet()];
            
            if (deleteContactList.size() > 0) {
                delete deleteContactList;
            }

            // //查找 住所阶层1
            // List<Address_Level__c> address_LevelList = [select Id, Name from Address_Level__c ];
            // Map<String, Address_Level__c> regionNameMap = new Map<String, Address_Level__c>();
            // for (Address_Level__c level1 : address_LevelList) {
            //     regionNameMap.put(level1.Name, level1);
            // }
            // // 查找 住所阶层2
            // List<Address_Level2__c> address_Level2List = [select Id, Name from Address_Level2__c];
            // Map<String, Address_Level2__c> cityMap = new Map<String, Address_Level2__c>();
            // for (Address_Level2__c level2 : address_Level2List) {
            //     cityMap.put(level2.Name, level2);
            // }



            // 3.给联系人与收货地址的字段赋值
            List<Contact> insertContactList = new List<Contact>();
            Map<String,Address__c> insertAddressMap = new Map<String,Address__c>();
            List<String> accountCodeList = new List<String>();
            for(String accountCode:tempAccountMap.keySet()){

                if (complianceDataMap.containsKey(accountCode)) {
                    // 获取客户Id
                    for(Consignee_Info info:complianceDataMap.get(accountCode)){
                        // add  sushanhu for pi '000000'为Consignee_Info源数据为空
                        if (!'000000'.equals(info.ContactDataId)) {
                            String accountId = tempAccountMap.get(accountCode).Id;
                        String contactPhone = info.ContactPhone;
                        String contactName = info.ContactName;
                        // String contactAllName = contactAllName(contactName);
                        //update to aws contactName 20220221 sushanhu
                        String contactAllName=info.contactName;

                        // 联系人字段赋值
                        Contact contact  = new Contact();
                        contact.AccountId = accountId;
                        contact.Isactive__c = '有效';
                        contact.Phone = contactPhone;
                        contact.MobilePhone = contactPhone;
                        contact.LastName = contactAllName.split('_')[0];
                        // contact.FirstName = contactAllName.split('_')[1];//delete for pi 20220304 
                        contact.IsFromSPO__c = true;
                        // SFDC电话重复人员创建信息确认  pk 2022-2-28 start
                        contact.RecordTypeId = '01210000000QfWi';
                        // SFDC电话重复人员创建信息确认  pk 2022-2-28 end
                        contact.Ignore_Same_Name__c = true;//不是重复的客户名 跳过 客户人员名字已存在 验证
                        // add pi 密文 start 20220221 sushanhu
                        contact.Phone_Encrypted__c = info.ContactPhoneEncrypted;
                        contact.MobilePhone_Encrypted__c = info.ContactPhoneEncrypted;
                        contact.LastName_Encrypted__c =info.ContactNameEncrypted;
                        contact.AWS_Data_Id__c = info.ContactDataId;
                        // add pi 密文 end 20220221 sushanhu
                        insertContactList.add(contact);
                        if (!'000000'.equals(info.AddressDataId)) {
                            // 收货地址字段赋值
                        String contactCity = info.ContactCity;

                        Address__c addressData = new Address__c();
                        addressData.Customer__c = accountId;//客户
                        addressData.IsFromSPO__c = true;//是否SPO来源
                        addressData.Telephone__c = contactPhone;//电话
                        addressData.Telephone_Encrypted__c =info.ContactPhoneEncrypted;//电话密文 add sushanhu for pi 20220304
                        addressData.Address_Classification__c = '经销商';//地址分类
                        addressData.Detailed_Address__c = info.ContactAddress;//详细地址
                        // 因接口不传输省，导致保存时报错。因此将其注掉,城市字段不赋值 XHL 20210823
                        // if (cityMap.containsKey(contactCity)) {
                        //     addressData.City__c = cityMap.get(contactCity).Id;//市
                        // }
                        // add pi 密文 start sushanhu 20220221
                        addressData.AWS_Data_Id__c =info.AddressDataId;
                        addressData.Detailed_Address_Encrypted__c =info.ContactAddressEncrypted;
                        // add pi 密文 end sushanhu 20220221

                        String mapkey = accountCode + contactName;
                        insertAddressMap.put(mapkey,addressData);
                        accountCodeList.add(accountCode);
                       }
                       
                        }
                        
                        
                    }
                    
                }
            }

            if (insertContactList.size() > 0) {
                // 新增联系人
                insert insertContactList;
                // 查找联系人获取联系人Id，为收货地址赋值
                List<Contact> seleteContactList = [SELECT Id,Name,Account.Management_FormulaCode__c,FullName__c,
                Account.Name FROM Contact WHERE IsFromSPO__c = true AND Account.Management_FormulaCode__c in : accountCodeList];
                List<Address__c> insertAddressList = new List<Address__c>();
                system.debug('seleteContactList--->'+seleteContactList);
                if ( seleteContactList.size() > 0) {
                    
                    for (Contact contact:seleteContactList){

                        String accountCode = contact.Account.Management_FormulaCode__c;
                        String accountName = contact.Account.Name;
                        String mapkey = accountCode + contact.FullName__c;
                        if (insertAddressMap.containsKey(mapkey)) {
                            Address__c addressData = insertAddressMap.get(mapkey);
                            addressData.Contacts__c = contact.Id;//联系人
                            //addressData.Name = accountName + '_'+ contact.Name;//收货地址名称
                            insertAddressList.add(addressData);
                        }
                    }
                    // 新增收货地址
                    if (insertAddressList.size() > 0) {
                        insert insertAddressList;
                    }
                }
            }   
        }
    }

    global static String contactAllName(String contactName){
        // 中国 复姓大全
        String CompoundSurname = '濮阳、公冶、太叔、申屠、公孙、慕容、仲孙、钟离、长孙、宇文、司徒、鲜于、司空、闾丘、子车、亓官、司寇、巫马、公西、颛孙、壤驷、公良、漆雕、乐正、宰父、谷梁、拓跋、夹谷、轩辕、令狐、段干、百里、呼延、东郭、南门、羊舌、微生、公户、公玉、公仪、梁丘、公仲、公上、公门、公山、公坚、左丘、公伯、西门、公祖、第五、公乘、贯丘、公皙、南荣、东里、东宫、仲长、子书、子桑、即墨、达奚、褚师、吴铭';
        // string allname = '朱启贤';
        // contactName = '第五惆怅';
        String lastName = '';
        String firstName = '';
        String result = '';
        if (contactName.contains('·')) {
            lastName = contactName.split('·')[0];
            firstName = contactName.split('·')[1];
        } else {
            if (contactName.length() > 2) {

                system.debug('CompoundSurname--->01' + contactName.subString(0, 2));
                if (CompoundSurname.contains(contactName.subString(0, 2))) {
                    lastName = contactName.substring(0,2);
                    firstName = contactName.substring(2,contactName.length());
                    system.debug('lastName--->'+lastName);
                    system.debug('firstName--->'+firstName);
                } else {
                    lastName = contactName.substring(0,1);
                    firstName = contactName.substring(1,contactName.length());
                    system.debug('lastName--->'+lastName);
                    system.debug('firstName--->'+firstName);           
                }
            } else {
                if (contactName.length() == 2) {
                    lastName = contactName.substring(0,1);
                    firstName = contactName.substring(1,contactName.length());
                    system.debug('lastName--->'+lastName);
                    system.debug('firstName--->'+firstName);
                } else {
                    lastName = contactName;
                    firstName = contactName;
                    system.debug('lastName--->'+lastName);
                    system.debug('firstName--->'+firstName);
                }
            }
        }
        if (!contactName.equals(lastName+firstName)) {
            lastName = contactName;
            firstName = contactName;
        }
        result = lastName + '_' + firstName;
        //system.debug('CompoundSurname--->02' + CompoundSurname);
        return result;
    }
}