/**
 * NFM007.triggerから呼び出す
 */
public without sharing class NFM007Controller {
    //CHAN-BSV3GZ SAP返回状态值 start
    public static String status;
    // CHAN-BSV3GZ end
    //CHAN-BDPBVY 20190703 start
    public class Detail_element {
        public String DetailLine;
        public String ItemCode;
        public Double ItemQuantity;
                                                                                                     
        public Decimal ListPrice;
        public Decimal Discount;
        public Decimal SalesPrice;

        // LHJ 多年保修 20190627 Start
        public String GuaranteePeriod;  // 保修年限
        public Decimal GuaranteePrice;   // 计提金额
        public Decimal ServicePrice;     // ServicePrice
        public Decimal MaintenancePrice;  // 维修合同报价
        public String GuaranteeType;     // 保修类别
        public String ProvistonPeriod;  // 计提年限
        // LHJ 多年保修 20190627 End
        //报价试算  合同申请时 所有明细行 全部替换 掉 start
        public String PROCODE;          //促销方案代码
        //报价试算 合同申请时 所有明细行 全部替换 掉 end
    }

    public class PresalesPerson_element {
        public String PresalesLine;
        public String PresalesPersonCode;
        public String PresalesPersonName;
    }
    public class Quotations_element {
        public NFMUtil.Monitoring Monitoring;
        public Quotation_element[] Quotation;
    }
    public class NFM007 {
        public Quotations_element Quotations;
    }
    public class Quotation_element {
        public String QuotationCode;
        public String SalesPoint;
        public String SalesPersonCode;
        public String SalesPersonName;
        public String Currency_x;
        public String EnduserCode;
        public String DepartmentCode;
        public String SalesChannel;
        public String CLBICCategory;
        public Decimal SalesPriceForAgent1;
        public Decimal SalesPriceForEnduser;
        public String Agent1Code;
        public String Agent2Code;
        public Decimal SalesPriceForAgent2;
        public String ProspectCategory;
        public String ContractType;
        public String FundSource;
        public String AuthorizationNo;
        public String ContractApplicationNo;
        public String DealerContractNo;
        public String InspectionCertificate;
        public String InspectionCertificateComment;
        public String PurposeOfAdvice;
        public Detail_element[] Detail;
        public PresalesPerson_element[] PresalesPerson;
        // LHJ 多年保修 20190627 Start
        public String ContractPeriod;  // 合同保修期（年）
        // LHJ 多年保修 20190627 End
        public String Other1 ;

    }
    //CHAN-BDPBVY 20190703 end
    public static boolean isRunning = false;
    public static String debug_msg = '';

    /**
     * NFM007の送信処理
     *
     * @param iflog_Id           ログテーブルのId
     * @param oppIds             送信対象商談(論理上1件のみです)
     * @param purposeOfAdviceMap 1:Delete 2:Add(Insert) 3:Change(Update)
     */
    @future (callout=true)
    public static void callout(String iflog_Id, List<String> oppIds, Map<String, String> purposeOfAdviceMap) {
        if (oppIds == null || oppIds.size() == 0) {
            return;
        }

        //CHAN-BDPBVY 20190703 start
        // Nfm007Sync.HTTPS_Port stub = new Nfm007Sync.HTTPS_Port();
        // stub.timeout_x = 100000; // timeout in milliseconds
        // stub.endpoint_x = NFMUtil.NFM007_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;
        // }
        //CHAN-BDPBVY 20190703 end


        // 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=' + oppIds.size() + '\n';

        // Monitoringの設定
        Datetime nowDT = Datetime.now();
        String nowStr = nowDT.format('yyyyMMddHHmm');


        //CHAN-BDPBVY 20190703 start
        // Nfm007Sync.Quotations_element quotations = new Nfm007Sync.Quotations_element();
        Quotations_element quotations = new Quotations_element();
        //CHAN-BDPBVY 20190703 end
        quotations.Monitoring = new NFMUtil.Monitoring();
        quotations.Monitoring.Tag                  = 'MSGH';
        quotations.Monitoring.Sender               = '8402';
        quotations.Monitoring.Receiver             = '1330';
        quotations.Monitoring.MessageType          = 'NFM007';
        quotations.Monitoring.MessageGroupNumber   = iflog.Name;
        quotations.Monitoring.NumberOfRecord       = '' + oppIds.size();
        quotations.Monitoring.TransmissionDateTime = nowStr;
        quotations.Monitoring.Text = '';

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

        try {
            // 転送データを取得、参照先のデータがあるので、ここで検索必要です。
            List<Opportunity> oppList = [select Id, Name, CurrencyIsoCode,
                                                Owner.Name, Owner.Employee_No__c,
                                                Opportunity_No__c, SalesPoint_Code__c,
                                                Hospital__c, Hospital__r.Management_Code__c,
                                                Account.Id, Account.Management_Code__c, Account.AgencyContract_Management_Code__c, Account.RecordType.DeveloperName,
                                                Account.Name, Account.ParentId, Account.Parent.Management_Code__c,
                                                Sales_Root__c, Opportunity_Category__c, OCM_Agent1_Price__c,
                                                Agency1__c, Agency1__r.Management_Code__c,
                                                Agency2__c, Agency2__r.Management_Code__c,
                                                Purchase_Type__c, Promise_Class__c, Fund_Basis__c,
                                                Authorized_DB_No__c, NotesApprovedNo__c, Sales_Contract_No__c,
                                                // Inspection_Certificate__c, Inspection_Certificate_Comment__c
                                                //LHJ CBPR Start
                                                Salesdepartment_Owner__c, Estimation_Id__c,
                                                // LHJ CBPR End
                                                // CHAN-B8U4TG 20190128 Start
                                                Trade__c,
                                                // CHAN-B8U4TG 20190128 End
                                                // LHJ 多年保修 20190627 Start
                                                Gurantee_Period__c,DecideQuoteDate__c,
                                                // LHJ 多年保修 20190627 End
                                                STMS_Package_Sale__c, Equipment_Order_Flg__c,
                                                //【是否需要价格申请】为是的场合,才要检查做没做过报价试算 thh 2021-11-03 start
                                                If_Need_PriceApply__c 
                                                //【是否需要价格申请】为是的场合,才要检查做没做过报价试算 thh 2021-11-03 end
                                           from Opportunity where Id IN :oppIds];
            System.debug(Logginglevel.DEBUG, 'NFM007_ oppList.size()=' + oppList.size());

            // Quotationのデータの設定
            //CHAN-BDPBVY 20190703 start
            // quotations.Quotation = new List<Nfm007Sync.Quotation_element>();
            quotations.Quotation = new List<Quotation_element>();
            //CHAN-BDPBVY 20190703 end
            for (Opportunity opp : oppList) {
                // 20211101 gzw 报价试算  fix  获取试算行项目 start
                List<PromotionSalesProducts__c> promotionSalesProductsList= [select id,
                        AgencyUnitPrice__c,
                        Quantity__c,
                        Product2__c,
                        PromotionNo__c,
                        latestProvistonPeriod__c,
                        latestGuranteePrice__c,
                        lastestGuaranteePeriod__c,
                        Product2__r.ProductCode,
                        // 20211101 gzw 报价试算  fix 查询产品新code相关 start
                        Product2__r.Correspond_Code__c,
                        Product2__r.Correspond_ProductCode__c,
                        Product2__r.Correspond_Code__r.Intra_Trade_List_RMB__c,
                        Product2__r.Correspond_Code__r.Foreign_Trade_List_US__c,
                        // 20211101 gzw 报价试算  fix 查询产品新code end
                        latestServicePrice__c,latestWarrantyType__c,
                        LastestMaintenance_Price_Year__c,
                        Product2__r.Intra_Trade_List_RMB__c,
                        Product2__r.Foreign_Trade_List_US__c,
                        recordTypeName__c
                    from PromotionSalesProducts__c 
                    where QuantityId__c =:opp.Estimation_Id__c ];
                // 20211101 gzw 报价试算  fix  获取试算行项目 end
                // 商談商品情報を取得
                List<OpportunityLineItem> oppLiList =
                                        [select Id,
                                                Quantity,
                                                PricebookEntry.ProductCode,
                                                // CHAN-BX66KN add by gzw start
                                                PricebookEntry.Product2.Estimation_Entry_Possibility__c,
                                                PricebookEntry.Product2.Correspond_ProductCode__c,
                                                PricebookEntry.Product2.Correspond_Code__c,
                                                // CHAN-BX66KN add by gzw end
                                                OpportunityId,
                                                Item_Order__c,
                                                ListPrice__c,UnitPrice__c,
                                                // CHAN-B8U4TG 20190128 Start
                                                PricebookEntry.Product2.Intra_Trade_List_RMB__c, // 内贸List价
                                                PricebookEntry.Product2.Foreign_Trade_List_US__c, // 外贸List价
                                                PricebookEntry.Product2.Correspond_Code__r.Foreign_Trade_List_US__c,
                                                PricebookEntry.Product2.Correspond_Code__r.Intra_Trade_List_RMB__c
                                                // CHAN-B8U4TG 20190128 End
                                                , AgencyUnitPrice__c //经销商单价
                                                //
                                                // LHJ 多年保修 20190627 Start
                                                , LatestGuranteePrice__c,
                                                LatestServicePrice__c,
                                                LastestGuaranteePeriod__c,
                                                latestWarrantyType__c,
                                                LastestMaintenance_Price_Year__c,
                                                latestProvistonPeriod__c
                                                // LHJ 多年保修 20190627 End
                                           from OpportunityLineItem
                                          where Opportunity.Id = :opp.Id
                                       order by Item_Order__c];

                // チームメンバー
                List<OpportunityTeamMember> oppTMList =
                                        [select Id, User.Employee_No__c, User.Name, OpportunityId
                                           from OpportunityTeamMember where OpportunityId = :opp.Id and TeamMemberRole = '副担当' order by CreatedDate desc];
                system.debug('oppLiList111111' + oppLiList);
                // LHJ 多年保修 Start
                Boolean oldDate = false;
                if (opp.DecideQuoteDate__c == null || opp.DecideQuoteDate__c < Date.valueOf(Label.GuaranteeWin)) {
                  oldDate = true;
                } else {
                  oldDate = false;
                }
                // LHJ 多年保修 End
                //外贸多年保修 精琢技术 wql 2021/03/23 start
                //上线前decide的询价标识
                Boolean oldDecideDateUSD = false;
                //已经decide 并且在上线前decide
                if(opp.DecideQuoteDate__c == null ||(opp.DecideQuoteDate__c!= null &&opp.DecideQuoteDate__c < Date.valueOf(Label.GuaranteeUSD)&&opp.Trade__c == '外貿')){
                    oldDecideDateUSD = true;
                }else{
                    oldDecideDateUSD = false;
                }
                //外贸多年保修 精琢技术 wql 2021/03/23 end
                //CHAN-BDPBVY 20190703 start
                // Nfm007Sync.Quotation_element quotation = new Nfm007Sync.Quotation_element();
                Quotation_element quotation = new Quotation_element();
                //CHAN-BDPBVY 20190703 end
                quotations.Quotation.add(quotation);
                quotation.QuotationCode                = opp.Opportunity_No__c;
                quotation.SalesPoint                   = opp.SalesPoint_Code__c;
                quotation.SalesPersonCode              = opp.Owner.Employee_No__c;
                quotation.SalesPersonName              = opp.Owner.Name;
                quotation.Currency_x                   = opp.CurrencyIsoCode;

                System.debug(Logginglevel.ERROR, 'NFM007_Account RecordType:' + opp.Account.RecordType.DeveloperName);
                if (opp.Account.RecordType.DeveloperName == 'AgencyContract') {
                    // 合同编码
                    quotation.EnduserCode                  = opp.Account.AgencyContract_Management_Code__c;
                    quotation.DepartmentCode               = opp.Account.AgencyContract_Management_Code__c;
//                    quotation.EnduserCode                  = opp.Account.Parent.Management_Code__c;
//                    quotation.DepartmentCode               = opp.Account.Parent.Management_Code__c;
                    System.debug(Logginglevel.ERROR, 'NFM007_AgencyContract EnduserCode:' + quotation.EnduserCode);
                    System.debug(Logginglevel.ERROR, 'NFM007_AgencyContract DepartmentCode:' + quotation.DepartmentCode);
                } else {
                    quotation.EnduserCode                  = opp.Hospital__r.Management_Code__c;
                    quotation.DepartmentCode               = opp.Account.Management_Code__c;
                    System.debug(Logginglevel.ERROR, 'NFM007_Hospital EnduserCode:' + quotation.EnduserCode);
                    System.debug(Logginglevel.ERROR, 'NFM007_Hospital DepartmentCode:' + quotation.DepartmentCode);
                }
                quotation.SalesChannel                 = NFMUtil.getMapValue(transferMap, 'Sales_Root__c', opp.Sales_Root__c, iflog);
                quotation.CLBICCategory                = NFMUtil.getMapValue(transferMap, 'Opportunity_Category__c', opp.Opportunity_Category__c, iflog);
                quotation.SalesPriceForAgent1          = opp.OCM_Agent1_Price__c;
                quotation.SalesPriceForAgent2          = 0;
                quotation.SalesPriceForEnduser         = 0;
                quotation.Agent1Code                   = opp.Agency1__r.Management_Code__c;
                quotation.Agent2Code                   = opp.Agency2__r.Management_Code__c;
                quotation.ProspectCategory             = NFMUtil.getMapValue(transferMap, 'Purchase_Type__c', opp.Purchase_Type__c, iflog);
                quotation.ContractType                 = NFMUtil.getMapValue(transferMap, 'Promise_Class__c', opp.Promise_Class__c, iflog);
                quotation.FundSource                   = NFMUtil.getMapValue(transferMap, 'Fund_Basis__c', opp.Fund_Basis__c, iflog);
                quotation.AuthorizationNo              = opp.Authorized_DB_No__c;
                quotation.ContractApplicationNo        = opp.NotesApprovedNo__c;
                quotation.DealerContractNo             = opp.Sales_Contract_No__c;
                // quotation.InspectionCertificate        = opp.Inspection_Certificate__c ? '1' : '0';
                // quotation.InspectionCertificateComment = opp.Inspection_Certificate_Comment__c;
                quotation.InspectionCertificate        = opp.STMS_Package_Sale__c ? '1' : '0';
                quotation.InspectionCertificateComment = opp.Equipment_Order_Flg__c ? '1' : '0';
                quotation.PurposeOfAdvice              = purposeOfAdviceMap.get(opp.Id);
                // LHJ 多年保修 20190627 Start
                //if (!oldDate) {
                    if (opp.Gurantee_Period__c != null) {
                        quotation.ContractPeriod               = String.valueOf(opp.Gurantee_Period__c).leftPad(2,'0');
                    } else {
                        quotation.ContractPeriod               = null;
                    }   
                //} else {
                //   quotation.ContractPeriod               = null;
                //}
                // LHJ 多年保修 20190627 End
                // xinhonglu AddStart
                quotation.Other1 = NFMUtil.getMapValue(transferMap, 'Salesdepartment_Owner__c', opp.Salesdepartment_Owner__c, iflog);

                // xinhonglu AddEnd
                 //CHAN-BDPBVY 20190703 start
                // quotation.Detail = new List<Nfm007Sync.Detail_element>();
                quotation.Detail = new List<Detail_element>();
                //CHAN-BDPBVY 20190703 end
                // 20211101 gzw 报价试算  fix  试算行项目有值，发试算信息，否则发询价行项目 end
                //询价上的【是否需要价格申请】为是的场合,才要检查做没做过报价试算 thh 2021-11-03 
                if (opp.If_Need_PriceApply__c && promotionSalesProductsList != null && promotionSalesProductsList.size() > 0) {
                    for(Integer i = 0; i < promotionSalesProductsList.size(); i++){
                        Detail_element detail = new Detail_element();
                        quotation.Detail.add(detail);
                        detail.DetailLine                  = '' + (i + 1);
                        // 20211101 gzw 报价试算  fix  ItemCode start
                        // detail.ItemCode                    = promotionSalesProductsList.get(i).Product2__r.ProductCode;
                        detail.ItemCode                    =
                        promotionSalesProductsList.get(i).Product2__r.Correspond_Code__c == null? promotionSalesProductsList.get(i).Product2__r.ProductCode :
                        promotionSalesProductsList.get(i).Product2__r.Correspond_ProductCode__c;
                        detail.ItemQuantity                = promotionSalesProductsList.get(i).Quantity__c;
                        if (opp.Trade__c == '外貿') {
                            // detail.ListPrice = promotionSalesProductsList.get(i).Product2__r.Foreign_Trade_List_US__c; // 外贸List价
                            detail.ListPrice =
                            promotionSalesProductsList.get(i).Product2__r.Correspond_Code__c == null? promotionSalesProductsList.get(i).Product2__r.Foreign_Trade_List_US__c :
                            promotionSalesProductsList.get(i).Product2__r.Correspond_Code__r.Foreign_Trade_List_US__c;
                        } else {
                            // detail.ListPrice = promotionSalesProductsList.get(i).Product2__r.Intra_Trade_List_RMB__c; // 内贸List价
                            detail.ListPrice =
                            promotionSalesProductsList.get(i).Product2__r.Correspond_Code__c == null? promotionSalesProductsList.get(i).Product2__r.Intra_Trade_List_RMB__c :
                            promotionSalesProductsList.get(i).Product2__r.Correspond_Code__r.Intra_Trade_List_RMB__c;
                        }
                        // 20211101 gzw 报价试算  fix  ItemCode end
                        // if (opp.Estimation_Id__c.startsWith('a2K')) {
                        //     detail.SalesPrice  = promotionSalesProductsList.get(i).UnitPrice__c; // 消耗品订单，销售价格
                        // } else {
                        //     detail.SalesPrice  = promotionSalesProductsList.get(i).AgencyUnitPrice__c;  // 一般询价，经销商销售价格
                        // }
                        detail.SalesPrice  = promotionSalesProductsList.get(i).AgencyUnitPrice__c;  // 一般询价，经销商销售价格
                        if (promotionSalesProductsList.get(i).LastestGuaranteePeriod__c != null) {
                            detail.GuaranteePeriod = String.valueOf(promotionSalesProductsList.get(i).LastestGuaranteePeriod__c).leftPad(2,'0');
                        } else {
                            detail.GuaranteePeriod = null;
                        }
                        // detail.PROCODE = promotionSalesProductsList.get(i).PromotionNo__c;
                        if(promotionSalesProductsList.get(i).recordTypeName__c=='Promotion'){
                            detail.PROCODE = promotionSalesProductsList.get(i).PromotionNo__c;
                        }else if(promotionSalesProductsList.get(i).recordTypeName__c=='Authorizer'){
                            detail.PROCODE = '9999';
                        }else{
                            detail.PROCODE = '8888';
                        }
                        system.debug(' detail.PROCODE=='+detail.PROCODE);
                        //WLIG-CCT9UG 【委托】关于市场多年保计提金调整 fy start
                        if(opp.Trade__c == '外貿'){
                            detail.GuaranteeType = promotionSalesProductsList.get(i).latestWarrantyType__c+',';// 保修类别
                        }else{
                            Date nowDate = Date.today();
                            // Date baojidate = Date.valueOf('2022-4-1');
                            Date baojidate = Date.newInstance(2022,3,30);
                            if(baojidate<=nowDate){
                                detail.GuaranteeType = promotionSalesProductsList.get(i).latestWarrantyType__c+',new';
                            }else{
                                detail.GuaranteeType = promotionSalesProductsList.get(i).latestWarrantyType__c+',';
                            }
                        }
                        //WLIG-CCT9UG 【委托】关于市场多年保计提金调整 fy end
                        // detail.GuaranteeType = promotionSalesProductsList.get(i).latestWarrantyType__c;  // 保修类别
                        if (!oldDate) {
                            if (promotionSalesProductsList.get(i).latestProvistonPeriod__c != null) {
                                detail.ProvistonPeriod = String.valueOf(promotionSalesProductsList.get(i).latestProvistonPeriod__c).leftPad(2,'0');
                            } else {
                                detail.ProvistonPeriod = null;
                            }
                            if (promotionSalesProductsList.get(i).LastestGuaranteePeriod__c != null) {
                                detail.GuaranteePeriod = String.valueOf(promotionSalesProductsList.get(i).LastestGuaranteePeriod__c).leftPad(2,'0');
                            } else {
                                detail.GuaranteePeriod = null;
                            }
                            detail.GuaranteePrice = promotionSalesProductsList.get(i).latestGuranteePrice__c;
                            detail.ServicePrice = promotionSalesProductsList.get(i).latestServicePrice__c;
                            // detail.GuaranteeType = oppLiList.get(i).latestWarrantyType__c;  // 保修类别
                            detail.MaintenancePrice = promotionSalesProductsList.get(i).LastestMaintenance_Price_Year__c; // 维修合同报价
                            detail.Discount   = (detail.ListPrice == null ? 0 : detail.ListPrice) 
                                                - (detail.SalesPrice == null ? 0 : detail.SalesPrice) 
                                                + (detail.ServicePrice == null ? 0 : detail.ServicePrice);   //折扣金额
    
                        }
                        else {
                            // detail.GuaranteePeriod = null;
                            // detail.GuaranteeType = null;
                            detail.ProvistonPeriod = null;
                            detail.GuaranteePrice = null;
                            detail.ServicePrice = null;
                            detail.MaintenancePrice = null;
                            detail.Discount   = (detail.ListPrice == null ? 0 : detail.ListPrice) 
                                                - (detail.SalesPrice == null ? 0 : detail.SalesPrice) 
                                                + (detail.ServicePrice == null ? 0 : detail.ServicePrice);   //折扣金额
                        }
                    }
                }else{
                    for (Integer i = 0; i < oppLiList.size(); i++) {
                        //CHAN-BDPBVY 20190703 start
                        // Nfm007Sync.Detail_element detail = new Nfm007Sync.Detail_element();
                        Detail_element detail = new Detail_element();
                        //CHAN-BDPBVY 20190703 end
                        quotation.Detail.add(detail);
                        detail.DetailLine                  = '' + (i + 1);
                        // CHAN-BX66KN add by gzw start
                        // detail.ItemCode                    = oppLiList.get(i).PricebookEntry.ProductCode;
                        detail.ItemCode                    =
                        oppLiList.get(i).PricebookEntry.Product2.Correspond_Code__c == null ? oppLiList.get(i).PricebookEntry.ProductCode : 
                        oppLiList.get(i).PricebookEntry.Product2.Correspond_ProductCode__c;
                        detail.ItemQuantity                = oppLiList.get(i).Quantity;
                        // CHAN-BX66KN add by gzw end
                        // CHAN-B8U4TG 20190128 Start
                        // detail.ListPrice  = oppLiList.get(i).ListPrice__c;          //产品折扣前清单价格
                        // CHAN-BX66KN update by gwy start
                        if (opp.Trade__c == '外貿') {
                            detail.ListPrice               = 
                            oppLiList.get(i).PricebookEntry.Product2.Correspond_Code__c == null ? oppLiList.get(i).PricebookEntry.Product2.Foreign_Trade_List_US__c:
                            oppLiList.get(i).PricebookEntry.Product2.Correspond_Code__r.Foreign_Trade_List_US__c; // 外贸List价
                        }else{
                            detail.ListPrice               = 
                            oppLiList.get(i).PricebookEntry.Product2.Correspond_Code__c == null ? oppLiList.get(i).PricebookEntry.Product2.Intra_Trade_List_RMB__c:
                            oppLiList.get(i).PricebookEntry.Product2.Correspond_Code__r.Intra_Trade_List_RMB__c; // 内贸List价
                        }
                        // CHAN-BX66KN update by gwy end
                        // CHAN-B8U4TG 20190128 End
                        //detail.SalesPrice  = oppLiList.get(i).UnitPrice__c;         //产品折扣后销售价格
                        //detail.SalesPrice  = oppLiList.get(i).AgencyUnitPrice__c;         //产品折扣后销售价格
                        if (opp.Estimation_Id__c.startsWith('a2K')) {
                            detail.SalesPrice  = oppLiList.get(i).UnitPrice__c; // 消耗品订单，销售价格
                        } else {
                            detail.SalesPrice  = oppLiList.get(i).AgencyUnitPrice__c;  // 一般询价，经销商销售价格
                        }

                        // LHJ 多年保修 20190627 Start
                        //detail.Discount   = (detail.ListPrice == null ? 0 : detail.ListPrice) 
                                            // - (detail.SalesPrice == null ? 0 : detail.SalesPrice) ;   //折扣金额
                        // if (oppLiList.get(i).LastestGuaranteePeriod__c != null) {
                        //     detail.GuaranteePeriod = String.valueOf(oppLiList.get(i).LastestGuaranteePeriod__c).leftPad(2,'0');
                        // } else {
                        //     detail.GuaranteePeriod = null;
                        // }
                        
                        //外贸多年保修 精琢技术 wql 2021/03/23 start

                        //计提年限 外贸多年保修 字段中4.1切换
                        if (oppLiList.get(i).latestProvistonPeriod__c != null) {
                            detail.ProvistonPeriod = String.valueOf(oppLiList.get(i).latestProvistonPeriod__c).leftPad(2,'0');
                        } else {
                            detail.ProvistonPeriod = null;
                        }
                        //保修年限 外贸多年保修 字段中4.1切换
                        if (oppLiList.get(i).LastestGuaranteePeriod__c != null) {
                            detail.GuaranteePeriod = String.valueOf(oppLiList.get(i).LastestGuaranteePeriod__c).leftPad(2,'0');
                        } else {
                            detail.GuaranteePeriod = null;
                        }
                        // 20211101 gzw 报价试算  fix  PROCODE start
                        detail.PROCODE = null;
                        // 20211101 gzw 报价试算  fix  PROCODE end
                        //oldDate 内贸多年保修切换 oldDecideDateUSD 外贸多年保修切换
                        //①decide在20191001之后 decide在20210401之后
                        if (!oldDate&&!oldDecideDateUSD) {
                            
                            //保修类别
                            if(oppLiList.get(i).latestWarrantyType__c != null){
                                //WLIG-CCT9UG 【委托】关于市场多年保计提金调整 fy start
                                if(opp.Trade__c == '外貿'){
                                    detail.GuaranteeType = oppLiList.get(i).latestWarrantyType__c+',';// 保修类别
                                }else{
                                    Date nowDate = Date.today();
                                    // Date baojidate = Date.valueOf('2022-4-1');
                                    Date baojidate = Date.newInstance(2022,3,30);
                                    if(baojidate<=nowDate){
                                        detail.GuaranteeType = oppLiList.get(i).latestWarrantyType__c+',new';
                                    }else{
                                        detail.GuaranteeType = oppLiList.get(i).latestWarrantyType__c+',';
                                    }
                                }
                                //WLIG-CCT9UG 【委托】关于市场多年保计提金调整 fy end
                                // detail.GuaranteeType = oppLiList.get(i).latestWarrantyType__c;  // 保修类别
                            }else{
                                //WLIG-CCT9UG 【委托】关于市场多年保计提金调整 fy start
                                if(opp.Trade__c == '外貿'){
                                    detail.GuaranteeType = ',';
                                }else{
                                    Date nowDate = Date.today();
                                    Date baojidate = Date.newInstance(2022,3,30);
                                    if(baojidate<=nowDate){
                                        detail.GuaranteeType = ',new';
                                    }else{
                                        detail.GuaranteeType = ',';
                                    }
                                }
                                //WLIG-CCT9UG 【委托】关于市场多年保计提金调整 fy end
                                // detail.GuaranteeType = null;
                            }
                            //计提金额
                            detail.GuaranteePrice = oppLiList.get(i).latestGuranteePrice__c;
                            //nodiscount
                            detail.ServicePrice = oppLiList.get(i).latestServicePrice__c;
                            // detail.GuaranteeType = oppLiList.get(i).latestWarrantyType__c;  // 保修类别
                            //维修合同报价
                            detail.MaintenancePrice = oppLiList.get(i).LastestMaintenance_Price_Year__c; // 维修合同报价
                            detail.Discount   = (detail.ListPrice == null ? 0 : detail.ListPrice) 
                                                - (detail.SalesPrice == null ? 0 : detail.SalesPrice) 
                                                + (detail.ServicePrice == null ? 0 : detail.ServicePrice);   //折扣金额
                        }
                        //①decide在20191001之后 外贸decide在20210401之前
                        else if(!oldDate&&oldDecideDateUSD){
                            // detail.GuaranteePeriod = null;
                            // detail.GuaranteeType = null;
                            //外贸多年保修未上线前 保修类别 传null
                            //WLIG-CCT9UG 【委托】关于市场多年保计提金调整 fy start
                            if(opp.Trade__c == '外貿'){
                                detail.GuaranteeType = ',';
                            }else{
                                Date nowDate = Date.today();
                                Date baojidate = Date.newInstance(2022,3,30);
                                if(baojidate<=nowDate){
                                    detail.GuaranteeType = ',new';
                                }else{
                                    detail.GuaranteeType = ',';
                                }
                            }
                            //WLIG-CCT9UG 【委托】关于市场多年保计提金调整 fy end
                            // detail.GuaranteeType = null;
                            //外贸多年保修未上线前  计提金额 传0 
                            detail.GuaranteePrice = 0;
                            //外贸多年保修未上线前 nodiscount 传0
                            detail.ServicePrice = 0;
                            //外贸多年保修未上线前 维修合同报价 传0 
                            detail.MaintenancePrice = 0;
                            detail.Discount   = (detail.ListPrice == null ? 0 : detail.ListPrice) 
                                                - (detail.SalesPrice == null ? 0 : detail.SalesPrice) 
                                                + (detail.ServicePrice == null ? 0 : detail.ServicePrice);   //折扣金额
                        } 
                        //③decide在20191001 之前  老数据
                        else if(oldDate){
                            detail.GuaranteePeriod = null;
                            //WLIG-CCT9UG 【委托】关于市场多年保计提金调整 fy start
                            if(opp.Trade__c == '外貿'){
                                detail.GuaranteeType = ',';
                            }else{
                                Date nowDate = Date.today();
                                Date baojidate = Date.newInstance(2022,3,30);
                                if(baojidate<=nowDate){
                                    detail.GuaranteeType = ',new';
                                }else{
                                    detail.GuaranteeType = ',';
                                }
                            }
                            //WLIG-CCT9UG 【委托】关于市场多年保计提金调整 fy end
                            // detail.GuaranteeType = null;
                            detail.ProvistonPeriod = null;
                            detail.GuaranteePrice = null;
                            detail.ServicePrice = null;
                            detail.MaintenancePrice = null;
                            detail.Discount   = (detail.ListPrice == null ? 0 : detail.ListPrice) 
                                                - (detail.SalesPrice == null ? 0 : detail.SalesPrice) 
                                                + (detail.ServicePrice == null ? 0 : detail.ServicePrice);   //折扣金额
                        }


                        // LHJ 多年保修 20190627 End
                        //外贸多年保修 精琢技术 wql 2021/03/23 start
                    }
                }
                
                //CHAN-BDPBVY 20190703 start
                // quotation.PresalesPerson = new List<Nfm007Sync.PresalesPerson_element>();
                quotation.PresalesPerson = new List<PresalesPerson_element>();
                //CHAN-BDPBVY 20190703 end
                for (Integer i = 0; i < oppTMList.size(); i++) {
                    //CHAN-BDPBVY 20190703 start
                    // Nfm007Sync.PresalesPerson_element person = new Nfm007Sync.PresalesPerson_element();
                    PresalesPerson_element person = new PresalesPerson_element();
                    //CHAN-BDPBVY 20190703 end
                    quotation.PresalesPerson.add(person);
                    person.PresalesLine                = '' + (i + 1);
                    person.PresalesPersonCode          = oppTMList.get(i).User.Employee_No__c;
                    person.PresalesPersonName          = oppTMList.get(i).User.Name;
                }
                logstr += quotation.QuotationCode + '(' + quotation.PurposeOfAdvice + ')Detail[' + oppLiList.size() + ']PresalesPerson[' + oppTMList.size() + '] ';
            }

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

                //请求号码：CHAN-BDPBVY 新增start
                NFM007 mfn007 = new NFM007();
                mfn007.Quotations = new Quotations_element();
                mfn007.Quotations = quotations;
                //请求号码：CHAN-BDPBVY 新增end
                //请求号码：CHAN-BDPBVY 修改前rowData = NFMUtil.makeRowData(Monitoring, 'NFM007', quotations);
                rowData = NFMUtil.makeRowData(Monitoring, 'NFM007', mfn007);
                System.debug('+++++rowData+++++' + rowData);
                execute(rowData, iflog);
            }
            Set<String> inquiryNoList = new Set<String>();

            Map<String, Opportunity> oppUpsertMap = new Map<String, Opportunity>();
            // CHAN-BSV3GZ start
            // 保存 status 状态
            logstr += '\nStatus:' + status;
            //CHAN-BSV3GZ end
            logstr += '\nend';
        } catch(Exception ex) {
            // エラーが発生した場合
            System.debug(Logginglevel.ERROR, 'NFM007_' + iflog.Name + ':' + ex.getMessage());
            System.debug(Logginglevel.ERROR, 'NFM007_' + iflog.Name + ':' + ex.getStackTraceString());
            logstr += ex.getMessage();
            iflog.ErrorLog__c += ex.getMessage() + '\n';
            iflog.ErrorLog__c += ex.getStackTraceString() + '\n';
        }
        if (rowData != null) {
            System.debug('+++++rowData+++++insert:' + rowData);
            insert rowData;
            System.debug('+++++rowData+++++afterinsert:' + rowData.Id);
        }

        System.debug(Logginglevel.DEBUG, 'NFM007_' + 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);
        //CHAN-BDPBVY 20190703 start
        // Nfm007Sync.Quotations_element quotations = (Nfm007Sync.Quotations_element) JSON.deserialize(rowDataStr, Nfm007Sync.Quotations_element.class);
        NFM007 nfm007 = (NFM007) JSON.deserialize(rowDataStr, NFM007.class);
        //CHAN-BDPBVY 20190703 end
        String logstr = nfm007.Quotations.Monitoring.MessageGroupNumber + ' start\n';
        Boolean needUpdateIflog = false;
        if  (iflog == null) {
            needUpdateIflog = true;
            iflog = new BatchIF_Log__c();
            iflog.Type__c = 'NFM007';
            iflog.MessageGroupNumber__c = nfm007.Quotations.Monitoring.MessageGroupNumber;
            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{
            //gaozw
            //CHAN-BDPBVY 20190703 start
            // Nfm007Sync.HTTPS_Port stub = new Nfm007Sync.HTTPS_Port();
            // stub.timeout_x = 100000; // timeout in milliseconds
            // stub.endpoint_x = NFMUtil.NFM007_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;
            // }
            // Nfm007Sync.Quotations_element[] pQuotations = new Nfm007Sync.Quotations_element[] { quotations };
            // OlympusCoJpCommonMessage.LOG_element[] logs = stub.NFM007_Sync_BC2GPI(pQuotations);
            //CHAN-BDPBVY 20190703 end

            //CHAN-BDPBVY 20190703 start
            // NFMUtil.sendToSap(rowDataStr, NFMUtil.NFM007_ENDPOINT);
            // CHAN-BSV3GZ start
            // 接收 SAP返回状态
            status =
            // CHAN-BSV3GZ end
            NFMUtil.sendToSapRet(rowDataStr, NFMUtil.NFM007_ENDPOINT);
            //CHAN-BDPBVY 20190703 end
            // CHAN-BSV3GZ start
            // 原代码
            // rowData.retry_cnt__c=0;
             if (status == 'OK') {
                rowData.retry_cnt__c = 0;
            } 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 + ' 询价编码：' + nfm007.Quotations.Quotation.get(0).QuotationCode + 
                                          '\n错误次数已经超过自动送信设定的最大次数，请手动送信';
                }
            }
            // CHAN-BSV3GZ end
            
        }catch(Exception ex) {
            // TODO IOException
            // エラーが発生した場合
            System.debug(Logginglevel.ERROR, 'NFM007_' + iflog.Name + ':' + ex.getMessage());
            System.debug(Logginglevel.ERROR, 'NFM007_' + iflog.Name + ':' + ex.getStackTraceString());
            logstr += ex.getMessage();
            iflog.ErrorLog__c += ex.getMessage() + '\n';
            iflog.ErrorLog__c += ex.getStackTraceString() + '\n';

            //---xiongyl---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;
        }
    }
}