@RestResource(urlMapping = '/NFM301/*')
global  with sharing class NFM301Rest {

    public static boolean isRunning = false;
    global class ProductsDeliveryRest {
        public ProductsDelivery ProductsDelivery;
    }
    global class ProductsDelivery{
        public NFMUtil.Monitoring Monitoring;
        public GeneralData[] GeneralData;

    }

    //发货单信息
    global class GeneralData {

        public DnInformation[] DnInformation;
        public String  OrderNumber;                 //合同编号(订单编码)
        public String  SalesOrderNumber;            //订单编号(订单编码)
        public String  CompanyCode;                 //公司代码(备品所属公司CD_txt)
        public String  ApprovalNumber;              //采购申请决裁号(备品采购申请决裁号)
        public String  Category;                    //备品类别
        public String  Purpose;                     //备品用途
        public String  DeliveryDate;                //发货日期
        public String  SendTo;                      //收货方
        public String  ContactPerson;               //联系人
        public String  Comment;                     //备注
        public String  ProcessType;                 //处理方式(1：新建;2：资本化日期更新)
        public String  OtherGeneral1;               //抬头备用1
        public String  OtherGeneral2;               //抬头备用2
        public String  OtherGeneral3;               //抬头备用3
    }

    //备品信息
    global class DnInformation {

        public String  ProductCode;                 //物料(产品)
        public String  AssetNumber;                 //固定资产编号
        public String  AssetDay;                    //资本化日期
        public String  SerialNumber;                //机身编码/批次号(机身编码)
        public String  SorLMark;                    //SorLMark(保有设备标记)
        public String  TracingCode;                 //TracingCode
        public String  Barcode;                     //Barcode
        public String  ValidTo;                     //使用期限
        public String  CostCenterCD;                //备品成本中心(备品成本中心CD)
        public String  CostCenterMemo;              //备品成本中心描述(备品成本中心-文本)
        public String  InchargeProvinceCD;          //业务范围(业务范围CD)
        public String  InchargeProvince;            //业务范围描述(备品资产管理负责省)
        public String  LocationCD;                  //存放地点(备品存放地CD_txt)
        public String  LocationName;                //存放地点描述(备品存放地)
        public String  NMPA_NO;                     //产品注册证号/备案凭证编号
        public String  Provider;                    //生产企业
        public String  ProductionDate;               //生产日期
        // public String  OtherDetail1;                //明细备用1->有效期限（使用期限）
        // public String  OtherDetail2;                //明细备用2->SFDA证书开始日期
        // public String  OtherDetail3;                //明细备用3->SFDC证书结束日期
        public String  NMPA_ValidDate;              //SFDA证书的产品有效期限
        public String  NMPA_ValidFrom;              //SFDA证书开始日期
        public String  NMPA_ValidTo;                //SFDA证书结束日期
        // 【FY24大及巨大课题】北京新法规项目对应 DB202307428742 20230804 by lc Start
        public String  SHELF_LIFE;                  //储存条件
        public String  TRANS_CONDITION;             //运输条件
        // 【FY24大及巨大课题】北京新法规项目对应 DB202307428742 20230804 by lc End
    }

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

        if (ges == null ) {
            return;
        }
                        
        NFMUtil.Monitoring Monitoring = ges.ProductsDelivery.Monitoring;
        if (Monitoring == null) {
            return;
        }

        BatchIF_Log__c rowData = NFMUtil.saveRowData(Monitoring, 'NFM301', ges.ProductsDelivery.GeneralData);
        if (String.isBlank(rowData.Log__c) == false) {
            executefuture(rowData.Id);
        }
        // JSONを戻す
        RestResponse res = RestContext.response;
        res.addHeader('Content-Type', 'application/json');
        res.statusCode = 200;
        String jsonResponse = '{"status": "Success", "Message":""}';
        res.responseBody = blob.valueOf(jsonResponse);
        return;
    }

    @future
    global static void executefuture(String rowData_Id) {
        Oly_TriggerHandler.bypass(ReceivingNoteHandler.class.getName());
        main(rowData_Id);
    }

    global static void main(String rowData_Id) {
        Oly_TriggerHandler.bypass(ReceivingNoteHandler.class.getName());
        Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
        BatchIF_Log__c rowData = [Select Id, Name, Log__c, ErrorLog__c, Log2__c, Log3__c, Log4__c, Log5__c, Log6__c, Log7__c, Log8__c, Log9__c, Log10__c, Log11__c, Log12__c, MessageGroupNumber__c,retry_cnt__c from BatchIF_Log__c where RowDataFlg__c = true and Id = :rowData_Id];
        String logstr = rowData.MessageGroupNumber__c + ' start\n';
        BatchIF_Log__c iflog = new BatchIF_Log__c();
        iflog.Type__c = 'NFM301';
        iflog.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
        iflog.Log__c = logstr;
        iflog.ErrorLog__c = '';
        insert iflog;

        String rowDataStr = NFMUtil.getRowDataStr(rowData);
        List<GeneralData> geDataList = (List<GeneralData>) JSON.deserialize(rowDataStr, List<GeneralData>.class);
        if (geDataList == null || geDataList.size() == 0) {
            return;
        }

        String hospitalStr = Label.Account_Asset_Hospatal;
        String strategyDepartmentStr = Label.Account_Asset_Department;
        String clientStr = Label.Account_Asset_Client;

        //医院
        Account hospital = [select Id from Account where AgentCode_Ext__c = :hospitalStr];
        //战略科室
        Account strategyDepartment = [select Id from Account where AgentCode_Ext__c = :strategyDepartmentStr];
        //客户
        Account client = [select Id from Account where AgentCode_Ext__c = :clientStr];
        // 自定义设置，创建tracingcode
        List<TracingCode__c> cslist = [select trscingcode__c,SerialNumber__c,name__c from TracingCode__c ];
        Decimal createTracingCode = cslist[0].trscingcode__c;
        Decimal createSerialNumber = cslist[0].SerialNumber__c;
        String thirdParty = cslist[0].name__c;
        Savepoint sp = Database.setSavepoint();

        List<GeneralData> genlDatas = new List<GeneralData>();
        List<String> serialNumberList = new List<String>();
        Map<String,Asset> serialNumberIdMap = new  Map<String,Asset>();
        List<String> productCodeList = new List<String>();
        Map<String,String> productCode_IdMap = new  Map<String,String>();
        Map<String,String> productCode_NameMap = new  Map<String,String>();
        Map<String,String> productCode_ModelNoMap = new Map<String,String>();

        Map<String,String> summaryReceivingNoteMap = new Map<String,String>();
        Map<String,String> assReceivingNoteMap = new Map<String,String>();

        //List<String> companyCodeList = new List<String>();
        //List<String> assetNumberList = new List<String>();
        List<String> InternalAssetnumberkeyList = new List<String>();
        Set<String> InternalAssetnumberSet = New Set<String>(); // 20230517 ljh 301在7：30执行优化
        List<String> InternalInsertAssetnumberkeyList = new List<String>();
        Map<String,Asset> companyCodeAssetNumberMap = new  Map<String,Asset>();
        isRunning = true;
        List<String>  receivingNoteList = new List<String>();
        try {
            //验证必填字段
            for (GeneralData info: geDataList) {
                if (info.ProcessType != '1' && info.ProcessType != '2') {
                    iflog.ErrorLog__c += 'ApprovalNumber[ '+info.ApprovalNumber+' ] of ProcessType [ '+info.ProcessType+' ] Not specified ,This data is skipped.\n';
                    continue;
                }

                if (info.DnInformation == null) {
                    iflog.ErrorLog__c += 'ApprovalNumber[ '+info.ApprovalNumber+' ] of DnInformation is required,This data is skipped.\n';
                    continue;
                }

                if (String.isBlank(info.CompanyCode)) {
                    iflog.ErrorLog__c += 'ApprovalNumber[ '+info.ApprovalNumber+' ] of CompanyCode is required,This data is skipped.\n';
                    continue;
                }

                if (info.ProcessType == '1') {

                    if (String.isBlank(info.SalesOrderNumber)) {

                        iflog.ErrorLog__c += 'ApprovalNumber[ '+info.ApprovalNumber+' ] of SalesOrderNumber is required,This data is skipped.\n';
                        continue;
                    }

                    if (String.isBlank(info.DeliveryDate)) {
                        iflog.ErrorLog__c += 'ApprovalNumber[ '+info.ApprovalNumber+' ] of DeliveryDate is required,This data is skipped.\n';
                        continue;
                    }
                }

                for (DnInformation dnInfo : info.DnInformation) {

                    // if (String.isBlank(dnInfo.SerialNumber)) {
                    //     iflog.ErrorLog__c += 'ApprovalNumber[ '+info.ApprovalNumber+' ] of SerialNumber is required,This data is skipped.\n';
                    //     continue;
                    // }
                    
                    if (String.isBlank(dnInfo.ProductCode)) {
                        iflog.ErrorLog__c += 'SerialNumber[ '+dnInfo.SerialNumber+' ] of ProductCode is required,This data is skipped.\n';
                        continue;
                    }

                    if (info.ProcessType == '2' && String.isBlank(dnInfo.AssetNumber)) {
                        iflog.ErrorLog__c += 'SerialNumber[ '+dnInfo.SerialNumber+' ] of AssetNumber is required,This data is skipped.\n';
                        continue;
                    }

                    if (info.ProcessType == '2' && String.isBlank(dnInfo.AssetDay)) {
                        iflog.ErrorLog__c += 'SerialNumber[ '+dnInfo.SerialNumber+' ] of ProcessType is 2 ,The AssetDay is required,This data is skipped.\n';
                        continue;
                    }

                    // if (info.ProcessType == '1') {
                    //     if (dnInfo.SorLMark != 'S' &&  dnInfo.SorLMark != 'L') {
                    //         iflog.ErrorLog__c += 'SerialNumber[ '+dnInfo.SerialNumber+' ] of SorLMark [ '+dnInfo.SorLMark+' ] Not specified ,This data is skipped.\n';
                    //         continue;
                    //     }
                    // }
                    if(dnInfo.LocationCD == '1021'){
                        dnInfo.LocationName = '北京 备品中心';
                    }
                    if(dnInfo.LocationCD == '2019'){
                        dnInfo.LocationName = '上海 备品中心';
                    }
                    if(dnInfo.LocationCD == '3017'){
                        dnInfo.LocationName = '广州 备品中心';
                    }

                    if (info.ProcessType == '1') {
                        
                        // 为空SerialNumber和tracingcode赋值
                        if(String.isBlank(dnInfo.SerialNumber)){
                            dninfo.SerialNumber = thirdParty+createSerialNumber;
                            createSerialNumber++;
                        }
                        serialNumberList.add(dnInfo.ProductCode +':'+dnInfo.SerialNumber);
                        if(String.isBlank(dnInfo.TracingCode)){
                            dnInfo.TracingCode = thirdParty+createTracingCode;
                            createTracingCode++;
                        }
                        // 之前只有sorLmark!='S'的时候才会补充TracingCode
                        // if(dnInfo.SorLMark != 'S' && String.isBlank(dninfo.TracingCode)){
                        //     dnInfo.TracingCode = thirdParty+createTracingCode;
                        //     createTracingCode++;
                        // }
                        serialNumberList.add(dnInfo.ProductCode +':'+dnInfo.SerialNumber + '('+dnInfo.TracingCode +')');

                        productCodeList.add(dnInfo.ProductCode);

                        receivingNoteList.add(info.SalesOrderNumber + info.DeliveryDate);
                        // System.debug('====================='+Integer.valueOf(info.CompanyCode + dnInfo.AssetNumber));
                        InternalInsertAssetnumberkeyList.add(info.CompanyCode + dnInfo.AssetNumber);
                    } else {
                        InternalAssetnumberkeyList.add(info.CompanyCode + dnInfo.AssetNumber); 
                        InternalAssetnumberSet.add(dnInfo.AssetNumber);// 20230517 ljh 301在7：30执行优化   
                    }

                }

                genlDatas.add(info);

            }
            cslist[0].trscingcode__c = createTracingCode;
            cslist[0].SerialNumber__c = createSerialNumber;
            update cslist;
            //查找收货清单
            Map<String,String> receivingNoteMap = new Map<String,String>();
            
            if ( receivingNoteList.size() > 0) {
                List<ReceivingNote__c> receivingNotes = [select Id,Managment_Code__c from ReceivingNote__c
                                                        where Managment_Code__c In :receivingNoteList];
                if (receivingNotes.size() > 0) {

                    for (ReceivingNote__c rn : receivingNotes) {
                        receivingNoteMap.put(rn.Managment_Code__c,rn.Id);
                    }
                }
                
            }
            // 查找收货清单配套
            //收货清单配套一览的原数据
            Map<String,String> receivingNoteSummaryAllMap = new Map<String,String>();
            Map<String,Integer> receivingNoteSummaryFixMap = new Map<String,Integer>();
            // Map<String,String> receivingNoteSummaryNoMap = new Map<String,String>();
            List<ReceivingNoteSummary__c> receivingNoteSummaryAllList = [select id,Product_Serial_No__c,passTxtNo3__c,ReceivingNote__r.passNo7__c,Fixture_Model_No_F__c,CompanyCodeOfEquipment_txt__c from ReceivingNoteSummary__c where ReceivingNote__c in :receivingNoteMap.values()];
            for(ReceivingNoteSummary__c rns : receivingNoteSummaryAllList){
                receivingNoteSummaryAllMap.put(rns.Product_Serial_No__c, rns.Id);
                // receivingNoteSummaryNoMap.put(rns.Product_Serial_No__c, rns.ReceivingNote__r.passNo7__c);
                if(receivingNoteSummaryFixMap.containsKey(rns.ReceivingNote__r.passNo7__c+rns.Fixture_Model_No_F__c)){
                    if(Integer.valueOf(receivingNoteSummaryFixMap.get(rns.ReceivingNote__r.passNo7__c+rns.Fixture_Model_No_F__c)) < Integer.valueOf(rns.passTxtNo3__c)){
                        receivingNoteSummaryFixMap.put(rns.ReceivingNote__r.passNo7__c+rns.Fixture_Model_No_F__c,Integer.valueOf(rns.passTxtNo3__c));
                    }
                }else{
                    System.debug('========rns.passTxtNo3__c'+rns.passTxtNo3__c);
                    receivingNoteSummaryFixMap.put(rns.ReceivingNote__r.passNo7__c+rns.Fixture_Model_No_F__c,Integer.valueOf(rns.passTxtNo3__c));
                }
            }
            // 查找收货清单配套明细
            Map<String,String> receivingNoteDetailAllMap = new Map<String,String>();
            List<ReceivingNoteDetail__c> receivingNoteDetailAllList = [select id,ReceivingNoteSummary__c from ReceivingNoteDetail__c where ReceivingNoteSummary__c in :receivingNoteSummaryAllMap.values()];
            for(ReceivingNoteDetail__c rnd : receivingNoteDetailAllList){
                receivingNoteDetailAllMap.put(rnd.ReceivingNoteSummary__c, rnd.Id);
            }

            //查找保有设备
            List<Asset> assetList = null;
            if (serialNumberList.size() > 0){

                assetList = [Select Id, Name, Product2.ProductCode, Product2.Dealer_special_Object__c , Product2.Dealer_Object__c,
                                       SerialNumber, Product_Serial_No__c, Repair_Count__c, TracingCode__c,
                                       Product2Id, AccountId, Account.Management_Code__c, Department_Class__c, Hospital__c,
                                       Posting_Date__c, InstallDate, SLMark__c, MDM_Model_No__c, OT_CODE__c,
                                       Guarantee_period_for_products__c, Installation_Site__c, Delete_Flag__c, Return_Flag__c
                                   from Asset  
                                   where Product_Serial_No__c In :serialNumberList];

                if ( assetList.size() > 0) {

                    for (Asset ass:assetList) {

                        serialNumberIdMap.put(ass.Product_Serial_No__c, ass);
                    }
                }
            }


            //查找变更资本化日期的保有设备(根据公司代码和固定资产编号)
            List<Asset> assetNumberAssetList = null;
            if (InternalAssetnumberkeyList.size() > 0) {
                // 20230517 ljh 301在7：30执行优化 start
                // assetNumberAssetList = [Select Id, Name, Product2.ProductCode, Product2.Dealer_special_Object__c , Product2.Dealer_Object__c,
                //                        SerialNumber, Product_Serial_No__c, Repair_Count__c, TracingCode__c,CompanyCodeOfEquipment_txt__c,
                //                        Product2Id, AccountId, Account.Management_Code__c, Department_Class__c, Hospital__c,
                //                        Posting_Date__c, InstallDate, SLMark__c, MDM_Model_No__c, OT_CODE__c,Internal_Asset_number__c,
                //                        Guarantee_period_for_products__c, Installation_Site__c, Delete_Flag__c, Return_Flag__c
                //                    from Asset  
                //                    where Internal_Asset_number_key__c In :InternalAssetnumberkeyList ];
                assetNumberAssetList = [Select Id, Name, Product2.ProductCode, Product2.Dealer_special_Object__c , Product2.Dealer_Object__c,
                                       SerialNumber, Product_Serial_No__c, Repair_Count__c, TracingCode__c,CompanyCodeOfEquipment_txt__c,
                                       Product2Id, AccountId, Account.Management_Code__c, Department_Class__c, Hospital__c,
                                       Posting_Date__c, InstallDate, SLMark__c, MDM_Model_No__c, OT_CODE__c,Internal_Asset_number__c,
                                       Guarantee_period_for_products__c, Installation_Site__c, Delete_Flag__c, Return_Flag__c
                                   from Asset  
                                   where Internal_Asset_number_key__c In :InternalAssetnumberkeyList and Internal_Asset_number__c In :InternalAssetnumberSet ];   
                // 20230517 ljh 301在7：30执行优化 end
                if ( assetNumberAssetList.size() > 0) {

                    for (Asset ass :assetNumberAssetList) {
                        String assetNumberStr = ass.CompanyCodeOfEquipment_txt__c + ass.Internal_Asset_number__c;
                        companyCodeAssetNumberMap.put(assetNumberStr,ass);
                    }
                }

            }
            
            List<String> fixtureSetId = new List<String>();
            Map<String,String> fixmodelNo_proIdMap = new Map<String,String>();
            Map<String,String> productCode_FixmodelMap = new Map<String,String>();
            // 【FY24大及巨大课题】北京新法规项目对应 DB202307428742 20230801 by lc Start
            Map<String,Product2> productCode_Product2Map = new Map<String,Product2>();
            List<String> assetModelNoList = new List<String>();
            Map<String,Product2> assetModelNo_Product2Map = new Map<String,Product2>();
            // 【FY24大及巨大课题】北京新法规项目对应 DB202307428742 20230801 by lc End
            //查找产品
            List<Product2> productList = null;
            if (productCodeList.size() > 0) {
                productList = [Select Id,Name,ProductCode,Fixture_Model_No_F__c,Asset_Model_No__c,Storage_Conditions__c,Transportation_Conditions__c  
                                    from Product2 
                                    where ProductCode 
                                    In :productCodeList];

                if ( productList.size() > 0) {
                    for (Product2 product :productList) {
                        fixtureSetId.add(product.Fixture_Model_No_F__c);
                        productCode_IdMap.put(product.ProductCode,product.Id);
                        productCode_NameMap.put(product.ProductCode,product.Name);
                        productCode_ModelNoMap.put(product.ProductCode, product.Fixture_Model_No_F__c);
                        fixmodelNo_proIdMap.put(product.Fixture_Model_No_F__c, product.Id);
                        productCode_FixmodelMap.put(product.ProductCode, product.Fixture_Model_No_F__c);
                        // 【FY24大及巨大课题】北京新法规项目对应 DB202307428742 20230801 by lc Start
                        assetModelNoList.add(product.Asset_Model_No__c);
                        productCode_Product2Map.put(product.ProductCode, product);
                        // 【FY24大及巨大课题】北京新法规项目对应 DB202307428742 20230801 by lc End
                    }
                }
            }

            // 【FY24大及巨大课题】北京新法规项目对应 DB202307428742 20230801 by lc Start
            if (!assetModelNoList.isEmpty()) {
                List<Product2> proAssetModelNoList = [
                        Select Id, ProductCode, Asset_Model_No__c, Storage_Conditions__c, Transportation_Conditions__c 
                        FROM Product2 
                        WHERE Asset_Model_No__c IN: assetModelNoList
                        AND (Storage_Conditions__c != null OR Transportation_Conditions__c != null)];

                for (Product2 prod : proAssetModelNoList) {
                    if (assetModelNo_Product2Map.isEmpty() || !assetModelNo_Product2Map.containsKey(prod.Asset_Model_No__c)) {
                        assetModelNo_Product2Map.put(prod.Asset_Model_No__c, prod);
                    }
                }
            }
            // 【FY24大及巨大课题】北京新法规项目对应 DB202307428742 20230801 by lc End

            // 查找备品配套，包括主体备品配套明细
            Map<String,String> fixtureSetMap = new Map<String,String>();
            List<String> fixtrueSetDetailId = new List<String>();
            // Map<String,String> fixtureSetIdMap = new Map<String,String>();
            List<Fixture_Set__c> fixtureSetList = [select id,Fixture_Set_Body_Model_No__c,Loaner_code__c from Fixture_Set__c where Fixture_Set_Body_Model_No__c In :fixtureSetId];
            for(Fixture_Set__c fixset : fixtureSetList){
                fixtureSetMap.put(fixset.Loaner_code__c, fixset.Id);
                fixtrueSetDetailId.add(fixset.Id+':'+fixmodelNo_proIdMap.get(fixset.Loaner_code__c));
            }
            // 查找备品配套明细
            Map<String,String> fixtrueSetDetailMap = new Map<String,String>();
            List<Fixture_Set_Detail__c> fixtrueSetDetailList = [select id,UniqueKey__c from Fixture_Set_Detail__c where UniqueKey__c In :fixtrueSetDetailId];
            for(Fixture_Set_Detail__c fixSetDetail :fixtrueSetDetailList){
                fixtrueSetDetailMap.put(fixSetDetail.UniqueKey__c,fixSetDetail.Id);
            }


            if (genlDatas.size() > 0) {
                List<String> receivingNoteOnlyInsertList = new List<String>(); 

                List<ReceivingNote__c>  upsertReceivingNotes = new List<ReceivingNote__c>();
                //新建或更新"收货清单"
                for (GeneralData info: genlDatas) {
                    if (info.ProcessType != '1' && info.ProcessType != '2') {
                        continue;
                    }

                    if (info.DnInformation == null) {
                        continue;
                    }

                    if (String.isBlank(info.CompanyCode)) {
                        continue;
                    }

                    if (info.ProcessType == '1') {
                        if (String.isBlank(info.SalesOrderNumber)) {
                            continue;
                        }

                        if (String.isBlank(info.DeliveryDate)) {
                            continue;
                        }
                    }

                    // for (DnInformation dnInfo : info.DnInformation) {

                    //     if (String.isBlank(dnInfo.ProductCode)) {
                    //         continue;
                    //     }

                    //     if (String.isBlank(dnInfo.SerialNumber)) {
                    //         continue;
                    //     }

                    //     if (info.ProcessType == '2' && String.isBlank(dnInfo.AssetNumber)) {
                    //         continue;
                    //     }

                    //     if (info.ProcessType == '2' && String.isBlank(dnInfo.AssetDay)) {
                    //         continue;
                    //     }
                    // }
                    ReceivingNote__c receivingNote = new ReceivingNote__c();
                    String str = info.SalesOrderNumber + info.DeliveryDate;    
                    if (info.ProcessType == '1') {

                        if (receivingNoteMap.containsKey(info.SalesOrderNumber + info.DeliveryDate)) {
                            System.debug('更新收货清单'+receivingNoteMap.get(info.SalesOrderNumber + info.DeliveryDate));
                            receivingNote.Id = receivingNoteMap.get(info.SalesOrderNumber + info.DeliveryDate);
                        } 
                        // receivingNote.ManagementCode__c = info.SalesOrderNumber + info.DeliveryDate;
                        
                        receivingNote.Managment_Code__c = str;
                        receivingNote.Sales_order_number__c = info.SalesOrderNumber;
                        //wangweipeng 20210616  备品收货清单 新增一个字段 “联系人”  需要自动获取字段数据
                        if(!String.isBlank(info.ContactPerson)){
                            receivingNote.ContactPerson__c = info.ContactPerson;
                        }
                        receivingNote.OrderCode__c = info.OrderNumber;
                        receivingNote.ApprovalNumber__c = info.ApprovalNumber;
                        receivingNote.Asset_loaner_category__c = info.Category;
                        receivingNote.DateOfDelivery__c = NFMUtil.parseStr2Date(info.DeliveryDate);
                        // receivingNote.ManagementCenter__c = info.OrderNumber.substring(0,4);
                        // 发货状态
                        // receivingNote.Status__c = '待数据确认';
                        // 获取备品存放地址
                        for (DnInformation dnInfo : info.DnInformation) {
                            receivingNote.Internal_asset_location__c = dnInfo.LocationName;
                            // if(dnInfo.LocationCD == '1021' || dnInfo.LocationCD == '1028'){
                            if(dnInfo.LocationCD == '1021'){
                                receivingNote.ManagementCenter__c = 'BJ';
                            // }else if(dnInfo.LocationCD == '2014' || dnInfo.LocationCD == '2019'){
                            }else if(dnInfo.LocationCD == '2019'){
                                receivingNote.ManagementCenter__c = 'SH';
                            }else if(dnInfo.LocationCD == '3017'){
                                receivingNote.ManagementCenter__c = 'GZ';
                            }else{
                                receivingNote.ManagementCenter__c = 'ZZ';
                            }
                            break;
                        }
                        
                        // receivingNote.ManagementCode__c = 'str';
                        upsertReceivingNotes.add(receivingNote);
                        // System.debug('========='+Integer.valueOf('新建收货清单'));
                        receivingNoteOnlyInsertList.add(info.SalesOrderNumber + info.DeliveryDate);
                    }
                }
                // 发邮件做准备，清单已存在不需要更新
                List<ReceivingNote__c> insertReceivingNote = new List<ReceivingNote__c>();
                // List<ReceivingNote__c> updateReceivingNote = new List<ReceivingNote__c>();
                List<String> updateReceivingNote = new List<String>();
                for(ReceivingNote__c receivingmote :upsertReceivingNotes){
                    if(receivingmote.Id == null ){
                        insertReceivingNote.add(receivingmote);
                    }else{
                        updateReceivingNote.add(receivingmote.Id);
                    }
                }
                // if (upsertReceivingNotes.size() > 0) {
                //     upsert upsertReceivingNotes;
                // }
                if (insertReceivingNote.size() > 0) {
                    insert insertReceivingNote;
                }

                // 收货清单的外键和id
                Map<String,String> receivingNoteIdMap = new Map<String,String>();
                Map<String,String> receivingNoteNoMap = new Map<String,String>();
                if ( receivingNoteOnlyInsertList.size() > 0) {
                // if ( receivingNoteList.size() > 0) {
                    // List<ReceivingNote__c> receivingNotes = [select Id,ManagementCode__c from ReceivingNote__c
                    //                                         where ManagementCode__c In :receivingNoteList];
                    List<ReceivingNote__c> receivingNotes = [select Id,Managment_Code__c,passNo7__c from ReceivingNote__c
                                                            where Managment_Code__c In :receivingNoteOnlyInsertList];
                    if (receivingNotes.size() > 0) {

                        for (ReceivingNote__c rn : receivingNotes) {
                            // System.debug('========='+Integer.valueOf(rn.ManagementCode__c));
                            receivingNoteIdMap.put(rn.Managment_Code__c,rn.Id);
                            receivingNoteNoMap.put(rn.Managment_Code__c,rn.passNo7__c);
                        }
                    }
                    
                }

                // System.debug('========='+Integer.valueOf('新建收货清单配套外1'));
                //新建"收货清单配套一览"
                List<ReceivingNoteSummary__c> receivingNoteSummaryList = new List<ReceivingNoteSummary__c>();
                for (GeneralData info: genlDatas) {
                    // System.debug('========='+Integer.valueOf('新建收货清单配套外'));
                    // ReceivingNoteSummary__c receivingNoteSummary = new ReceivingNoteSummary__c();
                    for (DnInformation dnInfo : info.DnInformation) {
                        // System.debug('========='+Integer.valueOf('新建收货清单配套内'));

                        if (String.isBlank(dnInfo.ProductCode)) {
                            continue;
                        }

                        if (String.isBlank(dnInfo.SerialNumber)) {
                            continue;
                        }

                        if (info.ProcessType == '2' && String.isBlank(dnInfo.AssetNumber)) {
                            continue;
                        }

                        if (info.ProcessType == '2' && String.isBlank(dnInfo.AssetDay)) {
                            continue;
                        }

                        // if (info.ProcessType == '1') {
                        //     if (dnInfo.SorLMark != 'S' &&  dnInfo.SorLMark != 'L') {
                        //         continue;
                        //     }
                        // }

                        if (info.ProcessType == '1') {
                            if (receivingNoteIdMap.containsKey(info.SalesOrderNumber + info.DeliveryDate)) {
                                ReceivingNoteSummary__c receivingNoteSummary = new ReceivingNoteSummary__c();
                                // 判断是否需要更新
                                if(receivingNoteSummaryAllMap.containsKey(dnInfo.ProductCode+':'+dnInfo.SerialNumber) || receivingNoteSummaryAllMap.containsKey(dnInfo.ProductCode+':'+dnInfo.SerialNumber+'('+dnInfo.TracingCode+')')){
                                    if(dnInfo.SorLMark == 'S'){
                                        receivingNoteSummary.Id = receivingNoteSummaryAllMap.get(dnInfo.ProductCode+':'+dnInfo.SerialNumber);
                                    }else{
                                        receivingNoteSummary.Id = receivingNoteSummaryAllMap.get(dnInfo.ProductCode+':'+dnInfo.SerialNumber+'('+dnInfo.TracingCode+')');
                                    }
                                    
                                    // Integer.valueOf(receivingNoteSummaryAllMap.get(dnInfo.ProductCode+':'+dnInfo.SerialNumber)+'==='+receivingNoteSummaryAllMap.get(dnInfo.ProductCode+':'+dnInfo.SerialNumber+'('+dnInfo.TracingCode+')')+'==='+receivingNoteSummaryAllMap);
                                    // System.debug(Integer.valueOf(productCode_FixmodelMap+'==='+receivingNoteSummaryFixMap));
                                }else{
                                    System.debug('======进入fuzhi选项');
                                    // Integer.valueOf(receivingNoteIdMap.get(info.SalesOrderNumber + info.DeliveryDate)+'==='+receivingNoteIdMap);
                                    receivingNoteSummary.ReceivingNote__c = receivingNoteIdMap.get(info.SalesOrderNumber + info.DeliveryDate);
                                }
                                    String noKey = receivingNoteNoMap.get(info.SalesOrderNumber + info.DeliveryDate);
                                    // 判断产品是否存在，存在则通过productcode获取，备品配套明细型号
                                    // System.debug(Integer.valueOf(productCode_FixmodelMap+'==='+receivingNoteNoMap+'+++'+receivingNoteSummaryFixMap+'一条数据'+'键值'+noKey+'---'+receivingNoteNoMap.get(noKey)+productCode_FixmodelMap.get(dnInfo.ProductCode)));
                                    if(productCode_FixmodelMap.containsKey(dnInfo.ProductCode)){
                                        // 判断收货清单一览上是否存在
                                        if(receivingNoteSummaryFixMap.containsKey(noKey+productCode_FixmodelMap.get(dnInfo.ProductCode))){
                                            Integer passTxtNo3 = receivingNoteSummaryFixMap.get(noKey+productCode_FixmodelMap.get(dnInfo.ProductCode));
                                            passTxtNo3++;
                                            if(passTxtNo3 >= 1 && passTxtNo3 < 10 ){
                                                receivingNoteSummary.passTxtNo3__c = '00'+passTxtNo3;
                                                 receivingNoteSummaryFixMap.put(noKey+productCode_FixmodelMap.get(dnInfo.ProductCode),passTxtNo3);
                                            }
                                            if(passTxtNo3 >= 10 && passTxtNo3 < 100){
                                                receivingNoteSummary.passTxtNo3__c = '0'+passTxtNo3;
                                                 receivingNoteSummaryFixMap.put(noKey+productCode_FixmodelMap.get(dnInfo.ProductCode),passTxtNo3);
                                            }
                                            if(passTxtNo3 >= 100){
                                                receivingNoteSummary.passTxtNo3__c = ''+passTxtNo3;
                                                 receivingNoteSummaryFixMap.put(noKey+productCode_FixmodelMap.get(dnInfo.ProductCode),passTxtNo3);
                                            }
                                        }else{
                                            receivingNoteSummary.passTxtNo3__c = '001';
                                            receivingNoteSummaryFixMap.put(noKey+productCode_FixmodelMap.get(dnInfo.ProductCode),1);
                                        }
                                    }
                                // }
                                // 如果是s主机
                                if (dnInfo.SorLMark == 'S') {
                                    receivingNoteSummary.Product_Serial_No__c = dnInfo.ProductCode+':'+dnInfo.SerialNumber;
                                }else{
                                    receivingNoteSummary.Product_Serial_No__c = dnInfo.ProductCode+':'+dnInfo.SerialNumber+'('+dnInfo.TracingCode+')';
                                }
                                // 为收货清单配套一览字段赋值
                                if(fixtureSetMap.containsKey(productCode_ModelNoMap.get(dnInfo.ProductCode))){
                                    receivingNoteSummary.Fixture_Set__c = fixtureSetMap.get(productCode_ModelNoMap.get(dnInfo.ProductCode));
                                }


                                // receivingNoteSummary.Fixture_Model_No_F__c = productCode_ModelNoMap.get(dnInfo.ProductCode);
                                receivingNoteSummary.QRCode__c = dnInfo.Barcode;
                                receivingNoteSummaryList.add(receivingNoteSummary);
                                
                            } 
                            // receivingNoteSummaryList.add(receivingNoteSummary);
                            
                        }

                        
                    }

                    // if (receivingNoteSummaryList.size() >0) {
                    //     Insert receivingNoteSummaryList;
                    // }

                }
                // 邮件收货清单一览，只创建不更新
                List<ReceivingNoteSummary__c> insertRreceivingNoteSummary = new List<ReceivingNoteSummary__c>();
                // List<ReceivingNoteSummary__c> updateRreceivingNoteSummary = new List<ReceivingNoteSummary__c>();
                List<String> updateRreceivingNoteSummary = new List<String>();
                for(ReceivingNoteSummary__c receivingnotesum :receivingNoteSummaryList){
                    if(receivingnotesum.Id == null ){
                        insertRreceivingNoteSummary.add(receivingnotesum);
                    }else{
                        updateRreceivingNoteSummary.add(receivingnotesum.Id);
                    }
                }
                // if (receivingNoteSummaryList.size() >0) {
                //     upsert receivingNoteSummaryList;
                // }
                System.debug('======insertRreceivingNoteSummary'+insertRreceivingNoteSummary);
                if (insertRreceivingNoteSummary.size() >0) {
                    insert insertRreceivingNoteSummary;
                }

                receivingNoteSummaryList = [select Id,Product_Serial_No__c,CompanyCodeOfEquipment_txt__c from ReceivingNoteSummary__c 
                                    where ReceivingNote__c In :receivingNoteIdMap.values()];
                // 配套一览的拼接的外部id和配套一览
                // Map<String,ReceivingNoteSummary__c> summaryReceivingNoteMap = new Map<String,ReceivingNoteSummary__c>();

                
                if (receivingNoteSummaryList.size() > 0) {

                    for (ReceivingNoteSummary__c receivingNoteSummary :receivingNoteSummaryList){
                        // System.debug(Integer.valueOf('qingkuang'+receivingNoteSummary));
                        // summaryReceivingNoteMap.put(receivingNoteSummary.CompanyCodeOfEquipment_txt__c+receivingNoteSummary.Internal_Asset_number__c, receivingNoteSummary.Id);
                        summaryReceivingNoteMap.put(receivingNoteSummary.Product_Serial_No__c, receivingNoteSummary.Id);
                    }
                }
                
                // 创建或更新保有设备
                List<Asset> assets = new List<Asset>();
                // 更新资本化日期
                List<Asset> updateAssetZB = new List<Asset>();
                // 【FY24大及巨大课题】北京新法规项目对应 DB202307428742 20230804 by lc Start
                Map<String, String> usedProductCode_Product2Map = new Map<String, String>();
                List<Product2> updProduct2List = new List<Product2>();
                // 备品中心邮件内容
                String emailBody = '';
                // 【FY24大及巨大课题】北京新法规项目对应 DB202307428742 20230804 by lc End
                for (GeneralData info: genlDatas) {

                    for (DnInformation dnInfo : info.DnInformation) {

                        if (String.isBlank(dnInfo.ProductCode)) {
                            continue;
                        }

                        // 20230221 ljh start 没说上线所以还是原来的，下面修改好的
                        if (String.isBlank(dnInfo.SerialNumber)) {
                        // if (info.ProcessType == '1' &&  String.isBlank(dnInfo.SerialNumber)) {
                        // 20230221 ljh end 
                            continue;
                        }
                        if (info.ProcessType == '2' && String.isBlank(dnInfo.AssetNumber)) {
                            continue;
                        }

                        if (info.ProcessType == '2' && String.isBlank(dnInfo.AssetDay)) {
                            continue;
                        }

                        // if (info.ProcessType == '1') {
                        //     if (dnInfo.SorLMark != 'S' &&  dnInfo.SorLMark != 'L') {
                        //         continue;
                        //     }
                        // }

                        Asset asset = new Asset();
                        Asset assetZB = new Asset();
                        ReceivingNote__c receivingNote = new ReceivingNote__c();
                        //List<ReceivingNote__c>  upsertReceivingNotes = new List<ReceivingNote__c>();
                        //ProcessType(处理方式)为1时，首先根据Product_Serial_No__c查询是否已存在，若存在则更新，否则新增
                        if (info.ProcessType == '1') {

                            //if (receivingNoteMap.containsKey(info.SalesOrderNumber + info.DeliveryDate)) {
                            //    receivingNote = receivingNoteMap.get(info.SalesOrderNumber + info.DeliveryDate);
                            //} else {
                            //    //新增收货清单
                            //}

                            //upsertReceivingNotes




                            if (productCode_IdMap.containsKey(dnInfo.ProductCode)) {

                                asset.Product2Id = productCode_IdMap.get(dnInfo.ProductCode);
                            } else {

                                iflog.ErrorLog__c += 'SerialNumber[ '+dnInfo.SerialNumber+' ] of ProductCode[ '+dnInfo.ProductCode+' ] is not exist,This data is skipped .\n';
                                continue;
                            }

                            if (dnInfo.SorLMark == 'S') {

                                if (serialNumberIdMap.containsKey(dnInfo.ProductCode+':'+dnInfo.SerialNumber)){
                                    asset =  serialNumberIdMap.get(dnInfo.ProductCode+':'+dnInfo.SerialNumber);
                                } else {
                                    //新建保有设备
                                    if (productCode_NameMap.containsKey(dnInfo.ProductCode)) {
                                        
                                        asset.Name = productCode_NameMap.get(dnInfo.ProductCode);
                                    }
                                    
                                }

                                asset.Product_Serial_No__c = dnInfo.ProductCode+':'+dnInfo.SerialNumber;
                                asset.AssetMark__c = '主机';
                                // SerialNumber为空或者TracingCode为空处理 start
                                // SerialNumber为空且TracingCode为空
                                if(dnInfo.TracingCode.substring(0,1) == '第' && dnInfo.SerialNumber.substring(0,1) == '第'){
                                    asset.unknow_serial_NO_product__c = true;
                                    asset.SerialNumber = dnInfo.SerialNumber;
                                    asset.SerialNumber_Origin__c = dnInfo.ProductCode+':'+dnInfo.SerialNumber;
                                }else if(dnInfo.TracingCode.substring(0,1) != '第' && dnInfo.SerialNumber.substring(0,1) == '第'){
                                    asset.unknow_serial_NO_product__c = true;
                                    asset.SerialNumber = dnInfo.SerialNumber;
                                    asset.SerialNumber_Origin__c = dnInfo.ProductCode+':'+dnInfo.SerialNumber;
                                    asset.TracingCode__c = dnInfo.TracingCode;
                                }else{
                                    asset.SerialNumber = dnInfo.SerialNumber;
                                    if(dnInfo.TracingCode.substring(0,1) != '第'){
                                        asset.TracingCode__c = dnInfo.TracingCode;
                                    }
                                   
                                }
                                // asset.SerialNumber = dnInfo.SerialNumber;
                                // asset.TracingCode__c = dnInfo.TracingCode;
                                // SerialNumber为空或者TracingCode为空处理 end
                                logstr += asset.Product_Serial_No__c + ' ';
                            } else {
                                
                                if (serialNumberIdMap.containsKey(dnInfo.ProductCode+':'+dnInfo.SerialNumber+'('+dnInfo.TracingCode+')')) {
                                
                                    //更新耗材
                                    asset =  serialNumberIdMap.get(dnInfo.ProductCode+':'+dnInfo.SerialNumber+'('+dnInfo.TracingCode+')');
                                } else {

                                    //新建保有设备
                                    if (productCode_NameMap.containsKey(dnInfo.ProductCode)) {

                                        asset.Name = productCode_NameMap.get(dnInfo.ProductCode);
                                    }
                                }

                                asset.Product_Serial_No__c = dnInfo.ProductCode+':'+dnInfo.SerialNumber+'('+dnInfo.TracingCode+')';
                                if (dnInfo.SorLMark == 'L'){
                                    asset.AssetMark__c = '耗材';
                                }
                                if(dnInfo.SorLMark == ''){
                                    asset.AssetMark__c = '';
                                }
                                //asset.SerialNumber = dnInfo.SerialNumber +'('+dnInfo.TracingCode+')';
                                // SerialNumber为空或者TracingCode为空处理 start
                                if(dnInfo.SerialNumber.substring(0,1) != '第' && dnInfo.TracingCode.substring(0,1) != '第'){
                                    asset.SerialNumber = dnInfo.SerialNumber +'('+dnInfo.TracingCode+')';
                                    asset.TracingCode__c = dnInfo.TracingCode;
                                }else{
                                    asset.unknow_serial_NO_product__c = true;
                                    asset.SerialNumber = dnInfo.SerialNumber + dnInfo.TracingCode;
                                    asset.SerialNumber_Origin__c = dnInfo.ProductCode+':'+dnInfo.SerialNumber +'('+dnInfo.TracingCode+')';
                                    if(dnInfo.SerialNumber.substring(0,1) == '第' && dnInfo.TracingCode.substring(0,1) != '第'){
                                        asset.TracingCode__c = dnInfo.TracingCode;
                                    }
                                }
                                // if(dnInfo.TracingCode.substring(0,1) == '第'){
                                //     //  SerialNumber不为空且TracingCode不为空
                                //     asset.unknow_serial_NO_product__c = true;
                                //     asset.SerialNumber = dnInfo.SerialNumber + dnInfo.TracingCode;
                                //     asset.SerialNumber_Origin__c = dnInfo.ProductCode+':'+dnInfo.SerialNumber +'('+dnInfo.TracingCode+')';
                                // }else{
                                //     asset.SerialNumber = dnInfo.SerialNumber +'('+dnInfo.TracingCode+')';
                                //     asset.TracingCode__c = dnInfo.TracingCode;
                                // }
                                // SerialNumber为空或者TracingCode为空处理 end
                                logstr += asset.Product_Serial_No__c + ' ';
                            }
                              
                            asset.Status = '未使用';
                            asset.IF_Information_From__c = true ;

                            //SAP传过来的，这是默认的值--Start 
                            asset.Hospital__c = hospital.Id;
                            asset.AccountId = client.Id;
                            asset.Department_Class__c = strategyDepartment.Id;
                            asset.Manage_type__c = '个体管理';
                            asset.RecordTypeId = System.label.access_1;
                            //SAP传过来的，这是默认的值--End
                            
                            asset.Order_No__c = info.OrderNumber;
                            asset.Sales_order_number__c = info.SalesOrderNumber;
                            asset.CompanyCodeOfEquipment_txt__c = info.CompanyCode;
                            asset.Loaner_approval_number__c = info.ApprovalNumber;
                            asset.Asset_loaner_category__c = info.Category;
                            asset.Loaner_asset_purpose__c = info.Purpose;
                            asset.Posting_Date__c = NFMUtil.parseStr2Date(info.DeliveryDate);
                            asset.ReceivingParty__c = info.SendTo;
                            asset.ContactPerson__c = info.ContactPerson;
                            asset.Remarks__c = info.Comment;
                            asset.Internal_Asset_number__c = dnInfo.AssetNumber;
                            asset.Asset_day__c = NFMUtil.parseStr2Date(dnInfo.AssetDay);
                            
                            // if(dnInfo.TracingCode.substring(0,5) != '第三方收货'){
                            //     asset.TracingCode__c = dnInfo.TracingCode;
                            // }
                            asset.Barcode__c = dnInfo.Barcode;
                            asset.Consumable_Guaranteen_end__c = NFMUtil.parseStr2Date(dnInfo.ValidTo);
                            asset.Internal_cost_center_cd__c = dnInfo.CostCenterCD;
                            //因"备品成本中心"的值修改会通过工作流修改"备品成本中心-文本"的值，故现在直接赋值给"备品中心成本"
                            asset.Internal_cost_center_text__c = dnInfo.CostCenterMemo;
                            asset.SphereOfBusinessCD__c = dnInfo.InchargeProvinceCD;
                            asset.Internal_demo_incharge_demo_province__c = dnInfo.InchargeProvince;
                            asset.Internal_asset_location_CD_txt__c = dnInfo.LocationCD;
                            asset.Internal_asset_location__c = dnInfo.LocationName;

                            asset.NMPA_Approbation_No__c = dnInfo.NMPA_NO;
                            asset.ProductionDate__c = NFMUtil.parseStr2Date(dnInfo.ProductionDate);
                            asset.ProduceCompany__c = dninfo.Provider;
                            //WLIG-C5UAB9 【委托】【SAP-SFDC接口】SAP接口数据传输、保有设备信息完善 liuyan start
                            asset.NMPA_ValidDate__c= dninfo.NMPA_ValidDate;                             //SFDA证书的产品有效期限
                            asset.NMPA_ValidFrom__c = NFMUtil.parseStr2Date(dnInfo.NMPA_ValidFrom); //SFDA证书开始日期 
                            asset.NMPA_ValidTo__c = NFMUtil.parseStr2Date(dnInfo.NMPA_ValidTo);     //SFDA证书结束日期                      
                            //end
                            assets.add(asset);
                        } else {
                            //ProcessType(处理方式)为2时，更新保有设备的Asset_day__c(资产化日期)
                            String assetNumberStr = info.CompanyCode + dnInfo.AssetNumber;
                            // System.debug('====='+Integer.valueOf(assetNumberStr+companyCodeAssetNumberMap));
                            if ( companyCodeAssetNumberMap.containsKey(assetNumberStr)) {

                                assetZB = companyCodeAssetNumberMap.get(assetNumberStr);
                                assetZB.Asset_day__c = NFMUtil.parseStr2Date(dnInfo.AssetDay);
                                logstr += dnInfo.SerialNumber +'('+info.CompanyCode + dnInfo.AssetNumber+')' + ' ';
                            } else {
                                iflog.ErrorLog__c += 'SerialNumber[ '+dnInfo.SerialNumber+' ] of Did no find match [ '+dnInfo.SerialNumber +'('+info.CompanyCode +'-'+dnInfo.AssetNumber+')'+' ] with Asset,This data is skipped .\n';
                                continue;
                            }
                            
                            updateAssetZB.add(assetZB);
                        }

                        // 【FY24大及巨大课题】北京新法规项目对应 DB202307428742 20230804 by lc Start
                        // 非集中备品跳过处理，北上广以外的都为非集中管理备品
                        if (dnInfo.LocationCD == '1021' || dnInfo.LocationCD == '2019' || dnInfo.LocationCD == '3017') {
                            if (productCode_Product2Map.containsKey(dnInfo.ProductCode)) {
                                Product2 productCodeTemp = productCode_Product2Map.get(dnInfo.ProductCode);

                                if (assetModelNo_Product2Map.containsKey(productCodeTemp.Asset_Model_No__c)) {
                                    Product2 prod = assetModelNo_Product2Map.get(productCodeTemp.Asset_Model_No__c);
                                    // 如果接口传输值和系统中已存在的不一致，则发邮件通知
                                    if (dnInfo.SHELF_LIFE != prod.Storage_Conditions__c || dnInfo.TRANS_CONDITION != prod.Transportation_Conditions__c) {
                                        // 301接口涉及到的邮件提醒，收件人信息如下。关于公共邮箱需北 上 广都发送；个人邮箱三地均需要
                                        // ocmassetbj_storage@olympus.com.cn、ocmassetsh_storage@olympus.com.cn、ocmassetgz_storage@olympus.com.cn
                                        // ying_liu@olympus.com.cn、xuan_li@olympus.com.cn
                                        // 邮件通知信息
                                        // 当前传输的产品Code、温湿度、产品型号及此型号下其他的产品Code，执行之间有温湿度信息不一致
                                        if (usedProductCode_Product2Map.isEmpty() || !usedProductCode_Product2Map.containsKey(dnInfo.ProductCode)) {
                                            // 备品中心邮件内容
                                            emailBody += setEmailBody(dnInfo.ProductCode, dnInfo.SHELF_LIFE, dnInfo.TRANS_CONDITION, productCodeTemp.Asset_Model_No__c, prod.ProductCode);
                                        }
                                    } else {
                                        // ProductCode重复的不需要重复判断
                                        if (usedProductCode_Product2Map.isEmpty() || !usedProductCode_Product2Map.containsKey(dnInfo.ProductCode)) {
                                            // 如果接口传输值一致，并且本设备对应的产品没有温湿度信息，则更新温湿度信息到产品
                                            if (String.isBlank(productCodeTemp.Storage_Conditions__c) && String.isBlank(productCodeTemp.Transportation_Conditions__c)) {
                                                Product2 updProd = new Product2();
                                                updProd.Id = productCodeTemp.Id;
                                                updProd.Storage_Conditions__c = dnInfo.SHELF_LIFE;
                                                updProd.Transportation_Conditions__c = dnInfo.TRANS_CONDITION;
                                                updProduct2List.add(updProd);
                                            } else {
                                                // 如果接口传输值一致，并且本设备对应的产品已有温湿度信息，则不更新
                                            }
                                        }
                                    }
                                } else {
                                    // 温湿度信息不存在，即更新
                                    if (usedProductCode_Product2Map.isEmpty() || !usedProductCode_Product2Map.containsKey(dnInfo.ProductCode)) {
                                        Product2 updProd = new Product2();
                                        updProd.Id = productCodeTemp.Id;
                                        updProd.Storage_Conditions__c = dnInfo.SHELF_LIFE;
                                        updProd.Transportation_Conditions__c = dnInfo.TRANS_CONDITION;
                                        updProduct2List.add(updProd);
                                    }
                                }

                                if (usedProductCode_Product2Map.isEmpty() || !usedProductCode_Product2Map.containsKey(dnInfo.ProductCode)) {
                                    usedProductCode_Product2Map.put(dnInfo.ProductCode, '1');
                                }
                            }
                        }
                        // 【FY24大及巨大课题】北京新法规项目对应 DB202307428742 20230804 by lc End
                    }
                }
                // 邮件提醒，保有设备更新条件，收货清单一览明细的收货状态等于‘待收货’的时候更新
                List<Asset> insertAsset = new List<Asset>();
                List<Asset> updateAsset = new List<Asset>();
                // List<Asset> updateAssetY = new List<Asset>();
                // List<Asset> updateAssetN = new List<Asset>();
                List<String> updateAssetY = new List<String>();
                List<Asset> updateAssetYL = new List<Asset>();
                
                List<String> updateAssetN = new List<String>();
                for(Asset asset :assets){
                    if(asset.Id == null){
                        insertAsset.add(asset);
                    }else{
                        updateAsset.add(asset);
                    }
                }
                // if (assets.size() > 0) {
                //     upsert assets;
                // }
                if (insertAsset.size() > 0) {
                    insert insertAsset;
                }
                if(updateAssetZB.size() > 0){
                    update updateAssetZB;
                }
                // assets  = [select Id,Product_Serial_No__c,Internal_Asset_number__c,Internal_Asset_number_key__c,CompanyCodeOfEquipment_txt__c from Asset where Internal_Asset_number_key__c In :InternalInsertAssetnumberkeyList];

                // 【FY24大及巨大课题】北京新法规项目对应 DB202307428742 20230804 by lc Start
                if(updProduct2List.size() > 0) {
                    Oly_TriggerHandler.bypass('Product2Handler');
                    update updProduct2List;
                    Oly_TriggerHandler.clearBypass('Product2Handler');
                }
                // 【FY24大及巨大课题】北京新法规项目对应 DB202307428742 20230804 by lc End
                
                assets  = [select Id,SerialNumber_Origin__c,Product_Serial_No__c,Internal_Asset_number__c,Internal_Asset_number_key__c,CompanyCodeOfEquipment_txt__c from Asset where Product_Serial_No__c In :serialNumberList];

                List<Asset> assetsThree  = [select Id,SerialNumber_Origin__c,Product_Serial_No__c,Internal_Asset_number__c,Internal_Asset_number_key__c,CompanyCodeOfEquipment_txt__c from Asset where SerialNumber_Origin__c In :serialNumberList];
                // 存放保有设备的外部id和保有设备
                
                for(Asset ass : assets){
                    // System.debug(Integer.valueOf(ass.CompanyCodeOfEquipment_txt__c+ass.Internal_Asset_number__c));
                    assReceivingNoteMap.put(ass.Product_Serial_No__c, ass.Id);
                    // assReceivingNoteMap.put(ass.SerialNumber_Origin__c, ass.Id);
                }
                for(Asset ass : assetsThree){
                    // System.debug(Integer.valueOf(ass.CompanyCodeOfEquipment_txt__c+ass.Internal_Asset_number__c));
                    // assReceivingNoteMap.put(ass.Product_Serial_No__c, ass.Id);
                    assReceivingNoteMap.put(ass.SerialNumber_Origin__c, ass.Id);
                }
                //创建"收货清单配套一览明细"
                List<ReceivingNoteDetail__c> receivingNoteDetailList = new List<ReceivingNoteDetail__c>();
                for (GeneralData info: genlDatas) {

                    
                    // ReceivingNoteDetail__c  receivingNoteDetail = new ReceivingNoteDetail__c();
                    for (DnInformation dnInfo : info.DnInformation) {

                        if (String.isBlank(dnInfo.ProductCode)) {
                            continue;
                        }

                        if (String.isBlank(dnInfo.SerialNumber)) {
                            continue;
                        }

                        if (info.ProcessType == '2' && String.isBlank(dnInfo.AssetNumber)) {
                            continue;
                        }

                        if (info.ProcessType == '2' && String.isBlank(dnInfo.AssetDay)) {
                            continue;
                        }

                        // if (info.ProcessType == '1') {
                        //     if (dnInfo.SorLMark != 'S' &&  dnInfo.SorLMark != 'L') {
                        //         continue;
                        //     }
                        // }

                        if (info.ProcessType == '1') {
                            if (receivingNoteIdMap.containsKey(info.SalesOrderNumber + info.DeliveryDate)) {
                                // sss += 'a';
                                    ReceivingNoteDetail__c receivingNoteDetail = new ReceivingNoteDetail__c();
                                    String idstr;
                                    if(dnInfo.SorLMark == 'S'){
                                        idstr = summaryReceivingNoteMap.get(dnInfo.ProductCode+':'+dnInfo.SerialNumber);
                                        Id drnid = (Id)idstr;
                                        if(receivingNoteDetailAllMap.containsKey(receivingNoteSummaryAllMap.get(dnInfo.ProductCode+':'+dnInfo.SerialNumber))){
                                            receivingNoteDetail.Id = receivingNoteDetailAllMap.get(receivingNoteSummaryAllMap.get(dnInfo.ProductCode+':'+dnInfo.SerialNumber));
                                        }else{
                                            receivingNoteDetail.ReceivingNoteSummary__c = drnid;
                                        }
                                        if(info.Category == '耗材'){
                                            receivingNoteDetail.Loaner_accsessary__c = 'TRUE';
                                            receivingNoteDetail.unknow_serial_NO_product__c = 'FALSE';
                                        }
                                        receivingNoteDetail.Product_Serial_No__c = dnInfo.ProductCode+':'+dnInfo.SerialNumber;
                                        receivingNoteDetail.RNDAssert__c = assReceivingNoteMap.get(dnInfo.ProductCode+':'+dnInfo.SerialNumber);
                                        // SerialNumber为空或者TracingCode为空处理 start
                                        if(dnInfo.SerialNumber.substring(0,1) != '第'){
                                            receivingNoteDetail.SerialNumber_Origin__c = dnInfo.SerialNumber;
                                        }else{
                                            receivingNoteDetail.unknow_serial_NO_product__c = 'TRUE';
                                        }
                                        // receivingNoteDetail.SerialNumber_Origin__c = dnInfo.SerialNumber;
                                        // SerialNumber为空或者TracingCode为空处理 end
                                    }else{
                                        idstr = summaryReceivingNoteMap.get(dnInfo.ProductCode+':'+dnInfo.SerialNumber+'('+dnInfo.TracingCode+')');
                                        Id drnid = (Id)idstr;
                                        if(receivingNoteDetailAllMap.containsKey(receivingNoteSummaryAllMap.get(dnInfo.ProductCode+':'+dnInfo.SerialNumber+'('+dnInfo.TracingCode+')'))){
                                            receivingNoteDetail.Id = receivingNoteDetailAllMap.get(receivingNoteSummaryAllMap.get(dnInfo.ProductCode+':'+dnInfo.SerialNumber+'('+dnInfo.TracingCode+')'));
                                        }else{
                                            receivingNoteDetail.ReceivingNoteSummary__c = drnid;
                                        }
                                        receivingNoteDetail.Product_Serial_No__c = dnInfo.ProductCode+':'+dnInfo.SerialNumber+'('+dnInfo.TracingCode+')';
                                        // Integer.valueOf(assReceivingNoteMap.get(dnInfo.ProductCode+':'+dnInfo.SerialNumber+'('+dnInfo.TracingCode+')')+'==='+assReceivingNoteMap+'===');
                                        receivingNoteDetail.RNDAssert__c = assReceivingNoteMap.get(dnInfo.ProductCode+':'+dnInfo.SerialNumber+'('+dnInfo.TracingCode+')');
                                        if(info.Category == '耗材'){
                                            receivingNoteDetail.Loaner_accsessary__c = 'TRUE';
                                            receivingNoteDetail.unknow_serial_NO_product__c = 'FALSE';
                                        }
                                        // SerialNumber为空或者TracingCode为空处理 start
                                        if(dnInfo.SerialNumber.substring(0,1) != '第' && dnInfo.TracingCode.substring(0,1) != '第'){
                                            receivingNoteDetail.SerialNumber_Origin__c = dnInfo.SerialNumber+'('+dnInfo.TracingCode+')';
                                        }else{
                                            receivingNoteDetail.unknow_serial_NO_product__c = 'TRUE';
                                            if(dnInfo.SerialNumber.substring(0,1) != '第' && dnInfo.TracingCode.substring(0,1) == '第'){
                                                receivingNoteDetail.SerialNumber_Origin__c = dnInfo.SerialNumber;
                                            }
                                        }
                                        // if(dnInfo.TracingCode.substring(0,1) == '第'){
                                        //     receivingNoteDetail.SerialNumber_Origin__c = dnInfo.SerialNumber;
                                        //     receivingNoteDetail.unknow_serial_NO_product__c = 'TRUE';
                                        // }else{
                                        //     receivingNoteDetail.SerialNumber_Origin__c = dnInfo.SerialNumber+'('+dnInfo.TracingCode+')';
                                        // }
                                        // SerialNumber为空或者TracingCode为空处理 end
                                    }

                                    // 为收货清单配套一览明细字段赋值
                                    String fixmodel = productCode_ModelNoMap.get(dnInfo.ProductCode);
                                    // fixid = fixtureSetMap.get(fixmodel);
                                    // proid = productCode_FixmodelMap.get(fixmodel);
                                    
                                    // 备品配套明细
                                    // if(fixtrueSetDetailMap.containsKey(fixtureSetMap.get(fixmodel)+':'+fixmodelNo_proIdMap.get(fixmodel))){
                                    //     receivingNoteDetail.Fixture_Set_Detail__c = fixtrueSetDetailMap.get(fixtureSetMap.get(fixmodel)+':'+fixmodelNo_proIdMap.get(fixmodel));
                                    // }
                                    // receivingNoteDetail.SerialNumberLink__c = dnInfo.SerialNumber;
                                    // receivingNoteDetail.Manage_type__c = '个体管理';
                                    // receivingNoteDetail.Asset_loaner_category__c = info.Category;
                                    receivingNoteDetail.passNo2__c = '01';
                                    receivingNoteDetail.passNo3__c = '001';
                                    // if(dnInfo.TracingCode.substring(0,5) == '第三方收货'){
                                    // if(info.Category == '耗材'){
                                        
                                        
                                    // }
                                    // receivingNoteDetail.PeriodOfUse__c = dnInfo.ValidTo;
                                    // receivingNoteDetail.AsreceivedCondition__c = '待数据确认';
                                    // receivingNoteDetail.Category__c = info.Category;
                                    receivingNoteDetailList.add(receivingNoteDetail);
                                } 
                        }

                        
                    }

                }
                // String bbb = JSON.serialize(receivingNoteDetailList);
                // System.debug(Integer.valueOf(bbb));
                // 邮件提醒，收货清单配套一览明细也是只创建不更新
                List<ReceivingNoteDetail__c> insertReceivingNoteDetail = new List<ReceivingNoteDetail__c>();
                // List<ReceivingNoteDetail__c> updateReceivingNoteDetail = new List<ReceivingNoteDetail__c>();
                List<String> updateReceivingNoteDetail = new List<String>();
                for(ReceivingNoteDetail__c receivingnotedet :receivingNoteDetailList){
                    if(receivingnotedet.Id == null ){
                        insertReceivingNoteDetail.add(receivingnotedet);
                    }else{
                        updateReceivingNoteDetail.add(receivingnotedet.Id);
                    }
                }
                // if(receivingNoteDetailList.size() > 0){
                //     upsert receivingNoteDetailList;
                // }
                if(insertReceivingNoteDetail.size() > 0){
                    insert insertReceivingNoteDetail;
                }


                // List<ReceivingNoteSummary__c> updateReceivingSummaryList = new List<ReceivingNoteSummary__c>();
                // for(String str : summaryReceivingNoteMap.keySet()){
                //     if(assReceivingNoteMap.containsKey(str)){
                //         ReceivingNoteSummary__c receivingNoteSum = new ReceivingNoteSummary__c();
                //         receivingNoteSum.id = summaryReceivingNoteMap.get(str);
                //         receivingNoteSum.RNSAssert__c = assReceivingNoteMap.get(str);
                //         updateReceivingSummaryList.add(receivingNoteSum);
                //     }
                // }
                // if(updateReceivingSummaryList.size() > 0 ){
                //     update updateReceivingSummaryList;
                // }

                // 保有设备更新
                Map<String,String> assetUpdateMap = new Map<String,String>(); 

                receivingNoteDetailList = [select id,RNDAssert__c,RND_Status__c,Product_Serial_No__c from ReceivingNoteDetail__c where Product_Serial_No__c In :serialNumberList];
                Map<String,String> receivingNoteDetailMap = new Map<String,String>();
                for(ReceivingNoteDetail__c rnd : receivingNoteDetailList){
                    receivingNoteDetailMap.put(rnd.Product_Serial_No__c, rnd.Id);
                    assetUpdateMap.put(rnd.RNDAssert__c, rnd.RND_Status__c);
                }
                List<ReceivingNoteSummary__c> updateReceivingSummaryList = new List<ReceivingNoteSummary__c>();
                for(String str : summaryReceivingNoteMap.keySet()){
                    if(receivingNoteDetailMap.containsKey(str)){
                        ReceivingNoteSummary__c receivingNoteSum = new ReceivingNoteSummary__c();
                        receivingNoteSum.id = summaryReceivingNoteMap.get(str);
                        receivingNoteSum.First_RND__c = receivingNoteDetailMap.get(str);
                        updateReceivingSummaryList.add(receivingNoteSum);
                    }
                }
                if(updateReceivingSummaryList.size() > 0 ){
                    update updateReceivingSummaryList;
                }

                // if(receivingNoteDetailList.size() > 0){
                //     upsert receivingNoteDetailList;
                // }
                if(receivingNoteDetailList.size() > 0 ){
                    update receivingNoteDetailList;
                }

                // 判断是否需要更新保有设备
                // 收货清单一览明细的收获状态等于‘待收货’的时候更新
                for(Asset asset :updateAsset){
                    if(assetUpdateMap.get(asset.Id) == '待数据确认'){
                        asset.Return_Flag__c = false;
                        asset.Delete_Flag__c = false;
                        updateAssetY.add(asset.Id);
                        updateAssetYL.add(asset);
                    }
                    if(assetUpdateMap.get(asset.Id) != '待数据确认'){
                        updateAssetN.add(asset.Id);
                    }
                }
                if(updateAssetY.size() > 0){
                    update updateAssetYL;
                }


                // 发送邮件
                if(updateReceivingNote.size() > 0 || updateRreceivingNoteSummary.size() > 0 || updateReceivingNoteDetail.size() > 0 || updateAssetY.size() > 0 || updateAssetN.size() > 0){
                    System.debug(updateReceivingNote+'updateReceivingNote======');
                    System.debug(updateRreceivingNoteSummary+'updateRreceivingNoteSummary======');
                    System.debug(updateReceivingNoteDetail+'updateReceivingNoteDetail======');
                    System.debug(updateAssetN+'updateAssetN======');
                    System.debug(updateAssetY+'updateAssetY======');
                    NFM301SendEmail.sendEmailOnNFM301(updateReceivingNote,updateRreceivingNoteSummary,updateReceivingNoteDetail, updateAssetY, updateAssetN);
                    // 邮件List集合
                    // Messaging.SingleEmailMessage[] theEmails = new Messaging.SingleEmailMessage[]{};
                    // String emailBody = '';
                    // // 收货清单
                    // if(updateReceivingNote.size() > 0){
                    //     emailBody += '收货清单：<br/>';
                    //     for(ReceivingNote__c recenote :updateReceivingNote){
                    //         emailBody += '&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspWaring!&nbsp'+recenote.Managment_Code__c+'已存在。不处理收货清单。<br/>';
                    //     }
                    // }
                    // // 收货清单配套一览
                    // if(updateRreceivingNoteSummary.size() > 0){
                    //     emailBody += '收货清单一览：<br/>';
                    //     for(ReceivingNoteSummary__c recenotesum :updateRreceivingNoteSummary){
                    //         emailBody += '&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspWaring!&nbsp'+recenotesum.Product_Serial_No__c+'已存在。不处理收货清单一览。<br/>';
                    //     }
                    // }
                    // // 收货清单配套一览明细
                    // if(updateReceivingNoteDetail.size() > 0){
                    //     emailBody += '收货清单一览明细：<br/>';
                    //     for(ReceivingNoteDetail__c recenotedet :updateReceivingNoteDetail){
                    //         emailBody += '&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspWaring!&nbsp'+recenotedet.Product_Serial_No__c+'已存在。不处理收货清单一览明细。<br/>';
                    //     }
                    // }
                    // // 保有设备
                    // if(updateAssetY.size() > 0 || updateAssetN.size() > 0){
                    //     emailBody += '保有设备：<br/>';
                    //     emailBody += '&nbsp&nbsp&nbsp&nbspProcessType(处理方式)=1：新建的时候，<br/>';
                    //     if(updateAssetY.size() > 0){
                    //         emailBody += '&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp收货清单一览明细的收货状态（RND_Status__c）=“待收货”的时候，更新<br/>';
                    //         for(Asset yasset :updateAssetY){
                    //             emailBody += '&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspWaring!&nbsp'+yasset.Product_Serial_No__c+'已存在“待收货”的设备。更新保有设备（ID）'+yasset.Id+'。<br/>';
                    //         }
                    //     }
                    //     if(updateAssetN.size() > 0){
                    //         emailBody += '&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp收货清单一览明细的收货状态（RND_Status__c）<>“待收货”的时候，不更新<br/>';
                    //         for(Asset nasset :updateAssetN){
                    //             emailBody += '&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspWaring!&nbsp'+nasset.Product_Serial_No__c+'已存在不是“待收货”的设备。不处理保有设备。<br/>';
                    //         }
                    //     }
                        
                    // }
                    // // 查询一下联系人的邮箱
                    // // List<String> contactEmail = new List<String>();
                    // // contactEmail = [];

                    // Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                    // // mail.setToAddresses(new List<string> {'1666755024@qq.com'});
                    // mail.setToAddresses(new List<string> {'1666755024@qq.com','jhtaizxt@163.com'});
                    // mail.setSenderDisplayName('NFM301更新邮件');
                    // mail.setSubject('NFM301更新邮件');
                    // mail.setHtmlBody(emailBody);
                    // theEmails.add(mail);
             
                    // Messaging.Email[] allMails = new Messaging.Email[]{};
                    // for(Integer j = 0; j < theEmails.size(); j++) {
                    //     allMails.add(theEmails.get(j));
                    // }
                    // Messaging.sendEmail(allMails);
                }

                // 【FY24大及巨大课题】北京新法规项目对应 DB202307428742 20230804 by lc Start
                // 接收温湿度信息不一致，则发送邮件通知备品中心
                if (!String.isBlank(emailBody)) {
                    NFM301SendEmail.sendTemperatureHumidityEmailOnNFM301(emailBody);
                }
                // 【FY24大及巨大课题】北京新法规项目对应 DB202307428742 20230804 by lc End
            }

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

        }catch (Exception ex) {

            // エラーが発生した場合
            Database.rollback(sp);
            System.debug(Logginglevel.ERROR, 'NFM301_' + rowData.MessageGroupNumber__c + ':' + ex.getMessage());
            System.debug(Logginglevel.ERROR, 'NFM301_' + rowData.MessageGroupNumber__c + ':' + ex.getStackTraceString());
            logstr += '\n' + ex.getMessage();
            iflog.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + iflog.ErrorLog__c;
            if (rowData.retry_cnt__c == null) rowData.retry_cnt__c = 0;
            if (rowData.retry_cnt__c < batch_retry_max_cnt) {

                rowData.retry_cnt__c++;
                LogAutoSendSchedule.assignOneMinute();
            }
            
            if (rowData.retry_cnt__c >= batch_retry_max_cnt) {

                rowData.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + rowData.ErrorLog__c + '错误次数已经超过自动收信设定的最大次数，请手动收信';
            }
        }

        update rowData;
        iflog.Log__c = logstr;
        if (iflog.Log__c.length() > 131072) {
            iflog.Log__c = iflog.Log__c.subString(0, 131065) + ' ...';
        }
        if (iflog.ErrorLog__c.length() > 32768) {
            iflog.ErrorLog__c = iflog.ErrorLog__c.subString(0, 32760) + ' ...';
        }
        update iflog;

    }

    public boolean dataCheck(GeneralData info,DnInformation dnInfo,Boolean flag,BatchIF_Log__c iflog) {
        return true;
    }

    /**
    * 生成温湿度不一致的邮件所需的Body
    * @param newProductCode   当前传输的产品Code
    * @param stConditions     当前传输的储存条件
    * @param trConditions     当前传输的运输条件
    * @param assetModelNo     当前传输的产品Code对应的产品型号
    * @param existProductCode 温湿度不一致同产品型号的产品Code
    * @return 邮件Body
    */
    public static String setEmailBody(String newProductCode, String stConditions, String trConditions, String assetModelNo, String existProductCode) {
        //return '当前传输的产品Code:' + newProductCode + '、储存条件:' + stConditions + '、运输条件:' + trConditions + '、产品型号:' + assetModelNo + '、温湿度不一致同产品型号的产品Code:' + existProductCode + ';';
        return '您好，产品' + newProductCode + '的储存温湿度信息与产品 ' + existProductCode + '不一致，还请了解并确认，谢谢。';
    }
}