/**
 * RepairTrigger.trigger より NFM103Trigger() を呼び出す
 */
public without sharing class NFM103Controller {
    //NFM103修改Rest start
    public static String status;
    public class NFM103 {
        public RepairRequest_element RepairRequest;
    }
    // WLIG-BXQBH6 nfm103接口的详细回复的定义 start
    public static string ResponseBody;
    public static String SAPRepairNo;
    public class NFM103Response {
        public RepairRequest_element RepairRequest;
        public response[] response;
    }
    public class response {
        public LOG LOG;
    }
    public class LOG {
        public string BusinessDocumentProcessingResultCode;
        public string MaximumLogItemSeverityCode;
        public string Item;
        public string TypeID;
        public string SeverityCode;
        public string Note;
        public string WebURI;
        public string SAPRepairNo;

    }
    // WLIG-BXQBH6 nfm103接口的详细回复的定义 end

    public class RepairRequest_element {
        public NFMUtil.Monitoring Monitoring;
        public GeneralData_element[] GeneralData;
    }

    // tqz 2020/06/18 start
    public class IntakeInfos {
        public String IntakeUniversalCode;
        // public String EtQManagementNo;
    }
    // tqz 2020/06/18 end

    public class GeneralData_element {
        public String Workshop;
        public String SalesOfficeCode;
        public String EndUserNo;
        public String DepartmentNo;
        public String SAPAgentNo;
        public String RepairOTCode;
        public String RepairModel;
        public String SerialNo;
        public String FailureSymptomDescription;
        public String RepairSource;
        public String CompanyCodeOfEquipment;
        public String ProvinceCodeOfEquipment;
        public String EquipmentFixedAssetNo;
        public String RepairType;
        public String PaperRepairRequestNo;
        public String SFDCRepairNo;
        public String BreakdownStartDate;
        public String FSEReceiveDate;
        public String FSEDeliverDate;
        public String FSEPerson;
        public String FSEPersonEmail;
        public String RecordPersonID;
        public String RecordPersonEmail;
        public String RepairContractObject;
        public String RepairContractNumber;
        public String NewProductGuaranteeObject;
        public String InquiryNo;
        public String ProductDeliveryDate;
        public String InstallationDate;
        public String GuaranteeEndDate;
        public String ReRepairObject;
        public String LastSFDCRepairNo;
        public String RepairCancellationHistory;
        public String LastSFDCRepairCancellationNo;
        public String LastSFDCrepairCancellationReason;
        public String TradeType;
        // LHJ 多年保修 Start
        public String RepairCostType;
        public String RepairTypeQIS;
        // LHJ 多年保修 End
        // tqz 2020/06/18 start
        public IntakeInfos[] IntakeInfo;
        public String EtQManagementNo;
        // tqz 2020/06/18 end
        //add by rentx WLIG-C2GBMQ 2021-04-29 start
        public String AnimalExperiment;
        //add by rentx WLIG-C2GBMQ 2021-04-29 end;

        //add by wangweipeng  2021/07/14   start
        //把直返收货地址信息通过接口，传到SAP
        //public String Repairno;//修理单
        public String CustomerName;//客户名称
        public String ContactPerson;//联系人姓名
        public String Telephone;//电话
        public String City;//城市  市
        public String Address;//地址
        public String Postal;//邮编
        public String ReturnType;//返品方式
        public String UpdateStatus;//直返修改标识
        //add by wangweipeng  2021/07/14   end
        //add pi 加密 sushanhu 20220222 start
        //public String DataId;//AWS存储凭证
        //add pi 加密 sushanhu 20220222 end

        //20220330 lt WLIG-CCT9UG 【委托】关于市场多年保计提金调整  start
        public String QuotationDate;
        //20220330 lt WLIG-CCT9UG 【委托】关于市场多年保计提金调整  end


    }
    ////NFM103修改Rest end

    // Repair__cのId
    public static Set<Id> NFM103_Ids = new Set<Id>();
    public static String debug_msg = '';

    // on Repair__c (after insert, after update)
    // 新規修理、or 受付用の項目を編集した時（RepairOrderStatusCode__c = A95時のみ 受付用の項目を編集 できます）
    public static void NFM103Trigger(List<Repair__c> newList, Map<Id, Repair__c> newMap, List<Repair__c> oldList, Map<Id, Repair__c> oldMap) {
        System.debug('-----NFM103Trigger start');
        List<Id> rprIds = new List<Id>();           // 更新対象 Id をセット
        Map<Id, Repair__c> updMap = new Map<Id, Repair__c>();
        if (Trigger.isAfter) {
            if (Trigger.isInsert) {
                for (Repair__c rpr : newList) {
                    if (rpr.status__c == '1.受理完毕' ) {
                        if (NFM103Controller.NFM103_Ids.contains(rpr.Id) == false) {
                            NFM103_Ids.add(rpr.Id);
                            rprIds.add(rpr.Id);
                            updMap.put(rpr.Id, new Repair__c(Id = rpr.Id
                                                                  , BranchOfficeRecievedDate__c = Date.today()
                                                                          , Return_Without_Repair_History_Flg__c = rpr.Return_Without_Repair_History_Flg_F__c
                                                                                  , ReRepairObject__c = rpr.ReRepairObject_F__c
                                                            ));
                            NFM103Controller.debug_msg += 'NFM103_callout_insert_' + rpr.Name;
                        }
                    }
                }
            }
            if (Trigger.isUpdate) {
                System.debug('update触发器 进入');
                for (Repair__c rpr : newList) {
                    // 2020/06/19 start
                    System.debug('newList集合 进入');
                    // if (rpr.status__c == '1.受理完毕' && oldMap.get(rpr.Id).status__c != rpr.status__c) {
                    // Gzw 申请修理时，判断SAP_Transfer_time__c有值时，发送SAP
                    System.debug('当前修理 :' + rpr.Id);
                    System.debug('rpr的状态 :' + rpr.status__c);
                    System.debug('rpr的Old SAP...Time :' + oldMap.get(rpr.Id).SAP_Transfer_time__c);
                    System.debug('rpr的SAP...Time :' + rpr.SAP_Transfer_time__c);
                    // 2021/07/15  收货地址采用时，可以选择再次上传SAP数据
                    System.debug('rpr的直返收货地址... :'+rpr.Address_type__c);
                    //if ((rpr.status__c == '0.申请完毕' || rpr.status__c == '1.受理完毕' ) && (oldMap.get(rpr.Id).SAP_Transfer_time__c == null && rpr.SAP_Transfer_time__c != null)) {
                        // 2020/06/19 end
                    //2021/07/23  wangweipeng  start  新加再次上传数据到SAP，根据条件：直返标识为 X，并且Address_Type_Index__c 是否发生变化
                    //Address_Type_Index__c  在采用按钮是，并选择再次上传数据到SAP时，会加1
                    if (((rpr.status__c == '0.申请完毕' || rpr.status__c == '1.受理完毕' ) && (oldMap.get(rpr.Id).SAP_Transfer_time__c == null && rpr.SAP_Transfer_time__c != null)) || (rpr.Address_type__c=='X' && (rpr.Address_Type_Index__c != oldMap.get(rpr.Id).Address_Type_Index__c))) {
                    //2021/07/23  wangweipeng  end
                        System.debug('if 条件进入');
                        if (NFM103Controller.NFM103_Ids.contains(rpr.Id) == false) {
                            System.debug('if2 条件也进来了 ');
                            NFM103_Ids.add(rpr.Id);
                            rprIds.add(rpr.Id);
                            updMap.put(rpr.Id, new Repair__c(Id = rpr.Id
                                                                  , BranchOfficeRecievedDate__c = Date.today()
                                                                          , Return_Without_Repair_History_Flg__c = rpr.Return_Without_Repair_History_Flg_F__c
                                                                                  , ReRepairObject__c = rpr.ReRepairObject_F__c
                                                            ));
                            NFM103Controller.debug_msg += 'NFM103_callout_update_' + rpr.Name;
                        }
                    }
//                    // RepairOrderStatusCode__c = A95 （取消修理受理）の時だけ 受付用の項目を編集した時、再度 SAP に送信
//                    // TODO SAP側 同じ番号の再送はできるか？、使ってないかも！！
//                    else if (NFM103Controller.NFM103_Ids.contains(rpr.Id) == false && rpr.RepairOrderStatusCode__c == 'A95') {
//                        if (oldMap.get(rpr.Id).Repair_Detail__c != rpr.Repair_Detail__c
//                                || oldMap.get(rpr.Id).RepairSource__c != rpr.RepairSource__c
//                                || oldMap.get(rpr.Id).On_site_repair__c != rpr.On_site_repair__c
//                                || oldMap.get(rpr.Id).PaperRepairRequestNo__c != rpr.PaperRepairRequestNo__c
//                                || oldMap.get(rpr.Id).Failure_Occurrence_Date__c != rpr.Failure_Occurrence_Date__c
//                                || oldMap.get(rpr.Id).On_Site_Repair_Order_Date__c != rpr.On_Site_Repair_Order_Date__c
//                                || oldMap.get(rpr.Id).Send_To_RC_Date__c != rpr.Send_To_RC_Date__c
//                        ) {
//                            rpr.RepairOrderStatusCode__c = '';
//                            NFM103_Ids.add(rpr.Id);
//                            rprIds.add(rpr.Id);
//                            NFM103Controller.debug_msg += 'NFM103_callout_update2_' + rpr.Name;
//                        }
//                    }
                }
            }
        }

        if (rprIds.size() > 0) {
            update updMap.values();
            // MessageGroupNumber の採番
            BatchIF_Log__c iflog = new BatchIF_Log__c();
            iflog.Type__c = 'NFM103';
            iflog.Log__c  = 'callout start\n';
            insert iflog;
            iflog = [Select Id, Name from BatchIF_Log__c where Id = :iflog.Id];
            System.debug(Logginglevel.DEBUG, 'NFM103_' + iflog.Name + ' start');                  // callout の中 end のlogを出します
            NFM103Controller.callout(iflog.Id, rprIds);
        }
        System.debug('-----NFM103Trigger end');
    }

    /**
     * NFM103の送信処理
     *
     * @param iflog_Id           ログテーブルのId
     * @param repairIds          送信対象修理
     */
    @future (callout = true)
    public static void callout(String iflog_Id, List<Id> repairIds) {

        if (repairIds == null || repairIds.size() == 0) {
            return;
        }
        /*        Nfm103Sync.HTTPS_Port stub = new Nfm103Sync.HTTPS_Port();
                stub.timeout_x = 100000; // timeout in milliseconds
                stub.endpoint_x = NFMUtil.NFM103_ENDPOINT;
                stub.inputHttpHeaders_x = new Map<String, String>();
                stub.inputHttpHeaders_x.put('Authorization', NFMUtil.Authorization);
                if (NFMUtil.CLIENT_CERT_NAME != null) {
                    stub.clientCertName_x = NFMUtil.CLIENT_CERT_NAME;
                }
                */
        // MessageGroupNumber の取得
        List<BatchIF_Log__c> iflogList = [Select Id, Name, Log__c, ErrorLog__c from BatchIF_Log__c where Id = :iflog_Id];
        BatchIF_Log__c iflog = null;
        if (iflogList.size() > 0) {
            iflog = iflogList.get(0);
            iflog.ErrorLog__c = '';
        } else {
            // データ取れってないとは、rollbackされていることです
            return;
        }
        String logstr = iflog.Log__c + ' ' + 'NumberOfRecord=' + repairIds.size() + '\n';

        // Monitoringの設定
        Datetime nowDT = Datetime.now();
        String nowStr = nowDT.format('yyyyMMddHHmm');
        //NFM103修改Rest start
        // Nfm103Sync.RepairRequest_element repairRequest = new Nfm103Sync.RepairRequest_element();
        RepairRequest_element repairRequest = new RepairRequest_element();

        // repairRequest.Monitoring = new OlympusCoJpCommonMessage.Monitoring();
        repairRequest.Monitoring = new NFMUtil.Monitoring();
        //NFM103修改Rest end
        repairRequest.Monitoring.Tag                  = 'MSGH';
        repairRequest.Monitoring.Sender               = '8402';
        repairRequest.Monitoring.Receiver             = '1330';
        repairRequest.Monitoring.MessageType          = 'NFM103';
        repairRequest.Monitoring.MessageGroupNumber   = iflog.Name;
        repairRequest.Monitoring.NumberOfRecord       = '' + repairIds.size();
        repairRequest.Monitoring.TransmissionDateTime = nowStr;
        repairRequest.Monitoring.Text = '';

        BatchIF_Log__c rowData = null;
        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 = 'Opportunity'];
        for (BatchIF_Transfer__c t : transferList) {
            transferMap.put(t.Column__c + t.Internal_value__c, t.External_value__c);
        }

        //修理表的 返品方式
        Map<String, String> ReturnsProductWayMap = new Map<String, String>();
        List<BatchIF_Transfer__c> ReturnsProductWayList = [select Table__c,
                                                         Column__c,
                                                         External_value__c,
                                                         Internal_value__c
                                                    from BatchIF_Transfer__c
                                                   where Dropped_Flag__c = false
                                                     and Table__c = 'Repair__c'];
        for (BatchIF_Transfer__c t : ReturnsProductWayList) {
            ReturnsProductWayMap.put(t.Column__c + t.Internal_value__c, t.External_value__c);
        }

        try {
            // 転送データを取得、参照先のデータがあるので、ここで検索必要です。
            List<Repair__c> recptList = [select
                                         Id, Name, Workshop__c, SalesOfficeCode__c,
                                         Repair_Detail__c, RepairSource__c, On_site_repair__c, PaperRepairRequestNo__c,
                                         Failure_Occurrence_Date__c, On_Site_Repair_Order_Date__c, Send_To_RC_Date__c,
                                         Hospital__r.Management_Code__c, Account__r.Management_Code__c, Dealer__r.Management_Code__c,
                                         Incharge_Staff__r.alias, Incharge_Staff_Email__c, Incharge_Staff_Contact__c, Incharge_Staff_Contact__r.Name, CreatedBy.Alias, CreatedBy.Email,
                                         Delivered_Product__r.Product2.Asset_Model_No__c, Delivered_Product__r.SerialNumber, Delivered_Product__r.LastSFDCRepairNo__c,
                                         Delivered_Product__r.Internal_Asset_number__c, Delivered_Product__r.Order_No__c,
                                         Delivered_Product__r.Posting_Date__c, Delivered_Product__r.InstallDate, Delivered_Product__r.Guarantee_period_for_products__c,
                                         Delivered_Product__r.CompanyCodeOfEquipment__c, Delivered_Product__r.ProvinceCodeOfEquipment__c,
                                         CompanyCodeOfEquipment__c, ProvinceCodeOfEquipment__c,
                                         Delivered_Product__r.Product2.ProductCode, Delivered_Product__r.Product2.CanRepairAccsessary__c,
                                         Delivered_Product__r.Return_Without_Repair__c, Delivered_Product__r.Return_Without_Repair__r.Name,
                                         Delivered_Product__r.Return_Without_Repair__r.Return_Without_Repair_Reason__c, Delivered_Product__r.Return_Without_Repair__r.CancellationReason__c,
                                         NewProductGuaranteeObject__c, Delivered_Product__r.ReRepairObject__c, Delivered_Product__r.Return_Without_Repair_History_Flg__c,
                                         Maintenance_Contract__c, Maintenance_Contract__r.Maintenance_Contract_No__c, Maintenance_Contract__r.Status__c,
                                         Delivered_Product__r.Backorder__r.Opportunity__r.Trade__c, Complaint_Number__c,
                                         // 多年保修 LHJ Start
                                         RepairCostType__c, RepairType_QIS__c,
                                         Delivered_Product__r.SerMarGuranteeType__c,
                                         // 多年保修 LHJ End
                                         // tqz 2020/06/03 start
                                         // Intake universal code
                                         ASReportedCode__c
                                         // tqz 2020/06/03 end
                                         // Gzw 20201216 NFM103传SAP的时候，需要传FSE修理申请时的维修合同信息 start
                                         , FSE_ApplyForRepair_Day__c, Contract_Start_Date__c, Contract_End_Date__c
                                         // Gzw 20201216 NFM103传SAP的时候，需要传FSE修理申请时的维修合同信息 end
                                         // 2021-01-04 mzy  HWAG-BWB4ME   修改NFM103接口上传的 维修合同号 start
                                         , Dummy_Maintenance_Contract_No_F__c
                                         // 2021-01-04 mzy  HWAG-BWB4ME   修改NFM103接口上传的 维修合同号 end
                                         //add by rentx WLIG-C2GBMQ 2021-04-29 start
                                         ,AnimalExperiment__c 
                                         //add by rentx WLIG-C2GBMQ 2021-04-29 end;
                                         
                                         //add by wangweipeng  2021/07/14   start
                                         ,SAP_Transfer_time__c
                                         ,Address_type__c
                                         ,address_Contacts_Name__c//地址客户
                                         ,address_Contacts__c   //联系人名称
                                         ,address_Telephone__c  //联系电话
                                         ,address_City__c   //市
                                         ,Detailed_Address__c   //详细地址
                                         ,address_ZipCode__c    //邮编
                                         ,Returns_Product_way__c    //返品方式
                                         ,FSE_ApplyForRepair_time__c    //申请修理时间
                                         //add by wangweipeng  2021/07/14   start
                                         //,AWS_Data_Id__c //add by sushanhu AWSDateID for PIPL
                                         //20220330 lt WLIG-CCT9UG 【委托】关于市场多年保计提金调整  start
                                         ,Delivered_Product__r.Backorder__r.Opportunity__r.SAP_Send_OK_Date__c
                                         //20220330 lt WLIG-CCT9UG 【委托】关于市场多年保计提金调整  end
                                         from Repair__c where Id IN :repairIds];          // 削除データを検索しないはず、All ROWS いらないはず
            System.debug(Logginglevel.DEBUG, 'NFM103_ recptList.size()=' + recptList.size());

            // GeneralDataのデータの設定
            // NFM103修改Rest start
            // repairRequest.GeneralData = new List<Nfm103Sync.GeneralData_element>();
            repairRequest.GeneralData = new List<GeneralData_element>();
            //NFM103修改Rest start
            for (Repair__c rpr : recptList) {
                // NFM103修改Rest start
                // Nfm103Sync.GeneralData_element element = new Nfm103Sync.GeneralData_element();
                GeneralData_element element = new GeneralData_element();
                // NFM103修改Rest end

                element.SFDCRepairNo              = rpr.Name;
                element.Workshop                  = rpr.Workshop__c;                                    // 数式
                element.SalesOfficeCode           = rpr.SalesOfficeCode__c;                             // 数式
                element.EndUserNo                 = rpr.Hospital__r.Management_Code__c;
                element.DepartmentNo              = rpr.Account__r.Management_Code__c;
                element.SAPAgentNo                = rpr.Dealer__r.Management_Code__c;
                element.RepairOTCode              = rpr.Delivered_Product__r.Product2.ProductCode;
                //LJPH-C7Z8AP LY Start
                element.RepairModel               = rpr.Delivered_Product__r.Product2.Asset_Model_No__c;
                // LJPH-C9SB9C LHJ 特殊对应 Start
                if (element.RepairModel == 'G400') {
                    element.RepairModel = '777000';
                } else if (element.RepairModel == 'EU-ME2(KEYBOARD)') {
                    element.RepairModel = 'MAJ-1995';
                }
                // LJPH-C9SB9C LHJ 特殊对应 End
                //LJPH-C7Z8AP LY END
                
                // HWAG-BJTBPV LHJ Start
                // element.SerialNo                  = rpr.Delivered_Product__r.SerialNumber;
                element.SerialNo                  = rpr.Delivered_Product__r.SerialNumber == null ? null :
                                                    rpr.Delivered_Product__r.SerialNumber.replace('%', '％');
                // HWAG-BJTBPV LHJ End
                element.FailureSymptomDescription = rpr.Repair_Detail__c == null ?
                                                    rpr.Repair_Detail__c : rpr.Repair_Detail__c.replaceAll('%', '％');

                element.RepairSource              = rpr.RepairSource__c;
                element.CompanyCodeOfEquipment    = String.isBlank(rpr.Delivered_Product__r.CompanyCodeOfEquipment__c) ?
                                                    rpr.CompanyCodeOfEquipment__c : rpr.Delivered_Product__r.CompanyCodeOfEquipment__c;
                element.ProvinceCodeOfEquipment   = String.isBlank(rpr.Delivered_Product__r.ProvinceCodeOfEquipment__c) ?
                                                    rpr.ProvinceCodeOfEquipment__c : rpr.Delivered_Product__r.ProvinceCodeOfEquipment__c;
                element.EquipmentFixedAssetNo     = rpr.Delivered_Product__r.Internal_Asset_number__c;
                element.RepairType                = rpr.On_site_repair__c;
                element.PaperRepairRequestNo      = rpr.PaperRepairRequestNo__c;
                element.BreakdownStartDate        = NFMUtil.formatDate2Str(rpr.Failure_Occurrence_Date__c);
                element.FSEReceiveDate            = NFMUtil.formatDate2Str(rpr.On_Site_Repair_Order_Date__c);   // TODO 必須ではないけど、修理受付後入力したらどうやってSAPに送る？
                element.FSEDeliverDate            = NFMUtil.formatDate2Str(rpr.Send_To_RC_Date__c);             // TODO 必須ではないけど、修理受付後入力したらどうやってSAPに送る？
                element.TradeType                 = NFMUtil.getMapValue(transferMap, 'Trade__c', rpr.Delivered_Product__r.Backorder__r.Opportunity__r.Trade__c, iflog);

                //20220330 lt WLIG-CCT9UG 【委托】关于市场多年保计提金调整  start
                element.QuotationDate = NFMUtil.formatDateTime2StrSprit(rpr.Delivered_Product__r.Backorder__r.Opportunity__r.SAP_Send_OK_Date__c).replaceAll('/', '');
                //20220330 lt WLIG-CCT9UG 【委托】关于市场多年保计提金调整  end

                // 多年保修 LHJ Start
                element.RepairCostType            = rpr.Delivered_Product__r.SerMarGuranteeType__c != '市场多年保修'  ? '' : rpr.RepairCostType__c;
                element.RepairTypeQIS             = rpr.RepairType_QIS__c;
                // 多年保修 LHJ End
                //element.TradeType                 = rpr.Delivered_Product__r.Backorder__r.Opportunity__r.Trade__c;
                // 如果手动输入修理委托者有值，使用手动输入的修理委托者
                if (String.isBlank(rpr.Incharge_Staff_Contact__c)) {
                    element.FSEPerson                 = rpr.Incharge_Staff__r.alias;
                    element.FSEPersonEmail            = rpr.Incharge_Staff_Email__c;
                    NFM103Controller.debug_msg += '_user_' + rpr.Incharge_Staff__c;
                } else {
                    element.FSEPerson                 = rpr.Incharge_Staff_Contact__r.Name;
                    element.FSEPersonEmail            = rpr.Incharge_Staff_Email__c;
                    NFM103Controller.debug_msg += '_contact_' + rpr.Incharge_Staff_Contact__c;
                }
                element.RecordPersonID            = rpr.CreatedBy.Alias;
                element.RecordPersonEmail         = rpr.CreatedBy.Email;
                element.RepairContractObject      = '';
                element.RepairContractNumber      = '';
                /*// Gzw 20201216 NFM103传SAP的时候，需要传FSE修理申请时的维修合同信息 start
                // if (rpr.Maintenance_Contract__c != null && rpr.Maintenance_Contract__r.Status__c == '契約') {
                if (rpr.Maintenance_Contract__c != null && rpr.FSE_ApplyForRepair_Day__c != null
                    && rpr.FSE_ApplyForRepair_Day__c >= rpr.Contract_Start_Date__c && rpr.FSE_ApplyForRepair_Day__c <= rpr.Contract_End_Date__c) {
                // Gzw 20201216 NFM103传SAP的时候，需要传FSE修理申请时的维修合同信息 end
                    element.RepairContractObject  = 'X';
                    element.RepairContractNumber  = rpr.Maintenance_Contract__r.Maintenance_Contract_No__c;
                }*/
                // 2021-01-07  mzy  update  多年保修外贸NFM103接口修改  start
                String tradeType = rpr.Delivered_Product__r.Backorder__r.Opportunity__r.Trade__c;

                String NewProductGuaranteeObject = rpr.NewProductGuaranteeObject__c == null ? '':  rpr.NewProductGuaranteeObject__c;


                // 维修合同
                if (rpr.Maintenance_Contract__c != null && rpr.FSE_ApplyForRepair_Day__c != null
                        && rpr.FSE_ApplyForRepair_Day__c >= rpr.Contract_Start_Date__c && rpr.FSE_ApplyForRepair_Day__c <= rpr.Contract_End_Date__c) {
                    element.RepairContractObject  = 'X';
                    element.RepairContractNumber  = rpr.Maintenance_Contract__r.Maintenance_Contract_No__c;
                } else {
                    if (!String.isBlank(tradeType) && tradeType.equals('外貿')) {
                        // 多年保外贸服务多年保 (生成虚拟维修合同号) 和 多年保外贸市场多年保 (生成虚拟维修合同号)
                        // 维修合同标识（RepairContractObject）上传为空。
                        if (NewProductGuaranteeObject.equals('2: 服务多年保修') || NewProductGuaranteeObject.equals('8: 市场多年保修')) {
                            element.RepairContractObject  = '';
                            element.RepairContractNumber = rpr.Dummy_Maintenance_Contract_No_F__c;
                        }

                    }
                }

                // 2021-01-07  mzy  update 多年保修外贸NFM103接口修改 end
                element.NewProductGuaranteeObject = '';
                if (String.isBlank(rpr.NewProductGuaranteeObject__c) == false && rpr.NewProductGuaranteeObject__c.contains(':')) {
                    element.NewProductGuaranteeObject = rpr.NewProductGuaranteeObject__c.substring(0, rpr.NewProductGuaranteeObject__c.indexOf(':'));
                }
                element.InquiryNo                 = rpr.Delivered_Product__r.Order_No__c;
                element.ProductDeliveryDate       = NFMUtil.formatDate2Str(rpr.Delivered_Product__r.Posting_Date__c);
                element.InstallationDate          = NFMUtil.formatDate2Str(rpr.Delivered_Product__r.InstallDate);
                element.GuaranteeEndDate          = NFMUtil.formatDate2Str(rpr.Delivered_Product__r.Guarantee_period_for_products__c);
                element.ReRepairObject            = rpr.Delivered_Product__r.ReRepairObject__c == false ? '' : 'X';          // TODO 再修理保修对象品、最後修理したあとの経過日より計算？
                element.LastSFDCRepairNo          = rpr.Delivered_Product__r.LastSFDCRepairNo__c;                            // TODO Assetに数式、修理に Text 項目
                element.RepairCancellationHistory = rpr.Delivered_Product__r.Return_Without_Repair_History_Flg__c == false ? '' : 'X';           // TODO 未修理归还申请 の業務フロー？
                element.LastSFDCRepairCancellationNo = rpr.Delivered_Product__r.Return_Without_Repair__r.Name;
                element.LastSFDCrepairCancellationReason = (rpr.Delivered_Product__r.Return_Without_Repair__r.Return_Without_Repair_Reason__c == 'I/F理由、確認') ? rpr.Delivered_Product__r.Return_Without_Repair__r.CancellationReason__c : rpr.Delivered_Product__r.Return_Without_Repair__r.Return_Without_Repair_Reason__c;
                repairRequest.GeneralData.add(element);
                logstr += '[' + element.SFDCRepairNo + ',' +  element.LastSFDCRepairNo + ']Department[' + element.DepartmentNo + ']';
                // tqz 2020/06/18 start
                element.EtQManagementNo = rpr.Complaint_Number__c;
                element.IntakeInfo = new List<IntakeInfos>();
                String Intake_universal_codes = rpr.ASReportedCode__c;
                if (!String.isBlank(Intake_universal_codes)) {
                    String[] codes = Intake_universal_codes.split(',');
                    for (String code : codes) {
                        IntakeInfos intake =  new IntakeInfos();
                        intake.IntakeUniversalCode = code;
                        element.IntakeInfo.add(intake);
                    }
                }
                // tqz 2020/06/18 end

                //add by rentx WLIG-C2GBMQ 2021-04-29 start
                element.AnimalExperiment = rpr.AnimalExperiment__c ? 'Y':'';
                //add by rentx WLIG-C2GBMQ 2021-04-29 end;
                
                //add by wangweipeng  2021/07/14   start
                 element.CustomerName               = rpr.address_Contacts_Name__c;//客户名
                 element.ContactPerson              = rpr.address_Contacts__c;   //联系人名称
                 element.Telephone                  = rpr.address_Telephone__c;  //联系电话
                 element.City                       = rpr.address_City__c;   //市
                 element.Address                    = rpr.Detailed_Address__c;   //详细地址
                 element.Postal                     = rpr.address_ZipCode__c;    //邮编
                 element.ReturnType                 = NFMUtil.getMapValue(ReturnsProductWayMap,'Returns_Product_way__c', rpr.Returns_Product_way__c, iflog);//返品方式
                 element.UpdateStatus               = rpr.Address_type__c;    //申请修理时间
                 //add by wangweipeng  2021/07/14   end
                 //add pi 密文 sushanhu 20220222 start
                 //element.DataId                     =rpr.AWS_Data_Id__c;//aws存储凭证
                 //add pi 密文 sushanhu 20220222 end

            }

            if (repairRequest.GeneralData.size() > 0) {
                //Nfm103Sync.RepairRequest_element[] pRepairRequest = new Nfm103Sync.RepairRequest_element[] { repairRequest };
                logstr += '\ncallout count=' + repairRequest.GeneralData.size();
                //OlympusCoJpCommonMessage.LOG_element[] logs = stub.NFM103_Sync_BC2GPI(pRepairRequest);
                // 原則非同期ですので、logsを確認する必要がないでしょう。
                NFMUtil.Monitoring Monitoring   = new NFMUtil.Monitoring();
                Monitoring.Tag                  = repairRequest.Monitoring.Tag;
                Monitoring.Sender               = repairRequest.Monitoring.Sender;
                Monitoring.Receiver             = repairRequest.Monitoring.Receiver;
                Monitoring.MessageType          = repairRequest.Monitoring.MessageType;
                Monitoring.MessageGroupNumber   = repairRequest.Monitoring.MessageGroupNumber;
                Monitoring.NumberOfRecord       = repairRequest.Monitoring.NumberOfRecord;
                Monitoring.TransmissionDateTime = repairRequest.Monitoring.TransmissionDateTime;
                Monitoring.Text = '';

                // NFM103修改Rest 新增 start
                NFM103 nfm103 = new NFM103();
                nfm103.RepairRequest = new RepairRequest_element();
                nfm103.RepairRequest = repairRequest;
                // NFM103修改Rest 新增 end

                // NFM103修改Rest start
                // rowData = NFMUtil.makeRowData(Monitoring, 'NFM103', repairRequest);
                rowData = NFMUtil.makeRowData(Monitoring, 'NFM103', nfm103);
                // NFM103修改Rest end
                execute(rowData, iflog);
            }
            logstr += '\nStatus:' + status;
            // WLIG-BXQBH6 start 保存回复内容
            logstr += '\nResponse:' + responseBody;
            if(string.isNotEmpty(SAPRepairNo)){
                Repair__c rpr = new repair__c(id = repairIds[0], SAPRepairNo__c = SAPRepairNo);
                update rpr;
            }
            // WLIG-BXQBH6 end 保存回复内容
            logstr += '\nend';
        } catch (Exception ex) {
            // エラーが発生した場合
            System.debug(Logginglevel.ERROR, 'NFM103_' + iflog.Name + ':' + ex.getMessage());
            System.debug(Logginglevel.ERROR, 'NFM103_' + iflog.Name + ':' + ex.getStackTraceString());
            logstr += ex.getMessage();
            iflog.ErrorLog__c += ex.getMessage() + '\n';
            iflog.ErrorLog__c += ex.getStackTraceString() + '\n';
        }
        if (rowData != null) {
            insert rowData;
        }
        System.debug(Logginglevel.DEBUG, 'NFM103_' + iflog.Name + ' end');
        iflog.Log__c = logstr;
        update iflog;
    }

    public static void execute(BatchIF_Log__c rowData, BatchIF_Log__c iflog) {
        //gaozw
        Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
        String rowDataStr = NFMUtil.getRowDataStr(rowData);

        // NFM103修改Rest start
        // Nfm103Sync.RepairRequest_element repairRequest = (Nfm103Sync.RepairRequest_element) JSON.deserialize(rowDataStr, Nfm103Sync.RepairRequest_element.class);
        NFM103 nfm103 = (NFM103) JSON.deserialize(rowDataStr, NFM103.class);

        // String logstr = repairRequest.Monitoring.MessageGroupNumber + ' start\n';
        String logstr = nfm103.RepairRequest.Monitoring.MessageGroupNumber + ' start\n';
        // NFM103修改Rest end
        Boolean needUpdateIflog = false;
        if  (iflog == null) {
            needUpdateIflog = true;
            iflog = new BatchIF_Log__c();
            iflog.Type__c = 'NFM103';
            // NFM103修改Rest start
            // iflog.MessageGroupNumber__c = repairRequest.Monitoring.MessageGroupNumber;
            iflog.MessageGroupNumber__c = nfm103.RepairRequest.Monitoring.MessageGroupNumber;
            // NFM103修改Rest end
            iflog.Log__c = logstr;
            iflog.ErrorLog__c = '';
            //insert iflog;
            //iflog = [Select Id, Name, Log__c, ErrorLog__c from BatchIF_Log__c where Id = :iflog.Id];
        } else {
            logstr = iflog.Log__c;
        }
        try {
            // NFM103修改Rest start
            // Nfm103Sync.HTTPS_Port stub = new Nfm103Sync.HTTPS_Port();
            // stub.timeout_x = 100000; // timeout in milliseconds
            // stub.endpoint_x = NFMUtil.NFM103_ENDPOINT;
            // stub.inputHttpHeaders_x = new Map<String, String>();
            // stub.inputHttpHeaders_x.put('Authorization', NFMUtil.Authorization);
            // if (NFMUtil.CLIENT_CERT_NAME != null) {
            //     stub.clientCertName_x = NFMUtil.CLIENT_CERT_NAME;
            // }
            // Nfm103Sync.RepairRequest_element[] pRepairRequest = new Nfm103Sync.RepairRequest_element[] { repairRequest };
            // NFM103Controller.debug_msg += ', execute()';
            // OlympusCoJpCommonMessage.LOG_element[] logs = stub.NFM103_Sync_BC2GPI(pRepairRequest);
            // NFM103修改Rest end

            // WLIG-BXQBH6 start
            NFMUtil.response response =
                NFMUtil.sendToSapStatusAndBody(rowDataStr, NFMUtil.NFM103_ENDPOINT);
                //update to aws 20220222 sushanhu start for PIPL
            //    PIHelper.PIIntegration NFM103AWS =PIHelper.getPIIntegrationInfo('NFM103');
            //    NFMUtil.response response =     NFMUtil.sendToPiAWS(rowDataStr, NFM103AWS.newUrl,NFM103AWS.token);
                //update to aws 20220222 sushanhu end for PIPL
                status = response.status;
                system.debug('AWS Response status:'+status);
            ResponseBody = response.responseBody;
            //update to aws 20220302 sushanhu start for PIPL
            // Map<String, Object> results = (Map<String, Object>)JSON.deserializeUntyped(ResponseBody);
            // system.System.debug('NGM103 AWS result--'+ ResponseBody);
            //update to aws 20220302 sushanhu end for PIPL
            NFM103Response NFM103Response = new NFM103Response();
            system.debug(ResponseBody);
            if (string.isNotEmpty(ResponseBody)) {
                NFM103Response =
                    (NFM103Response) JSON.deserializeStrict(ResponseBody, NFM103Response.class);
            }
            if (NFM103Response.response != null &&
                    NFM103Response.response.size() > 0 &&
                    NFM103Response.response[0].LOG != null &&
                    string.isNotEmpty(NFM103Response.response[0].LOG.SAPRepairNo)) {
                SAPRepairNo = NFM103Response.response[0].LOG.SAPRepairNo;

            }
            // 原代码：
            // NFM103修改Rest start
            //status =
            //    NFMUtil.sendToSapRet(rowDataStr, NFMUtil.NFM103_ENDPOINT);
            // NFM103修改Rest end

            //  WLIG-BXQBH6 end

            // 原則非同期ですので、logsを確認する必要がないでしょう。
            if (status == 'OK') {
                rowData.retry_cnt__c = 0;
                //add           wangweipeng                       2022/02/18               start
                //如果为true，证明是重新发送的接口，需要把日志记录下
                if(needUpdateIflog){
                    logstr += 'Status:' + status;
                    logstr += '\nResponse:' + responseBody;
                    logstr += '\nend';
                }
                //add           wangweipeng                       2022/02/18               start
            } else {
                if (rowData.retry_cnt__c == null) rowData.retry_cnt__c = 0;
                if (rowData.retry_cnt__c < batch_retry_max_cnt) {
                    rowData.retry_cnt__c++;
                    LogAutoSendSchedule.assignOneMinute();
                }
                if (rowData.retry_cnt__c >= batch_retry_max_cnt) {
                    rowData.ErrorLog__c = 'status:' + status +
                                          '\n错误次数已经超过自动送信设定的最大次数，请手动送信';
                }
            }
        } catch (Exception ex) {
            // TODO IOException
            // エラーが発生した場合
            System.debug(Logginglevel.ERROR, 'NFM103_' + iflog.Name + ':' + ex.getMessage());
            System.debug(Logginglevel.ERROR, 'NFM103_' + iflog.Name + ':' + ex.getStackTraceString());
            logstr += ex.getMessage();
            iflog.ErrorLog__c += ex.getMessage() + '\n';
            iflog.ErrorLog__c += ex.getStackTraceString() + '\n';

            //---Gaozw---add
            if (rowData.retry_cnt__c == null) rowData.retry_cnt__c = 0;
            if (rowData.retry_cnt__c < batch_retry_max_cnt) {
                rowData.retry_cnt__c ++;
                LogAutoSendSchedule.assignOneMinute();
            }
            if (rowData.retry_cnt__c >= batch_retry_max_cnt) {
                rowData.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + rowData.ErrorLog__c + '错误次数已经超过自动送信设定的最大次数，请手动送信';
            }
        }
        iflog.Log__c = logstr;
        if (needUpdateIflog) {
            upsert iflog;
            update rowData;
        }
    }
}