global class NFM110dataBatch implements Database.Batchable<sObject> {
    public string  rowData_Id;
    public transient static List<Id> orderReturnIdList;

    global NFM110dataBatch() {
    }
    global NFM110dataBatch( string rowData_Id ) {
        this.rowData_Id = rowData_Id;
    }

    global Database.QueryLocator start(Database.BatchableContext bc) {
        if( string.isBlank( rowData_Id )){
            return Database.getQueryLocator([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, Type__c,
                 DA_retry_cnt__c, NFM501Future_Count__c, NFM501_Web_Annex_Count__c
                 FROM BatchIF_Log__c
                 WHERE RowDataFlg__c = true
                AND Type__c = 'NFM110'
                AND CreatedDate >= : Datetime.newInstance(2022, 4, 1)
                                                     order by MessageGroupNumber__c asc
                                             ]);
        }else{
            return Database.getQueryLocator([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,
                                             DA_retry_cnt__c ,DN_retry_cnt__c,CreatedDate 
                                             from BatchIF_Log__c
                                             where RowDataFlg__c = true
                                             and Id = :rowData_Id ]);
        }
    }

    global void execute(Database.BatchableContext BC, List<BatchIF_Log__c> rowDataList) {
        Oly_TriggerHandler.bypass('ConsumableAssetHander');
        BatchIF_Log__c rowData = rowDataList[0];
        StaticParameter.ConsumableAssetHanderTrigger = true;
        StaticParameter.EscapeConsumableOrderDetail2Trigger = true;
        Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
        String logstr = rowData.MessageGroupNumber__c + ' start\n';
        BatchIF_Log__c iflog = new BatchIF_Log__c();

        iflog.Type__c = 'NFM110';
        iflog.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
        iflog.Log__c = logstr;
        iflog.ErrorLog__c = '';
        insert iflog;
        String rowDataStr = NFMUtil.getRowDataStr(rowData);
        List<NFM110Rest.GeneralData> generalDataList =
            (List<NFM110Rest.GeneralData>) JSON.deserialize(rowDataStr, List<NFM110Rest.GeneralData>.class);
        if (generalDataList == null || generalDataList.size() == 0) {
            return;
        }


        orderReturnIdList = new List<Id>();
        //orderoutIdList = new List<Id>();
        Savepoint sp = Database.setSavepoint();
        try {
            // add by Gaozw  取当前执行日期，后面备用 start
            date strdate = date.today();
            String year = String.valueOf(strdate.year());
            String month = String.valueOf(strdate.month());
            String day = String.valueOf(strdate.day());
            String datestr = String.valueOf(year+month+day);
            // add by Gaozw  取当前执行日期，后面备用 end

            //update by rentx  20210823
            //本次修改只针对于保有设备 之前使用年月日去插入时 会出现 同一天多批日志里有同一个设备 导致更新失败  现解决方案为使用日志创建时间并精确到分
            //update by rentx  20210823
            //之前使用年月日去插入时 会出现 同一天多批日志里有同一个设备 导致更新失败  现解决方案为精确到分


            // 更新対応配列とMapなどをセット
            Set<String> managementCodeList = new Set<String>();
            Set<String> soNoList = new Set<String>();
            Set<String> inquiryNoList = new Set<String>();
            Set<String> productCodeList = new Set<String>();
            List<String> barCodeList = new List<String>();
            List<String> tracingCodeList = new List<String>();
            Set<String> productSerialNoList = new Set<String>();

            // SWAG-BDV589 start
            // OppNumberAndProductCode 和QIS 一一对应标识
            map<string, list<QIS_Report__c> > OppNumberAndProductCodetoQISMap
                = new Map<string, List<QIS_Report__c> >();
            // 返品标识为3的新品的OppNumberAndProductCode集合
            list<string> OppNumberAndProductCodeList = new List<string> ();
            // 直销耗材，出库单新建
            Map<String, Consumable_order__c> orderOutMap = new Map<String, Consumable_order__c>();

            // SWAG-BDV589 end

            for (nfm110rest.GeneralData infoH : generalDataList) {
                if (String.isBlank(infoH.DeliveryNote)) {
                    continue;
                }

                if (infoH.DnInformation == null || infoH.DnInformation.size() == 0) {
                    continue;
                }
                // 病院と診療科の管理コード、TODO 販売店
                infoH.EndUserNo = NFMUtil.trimLeft(infoH.EndUserNo, '0');
                infoH.DepartmentNo = NFMUtil.trimLeft(infoH.DepartmentNo, '0');
                if (infoH.EndUserNo == null || infoH.EndUserNo  == '') {
                    // 病院と診療科の管理コードがない場合、処理と飛ばす
                    continue;
                }
                if (infoH.DepartmentNo == null || infoH.DepartmentNo == '') {
                    infoH.DepartmentNo = infoH.EndUserNo;
                }
                managementCodeList.add(infoH.EndUserNo);
                managementCodeList.add(infoH.DepartmentNo);
                if (String.isBlank(infoH.SoNo) == false) {
                    soNoList.add(infoH.SoNo);
                }
                // SWAG-BDV589 start
                string tempInquiryNo = '';
                // SWAG-BDV589 end
                if (String.isBlank(infoH.InquiryNo) == false) {
                    String[] Inquiry;
                    if (infoH.InquiryNo.contains(',')) {
                        Inquiry = infoH.InquiryNo.split(',');
                        // SWAG-BDV589 start
                        tempInquiryNo = Inquiry[0];
                        // SWAG-BDV589 end
                        inquiryNoList.add(Inquiry[0]);
                    } else {
                        //根据数据传的样式决定
                    }
                }
                if (!(infoH.ReturnMark == null || infoH.ReturnMark  == ''
                      || infoH.ReturnMark == '1' || infoH.ReturnMark == '3'
                      )) {
                    // ReturnMark = 上記以外の場合 Errorメッセージ出力
                    continue;
                }
                for (nfm110rest.DnInformation dnInfo : infoH.DnInformation) {
                    // dnInfo.SerialNoorLotNo = checkSerialNoorLotNo(dnInfo.SerialNoorLotNo);
                    productCodeList.add(dnInfo.OTCode);
                    // CHAN-BBLAAP start
                    string Product_Serial_No = '';
                    if (dnInfo.SorLMark == 'S') {
                        Product_Serial_No =
                            dnInfo.OTCode + ':' + dnInfo.SerialNoorLotNo;
                    } else {
                        Product_Serial_No  =
                            dnInfo.OTCode + ':' + dnInfo.SerialNoorLotNo
                            + '(' + dnInfo.TracingCode + ')';

                    }
                    // CHAN-BBLAAP end
                    if (dnInfo.OTCode == null || dnInfo.OTCode == ''
                        || dnInfo.SerialNoorLotNo == null || dnInfo.SerialNoorLotNo == ''
                        ) {
                        // 商品コードがない場合、処理と飛ばす
                        continue;
                    }
                    // HHOA-AGN2EH start
                    //productSerialNoList.add(dnInfo.OTCode + ':' + dnInfo.SerialNoorLotNo);
                    productSerialNoList.add(dnInfo.SerialNoorLotNo);
                    productSerialNoList.add(dnInfo.SerialNoorLotNo + '(' + dnInfo.TracingCode + ')');
                    //if(dnInfo.TracingCode == null || dnInfo.TracingCode == ''){
                    //    continue;
                    //}else{
                    //    tracingCodeList.add(dnInfo.TracingCode);

                    //}
                    // HHOA-AGN2EH end
                    // SWAG-BDV589 start
                    if (infoH.ReturnMark == '3') {
                        OppNumberAndProductCodeList.add(tempInquiryNo + ':' + dnInfo.OTCode);
                    }
                    if (dnInfo.Barcode == null || dnInfo.Barcode == '') {
                        continue;
                    } else {
                        barCodeList.add(dnInfo.Barcode);
                    }
                    if (dnInfo.TracingCode == null || dnInfo.TracingCode == '') {
                        continue;
                    } else {
                        tracingCodeList.add(dnInfo.TracingCode);
                    }
                }
            }



            // 事前に（マスタ）データを取得
            // HHOA-BLC8S6 update by vivek 2020-02-13 start
            // List<Account> accList = [select Id, Name, Management_Code__c, Department_Class__c, Hospital__c, ParentId,
            //                          RecordType.DeveloperName, Department_Name__c
            //                          from Account
            //                          where Management_Code__c in :managementCodeList];
            List<Account> accList = [select Id, Name, Management_Code__c, Department_Class__c, Hospital__c, ParentId,
                                     RecordType.DeveloperName, Department_Name__c, OCM_man_province_txt__c
                                     from Account
                                     where Management_Code__c in :managementCodeList];
            // HHOA-BLC8S6 update by vivek 2020-02-13 end
            Map<String, Account> accsMap = new Map<String, Account>();
            for (Account acc : accList) {
                accsMap.put(acc.Management_Code__c, acc);
            }

            //接收订单类型判断是否不生成追溯系统相关内容  精琢技术 thh 2021-10-11 start
            List<Statu_Achievements__c> boList = [select Id, Name, orderType__c
                                                  from Statu_Achievements__c
                                                  where Name in :soNoList and OverviewStatus__c <> '无效合同'];
            Map<String, String> NameorderType = new Map<String, String>();
            for(Statu_Achievements__c bo1 : boList) {
                NameorderType.put(bo1.Name, bo1.orderType__c);
            }

            List<Product2> prdList = [select Id, Name, ProductCode, ProductCode_Ext__c, MDM_Model_No__c
                                      // 修改虚拟合同生成逻辑 gzw 20210324 start
                                      ,Virtual_Contract__c,GuranteeType__c
                                      // 修改虚拟合同生成逻辑 gzw 20210324 end
                                      from Product2
                                      where ProductCode_Ext__c in :productCodeList];
                                      //修改 OER-SMART 产品不生成虚拟维修合同
                                      // and Category5__c = 'OER-SMART'
            Map<String, Product2> prdsMap = new Map<String, Product2>();
            for (Product2 prd : prdList) {
                prdsMap.put(prd.ProductCode_Ext__c, prd);
            }
            if (productCodeList.size() != prdsMap.size()) {
                list<string> strList = new list<string>();
                for (string productcode : productCodeList) {
                    if (!prdsMap.containsKey(productcode)) {
                        strList.add(productcode);
                    }
                }

                throw new ControllerUtil.myException('发货数据中的OT CODE:' + String.join(strList, ' ')
                                                     + '不能找到对应的产品主数据！');
            }
            List<Product2__c> prdSearchList = [select Id, Name, Product2__r.ProductCode_Ext__c, Pro2_Dealer_ENG__c,
                                               Intra_Trade_List_RMB__c, Asset_Model_No__c, Pro2_Dealer_Object__c,Product2__r.ConsumCategory1F__c
                                               from Product2__c
                                               where Product2__r.ProductCode_Ext__c in :productCodeList];
            Map<String, Product2__c> prdSearchMap = new Map<String, Product2__c>();
            for (Product2__c prd2 : prdSearchList) {
                prdSearchMap.put(prd2.Product2__r.ProductCode_Ext__c, prd2);
            }
            // 已有的追溯产品
            List<Consumable_order_details2__c> orderDetails = [Select Id,
                                                               Consumable_order_minor__r.Name,
                                                               Bar_Code__c,
                                                               TracingCode__c,
                                                               Deliver_date__c,
                                                               Asset_Model_No__c,
                                                               Opportunity_No__c,
                                                               Dealer_Info_text__c,
                                                               Consumable_Sale_order__c,
                                                               Inventory_Status__c,
                                                               Consumable_order_minor__c,
                                                               Arrive_date__c,
                                                               Used_date__c
                                                               from Consumable_order_details2__c
                                                               where TracingCode__c IN :tracingCodeList];
            Map<String, Consumable_order_details2__c> orderDetailTCDeliveryMap = new Map<String, Consumable_order_details2__c>();
            for (Consumable_order_details2__c ordD : orderDetails) {
                if (String.isBlank(ordD.TracingCode__c) == false) {
                    orderDetailTCDeliveryMap.put(ordD.Dealer_Info_text__c + ':' + ordD.Bar_Code__c, ordD);
                }
            }
            List<Opportunity> oppList = [Select Id, Purchase_Type__c, Opportunity_No__c, Strategic_department_Class_Name__c,
                                         Sales_Root__c, SAP_Province__c, Trade__c, Agency1__c, Agency1__r.Name,Agency1_Name_F__c,
                                         Agency1__r.OCM_man_province_txt__c, Opportunity_Category__c
                                        //  ,SAP_Province__c //20230323 lt DB202303088261 两票制 add
                                        // DB202306197517 gzw start
                                        ,Sales_Shop_Class__c
                                        // DB202306197517 gzw end

                                         From Opportunity Where Opportunity_No__c IN :inquiryNoList];
            // update by gzw 2020-04-27 start
            Map<String, Opportunity> oppMap = new Map<String, Opportunity>();
            // 自动修改最终用户 update by vivek start
            Set<String> agency1Id = new Set<String>();
            // 自动修改最终用户 update by vivek end
            for (Opportunity opp : oppList) {
                oppMap.put(opp.Opportunity_No__c, opp);
                // 自动修改最终用户 update by vivek start
                if (opp.Strategic_department_Class_Name__c == 'ET') {
                    agency1Id.add(opp.Agency1__c);
                }
                // 自动修改最终用户 update by vivek end
            }
            Map<String, String> agencyContractETMap = new Map<String, String>();
            Date Contract_Decide_End_Date = Date.today();
            List<Account> agencyContractET = [select id, name, Is_Active__c, Contract_Decide_End_Date__c, Contact_Type__c, ParentId, Is_Active_Formula__c from Account where ParentId = :agency1Id and Contract_Decide_End_Date__c >= :Contract_Decide_End_Date and Contact_Type__c = 'ET'];
            for (Account acc : agencyContractET) {
                agencyContractETMap.put(acc.ParentId, acc.Id);
            }
            // 更新対応配列をセット
            Map<String, Consumable_order_details2__c> odDSUpsertMap = new Map<String, Consumable_order_details2__c>();
            // 直销耗材出库单明细2 （医院:科室）
            Map<String, List<Consumable_order_details2__c> > odDSUpsertIdxMap = new Map<String, List<Consumable_order_details2__c> >();
            for (NFM110Rest.GeneralData infoH : generalDataList) {
                // System.debug('562:::'+accsMap.get(infoH.EndUserNo).Id );
                // 订单明细2编号 auto NO
                Map<String, Integer> odUpsertIdxMap = new Map<String, Integer>();
                String InquiryNoStr = '';
                String InquiryNoStr2 = '';
                if (String.isBlank(infoH.InquiryNo) == false) {
                    if (infoH.InquiryNo.contains(',')) {
                        InquiryNoStr = infoH.InquiryNo.split(',')[0];
                        if (infoH.InquiryNo.split(',').size() > 1) {
                            InquiryNoStr2 = infoH.InquiryNo.split(',')[1];
                        }
                    }
                    if (String.isBlank(InquiryNoStr)) {
                        iflog.ErrorLog__c += 'Error! SoNo[' + infoH.SoNo + '] InquiryNo is required. This DN is skipped.\n';
                        continue;
                    }
                }
                if (String.isBlank(infoH.DeliveryNote)) {
                    iflog.ErrorLog__c += 'Error! SoNo[' + infoH.SoNo + '] DeliveryNote is required. This DN is skipped.\n';
                    continue;
                }
                if (infoH.DnInformation == null || infoH.DnInformation.size() == 0) {
                    iflog.ErrorLog__c += 'Error! SoNo[' + infoH.SoNo + '] DeliveryNote[' + infoH.DeliveryNote + '] DnInformation is required. This DN is skipped.\n';
                    continue;
                }
                if (infoH.EndUserNo == null || infoH.EndUserNo  == '') {
                    iflog.ErrorLog__c += 'Error! SoNo[' + infoH.SoNo + '] DeliveryNote[' + infoH.DeliveryNote + '] EndUserNo is required. This DN is skipped.\n';
                    continue;
                }
                if (accsMap.get(infoH.EndUserNo) == null) {
                    iflog.ErrorLog__c += 'Error! SoNo[' + infoH.SoNo + '] DeliveryNote[' + infoH.DeliveryNote + '] EndUserNo[' + infoH.EndUserNo + ']NotExist. This DN is skipped.\n';
                    continue;
                } else if (accsMap.get(infoH.EndUserNo).RecordType.DeveloperName != 'HP'
                           && accsMap.get(infoH.EndUserNo).RecordType.DeveloperName != 'Agency'
                           && accsMap.get(infoH.EndUserNo).RecordType.DeveloperName != 'AgencyContract') {
                    iflog.ErrorLog__c += 'Error! SoNo[' + infoH.SoNo + '] DeliveryNote[' + infoH.DeliveryNote + '] EndUserNo[' + infoH.EndUserNo + ']Is Not HP or Agency(Contract). This DN is skipped.\n';
                    continue;
                }
                if (accsMap.get(infoH.DepartmentNo) == null) {
                    iflog.ErrorLog__c += 'Error! SoNo[' + infoH.SoNo + '] DeliveryNote[' + infoH.DeliveryNote + '] DepartmentNo[' + infoH.DepartmentNo + ']NotExist. This DN is skipped.\n';
                    continue;
                }
                if (!(infoH.ReturnMark == null || infoH.ReturnMark  == ''
                      || infoH.ReturnMark == '1' || infoH.ReturnMark == '3'
                      )) {
                    iflog.ErrorLog__c += 'Error! SoNo[' + infoH.SoNo + '] DeliveryNote[' + infoH.DeliveryNote + '] ReturnMark[' + infoH.ReturnMark + '] Not Defined. This DN is skipped.\n';
                    continue;
                }
                // SWAG-BDV589 start
                string tempInquiryNo = '';
                if (String.isBlank(infoH.InquiryNo) == false) {
                    String[] Inquiry;
                    if (infoH.InquiryNo.contains(',')) {
                        Inquiry = infoH.InquiryNo.split(',');
                        tempInquiryNo = Inquiry[0];
                    } else {
                        //根据数据传的样式决定
                    }
                }
                // SWAG-BDV589 end
                // 直销耗材明细2
                List<Consumable_order_details2__c> cod2List = new List<Consumable_order_details2__c>();
                //DN中多年保修产品数量 计数
                Integer vmcCount = 0;
                integer tempDNdetailNumber = 0;
                System.debug('626:::'+infoH.DnInformation.size());
                for (NFM110Rest.DnInformation dnInfo : infoH.DnInformation) {
                    // dnInfo.SerialNoorLotNo = checkSerialNoorLotNo(dnInfo.SerialNoorLotNo);
                    if (dnInfo.OTCode == null || dnInfo.OTCode == '') {
                        iflog.ErrorLog__c += 'Error! SoNo[' + infoH.SoNo + '] DeliveryNote[' + infoH.DeliveryNote + '] SerialNoorLotNo[' + dnInfo.SerialNoorLotNo + '] OTCode is required. This asset is skipped.\n';
                        continue;
                    }
                    if (dnInfo.SerialNoorLotNo == null || dnInfo.SerialNoorLotNo == '') {
                        iflog.ErrorLog__c += 'Error! SoNo[' + infoH.SoNo + '] DeliveryNote[' + infoH.DeliveryNote + '] OTCode[' + dnInfo.OTCode + '] SerialNoorLotNo is required. This asset is skipped.\n';
                        continue;
                    }
                    Product2__c prdSearch = prdSearchMap.get(dnInfo.OTCode);
                    if (prdSearch == null) {
                        iflog.ErrorLog__c += 'Error! SoNo[' + infoH.SoNo + '] DeliveryNote[' + infoH.DeliveryNote + '] [' + InquiryNoStr + ']ProductSerch[' + dnInfo.OTCode + ']NotExist. This asset is skipped.\n';
                        continue;
                    }
                    // HHOA-AGN2EH end
                    if (oppMap.get(InquiryNoStr) != null
                             && oppMap.get(InquiryNoStr).Sales_Root__c == '販売店'
                             && accsMap.get(infoH.EndUserNo) != null
                             && accsMap.get(infoH.EndUserNo).RecordType.Developername == 'HP'
                             && String.isNotBlank( dnInfo.Barcode)) {
                        System.debug('销售渠道=经销商');
                        Product2__c prdMap = prdSearchMap.get(dnInfo.OTCode);
System.debug('step1');
                        if (!(prdMap.Pro2_Dealer_Object__c
                            || prdMap.Pro2_Dealer_ENG__c
                            || prdMap.Product2__r.ConsumCategory1F__c == 'ET耗材' 
                            || prdMap.Product2__r.ConsumCategory1F__c == 'ENG耗材')) {
                            continue;
                        }
                        logstr += '\n撒333333333 ' + prdMap.Asset_Model_No__c + '---' + prdMap.Pro2_Dealer_Object__c + '----' +prdMap.Pro2_Dealer_ENG__c + '----' + prdMap.Product2__r.ConsumCategory1F__c;
                        if (NameorderType.get(infoH.SoNo) == 'ZM16') {
                            continue;
                        }
System.debug('step2');
                        // DB202306197517 gzw end
System.debug('step3');  
                        Consumable_order_details2__c rac = orderDetailTCDeliveryMap.get(oppMap.get(InquiryNoStr).Agency1__r.Name + ':' + dnInfo.Barcode);
                        // logstr += '\撒222222222 '+ rac;
                        if (rac != null && String.isNotBlank(rac.Consumable_Sale_order__c)) {
                            // logstr += '\撒333333333 ';
                            continue;
                        }
                        if(rac != null && !(rac.Inventory_Status__c == '未到经销商' && String.isBlank(rac.Consumable_order_minor__c))){
                            // logstr += '\撒444444444 ';
                            continue;
                        }
                        // logstr += '\撒555555555 ';
                        if (rac == null) {
                            rac = new Consumable_order_details2__c();
                            if (oppMap.containsKey(InquiryNoStr)) {
                                rac.Agencyinfo_fromSAP__c     = oppMap.get(InquiryNoStr).Agency1__r.Name;
                                rac.Frist_Storage_Agency__c   = oppMap.get(InquiryNoStr).Agency1__r.Name;
                            }
                            // update by gzw 2020-04-27 end
                            cod2List.add(rac);
                            odDSUpsertMap.put(InquiryNoStr + ':' + dnInfo.Barcode, rac);
                            odUpsertIdxMap.put(InquiryNoStr + ':' + dnInfo.Barcode, odDSUpsertMap.size());

                            rac.Name                      = InquiryNoStr + ':' + ('000' + odUpsertIdxMap.get(InquiryNoStr + ':' + dnInfo.Barcode)).right(4);
                            rac.RecordTypeId              = System.Label.RT_ConOrderDetail2_Delivery;                // TODO 本番IDにする label
                            if (String.isNotBlank(dnInfo.VALUE)) {
                                rac.Intra_Trade_List_RMB__c = Decimal.valueOf(dnInfo.VALUE);
                            }else {
                                rac.Intra_Trade_List_RMB__c   = prdSearch.Intra_Trade_List_RMB__c;
                            }
                            rac.Delivery_List_RMB__c = Decimal.valueOf(dnInfo.VALUE);
                            rac.Asset_Model_No__c         = prdSearch.Asset_Model_No__c;
                            rac.Deliver_date__c           = NFMUtil.parseStr2Date(infoH.DeliveryDate);
                            // 自动修改最终用户 update by vivek start
                            // logstr += '\nUsed_date__c +++++++++++: ';
                            // if (!(oppMap.get(InquiryNoStr) != null && agencyContractETMap.get(oppMap.get(InquiryNoStr).Agency1__c) == null) ) {
                            // logstr += '\nUsed_date__c +++++++++++: ';
                                // 到货日期需要再确认 todo
                                // rac.Arrive_date__c           = NFMUtil.parseStr2Date(infoH.DeliveryDate);
                                rac.Used_date__c           = NFMUtil.parseStr2Date(infoH.DeliveryDate);
                            // }
                            // rac.Arrive_date__c           = NFMUtil.parseStr2Date(infoH.DeliveryDate);
                            // rac.Used_date__c           = NFMUtil.parseStr2Date(infoH.DeliveryDate);
                            // 自动修改最终用户 update by vivek end
                            // gzw DB202301244151 保修期限验证日期可行性调整 start
                            if (dnInfo.ValidTo !=null && dnInfo.ValidTo.length() == 8
                                        && Integer.valueOf(dnInfo.ValidTo.substring(0, 4)) <= Integer.valueOf(Date.today().Year())) {
                                rac.Sterilization_limit__c = null;
                            }else{
                                rac.Sterilization_limit__c    = NFMUtil.parseStr2Date(dnInfo.ValidTo);
                            }
                            // rac.Sterilization_limit__c    = NFMUtil.parseStr2Date(dnInfo.ValidTo);
                            // gzw DB202301244151 保修期限验证日期可行性调整 end
                            rac.Consumable_product__c     = prdSearch.Id;
                            rac.Bar_Code__c               = dnInfo.Barcode;
                            rac.Used_account__c           = oppMap.get(InquiryNoStr).Agency1__c;
                            // update by vivek start 2020-02-13
                            // rac.Account_province_txt__c   = oppMap.get(InquiryNoStr).Agency1__r.OCM_man_province_txt__c;
                            // update by vivek end 2020-02-13
                            rac.Dealer_Info_IF__c         = oppMap.get(InquiryNoStr).Agency1__c;
                            rac.DeliveryNote__c           = infoH.DeliveryNote;
                            // update by Gaozw start 20200514
                            rac.SerialLotNo__c            = dnInfo.SerialNoorLotNo == '.'? datestr : dnInfo.SerialNoorLotNo;
                            // update by Gaozw end 20200514
                            rac.TracingCode__c            = dnInfo.TracingCode;
                            // HHOA-BFF53G IF来源
                            rac.IF_Information_From__c    = true;
                            //全部System
                            rac.OwnerId                   = System.Label.User_OlympusSystem;
                            //生成追溯明细时 记录SAP合同号 by rentx 2020-12-14
                            if (String.isNotEmpty(InquiryNoStr2)) {
                                rac.ContractNo_text__c  = InquiryNoStr2;
                            }
                            //生成追溯明细时 记录SAP合同号
                            // 【委托】ET消耗品系统自动生成出库数量大于当月发货数量 精琢技术 tcm start
                            if (String.isNotEmpty(InquiryNoStr)) {
                                rac.Opportunity_No__c = InquiryNoStr;
                            }
                        }else{
                            // if (rac.Arrive_date__c == null){
                            //     rac.Arrive_date__c           = NFMUtil.parseStr2Date(infoH.DeliveryDate);
                            // }
                            if (rac.Used_date__c == null){
                                rac.Used_date__c           = NFMUtil.parseStr2Date(infoH.DeliveryDate);
                            }
                        }
                        rac.Sales_Shop_Class__c = true;
                        cod2List.add(rac);
                        odDSUpsertMap.put(InquiryNoStr + ':' + dnInfo.Barcode, rac);
                        odUpsertIdxMap.put(InquiryNoStr + ':' + dnInfo.Barcode, odDSUpsertMap.size());
                        if (odDSUpsertIdxMap.containsKey(accsMap.get(infoH.EndUserNo).Id + ':' + oppMap.get(InquiryNoStr).Id + '')) {
                            odDSUpsertIdxMap.get(accsMap.get(infoH.EndUserNo).Id + ':' + oppMap.get(InquiryNoStr).Id + '').add(rac);
                        } else {
                            odDSUpsertIdxMap.put(accsMap.get(infoH.EndUserNo).Id + ':' + oppMap.get(InquiryNoStr).Id + '', cod2List.clone());
                        }
                        // 【委托】ET消耗品系统自动生成出库数量大于当月发货数量 精琢技术 tcm end
                    } else {
                        continue;
                    }

                    // 自动修改最终用户 update by vivek start
                        if (!(oppMap.get(InquiryNoStr) != null && (agencyContractETMap.get(oppMap.get(InquiryNoStr).Agency1__c) != null)
						&& (prdSearch.Pro2_Dealer_Object__c && !(oppMap.get(InquiryNoStr).Purchase_Type__c != 'ET24時間販売'  && oppMap.get(InquiryNoStr).Opportunity_Category__c != 'ET')))) {
                            if (orderOutMap.containsKey(InquiryNoStr) == false) {
                                Consumable_order__c autoOrder = new Consumable_order__c();
                                autoOrder.Name = '*';
                                autoOrder.OwnerId = System.Label.User_OlympusSystem;
                                autoOrder.RecordTypeid = System.Label.RT_ConOrder_Sale;
                                autoOrder.Dealer_Info__c = oppMap.get(InquiryNoStr).Agency1__c;
                                autoOrder.Order_ForHospital__c = accsMap.get(infoH.EndUserNo).Id;
                                autoOrder.Order_type__c = '销售';
                                autoOrder.SummonsStatus_c__c = '已完成';
                                autoOrder.SummonsForDirction__c = '直接销售给医院';
                                autoOrder.Outbound_Date__c = NFMUtil.parseStr2Date(infoH.DeliveryDate);
                                autoOrder.Order_ForCustomerText__c = accsMap.get(infoH.DepartmentNo).Department_Name__c;
                                autoOrder.Opportunity__c = oppMap.get(InquiryNoStr).Id;
                                orderOutMap.put(InquiryNoStr, autoOrder);
                            }
                        }
                }
            }
            logstr += '\norderOutMap +++++++++++: '+ orderOutMap.size();
            //直销耗材 返品单、出库单新建
            if (orderOutMap.size() > 0) {
                insert orderOutMap.values();
                for (Consumable_order__c co : orderOutMap.values()) {
                    orderReturnIdList.add(co.Id);
                }
            }
            logstr += '\nodDSUpsertMap +++++++++++: '+ odDSUpsertMap.size();
            logstr += '\nodDSUpsertIdxMap +++++++++++: '+ odDSUpsertIdxMap.size();
            logstr += '\nodDSUpsertIdxMapvalues +++++++++++: '+ odDSUpsertIdxMap.values();
            //直销耗材 明细2
            if (odDSUpsertMap.size() > 0) {
                upsert odDSUpsertMap.values();
            }            
            // SWAG-BDV589 end
            // 自动生成出库单信息
            if (odDSUpsertIdxMap.size() > 0) {
                addReturnOrderAuto(odDSUpsertIdxMap);
            }

            logstr += '\nend';
            rowData.DA_retry_cnt__c = 0;
            if(System.Test.isRunningTest()){
                throw new ControllerUtil.myException('测试错误！');
            }
        } catch (Exception ex) {
            // エラーが発生した場合
            Database.rollback(sp);
            System.debug(Logginglevel.ERROR, 'NFM110_' + rowData.MessageGroupNumber__c + ':' + ex.getMessage());
            System.debug(Logginglevel.ERROR, 'NFM110_' + rowData.MessageGroupNumber__c + ':' + ex.getStackTraceString());
            logstr += '\n' + ex.getMessage();
            iflog.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + iflog.ErrorLog__c;
            if (rowData.DA_retry_cnt__c == null) rowData.DA_retry_cnt__c = 0;
            if (rowData.DA_retry_cnt__c < batch_retry_max_cnt) {
                rowData.DA_retry_cnt__c++;
                // LogAutoSendSchedule.assignOneMinute();
                //if(!Test.isRunningTest()) LogAutoSendSchedule.assignOneMinute();
            }
            if (rowData.DA_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;
    }

    
    // 耗材直销自动生成出库、退货单
    global static void addReturnOrderAuto (Map<String, List<Consumable_order_details2__c> > addMap) {
        Map<String, List<Consumable_order_details2__c> > accountGroupMap = new Map<String, List<Consumable_order_details2__c> >();
        Map<String, Map<Id, Integer> > productMap = new Map<String, Map<Id, Integer> > ();
        // 根据订单生成返品订单List
        List<Consumable_order__c> orderList = [select Id, Name, Order_ForHospital__c, Order_ForCustomerText__c,
                                               Order_type__c, Dealer_Info__c, Opportunity__c
                                               from Consumable_order__c
                                               where id in : orderReturnIdList];
        Map<String, List<Consumable_orderdetails__c> > insDetail1Map = new Map<String, List<Consumable_orderdetails__c> >();
        //出库单明细
        for (String keystr : addMap.keySet()) {
            for (Consumable_order_details2__c cod : addMap.get(keystr)) {
                List<Consumable_order_details2__c> accGroupList = new List<Consumable_order_details2__c> ();
                if (accountGroupMap.containsKey(keystr)) {
                    accGroupList = accountGroupMap.get(keystr);
                }
                accGroupList.add(cod);
                accountGroupMap.put(keystr, accGroupList);
            }
        }
        // 设置明细2 的 订单ID
        Map<String,Consumable_order_details2__c> updDetail2Map = new Map<String,Consumable_order_details2__c> ();
        for (Consumable_order__c setId : orderList) {
            //System.debug('订单明细22222 ' + setId.Order_ForHospital__c + ':' + setId.Opportunity__c);
            //System.debug('返品单Name   ' + setId.Name);
            // 明细2
            List<Consumable_order_details2__c> d2list = accountGroupMap.get(setId.Order_ForHospital__c + ':' + setId.Opportunity__c);
            if (d2list == null) continue;
            Integer i = 1;
            for (Consumable_order_details2__c dtl2 : d2list) {
                if (setId.Order_type__c == '销售') {
                    dtl2.Name = setId.Name + ':' + ('000' + i).right(4);
                    dtl2.Consumable_Sale_order__c = setId.Id;
                    dtl2.Consumable_ZS_order__c = setId.Id;
                } else {
                    dtl2.Consumable_Return_order__c = setId.Id;
                }
                updDetail2Map.put(dtl2.Bar_Code__c, dtl2);
                i++;
            }
        }
        update updDetail2Map.values();
    }

    global void finish(Database.BatchableContext BC) {

    }

}