@RestResource(urlMapping = '/NFM110/*')
global with sharing class NFM110Rest {
	public static boolean isRunning = false;
	//public transient static List<Id> orderoutIdList;
	public transient static List<Id> orderReturnIdList;
	// Integer batchsize = 200;  考量する必要がないと思います。
	global class ProductsDeliveryRest {
		public ProductsDelivery ProductsDelivery;
	}
	global class ProductsDelivery {
		public NFMUtil.Monitoring Monitoring;
		public GeneralData[] GeneralData;
	}
	global class GeneralData {
		public String SoNo;
		public String InquiryNo;
		public String ReturnMark;
		public String DeliveryDate;
		public String EndUserNo;
		public String DepartmentNo;
		public String DeliveryNote;
		// 电子签收单 2020/07/17 start
		public string supplier;
		public string supplierNo;
		public string shippingUnit;
		public string shippingAddress;
		public string contactName;
		public string contactNumber;
		public string totalNumber;
		public string transportMode;
		public string totalWeight;
		//电子签收单新建的字段，虽然不使用，但是SAP要求上线
		public string ACCMark;
		//public string GoodDetails;
		//public string weight;
		// 电子签收单 2020/07/17 end
		public DnInformation[] DnInformation;
	}
	global class DnInformation {
		public String OTCode;
		public String VALUE;
		public String SerialNoorLotNo;
		public String SorLMark;
		public String GuaranteePeriod;  // 期限——》年限 2019 0719
		// 多年保修价格 2019 0719
		public String GuaranteePrice;
		// 多年保修 start
		public string GuaranteeType;
		public string MaintenancePrice;
		// no discount
		public string ServicePrice;
		public String ProvistonPeriod;  // 计提年限
		// 多年保修 end

		public String TracingCode;
		public String ValidTo;
		public String Barcode;
		//CHAN-BC53ZG start
		public string NetWorth;
		//CHAN-BC53ZG end
		//CHAN-BGYE7C LHJ Start
		public string NetWorthNoProviston;  // 净值（不含计提）
		public string ProduceDate;  // 生产日期
		//CHAN-BGYE7C LHJ End
		// CHAN-BJX9EQ LHJ Start
		public String NMPA_NO;                      //产品注册证号/备案凭证编号
		public String Provider;                     //生产企业
		//CHAN-BJX9EQ LHJ End
		// 【委托】第三方发货DN明细合并 start
		public String QTY;
		// 【委托】第三方发货DN明细合并 end
		// 电子签收单 2020/08/21 start
		public String CaseNumber;
		// 电子签收单 2020/07/21 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, 'NFM110', 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":'  + gedata + '}';
		String jsonResponse = '{"status": "Success", "Message":""}';
		res.responseBody = blob.valueOf(jsonResponse);
		return;
	}

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

		// WLIG-CCT9UG 20220512 lt start
		Map<String, String> transferMap = new Map<String, String>();
        List<BatchIF_Transfer__c> transferList = [select Table__c,
                                  Column__c,
                                  External_value__c,
                                  Internal_value__c
                                  from BatchIF_Transfer__c
                                  where Dropped_Flag__c = false
                                          and (Table__c = 'NFM110')
                                          ];
        for (BatchIF_Transfer__c t : transferList) {
            transferMap.put(t.Column__c + t.External_value__c, t.Internal_value__c);
        }
		// WLIG-CCT9UG 20220512 lt end

		// 在进行NFM110处理时跳过消耗品明细2 arrived return 处理 HWAG-B3D9UV 2018/8/14 start
		StaticParameter.ConsumableAssetHanderTrigger = true;
		StaticParameter.EscapeConsumableOrderDetail2Trigger = true;
		Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
		//rentx 20210824 查询的时候多查了一个createdDate
		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, CreatedDate 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 = 'NFM110';
		iflog.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
		iflog.Log__c = logstr;
		iflog.ErrorLog__c = '';
		insert iflog;
		String rowDataStr = NFMUtil.getRowDataStr(rowData);
		List<GeneralData> generalDataList = (List<GeneralData>) JSON.deserialize(rowDataStr, List<GeneralData>.class);
		if (generalDataList == null || generalDataList.size() == 0) {
			return;
		}

		Account ocm = [select Id from Account where AgentCode_Ext__c = '9999900'];
		// HHOA-AGN2EH start
		Account olympus = [select Id from Account where AgentCode_Ext__c = '9999999'];
		Account olympus_return = [select Id, ParentId from Account where AgentCode_Ext__c = '9999901'];
		// HHOA-AGN2EH end
		isRunning = true;
		//orderoutIdList = new List<Id>();
		orderReturnIdList = 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
			//本次修改只针对于保有设备 之前使用年月日去插入时 会出现 同一天多批日志里有同一个设备 导致更新失败  现解决方案为使用日志创建时间并精确到分
			Datetime nowTime = rowData.CreatedDate;
			String oyear = String.valueOf(nowTime.year());
			String omonth = String.valueOf(nowTime.month());
			String oday = String.valueOf(nowTime.day());
			String ohour = String.valueOf(nowTime.hour());
			String ominute = String.valueOf(nowTime.minute());
			String odatestr = String.valueOf(oyear+omonth+oday+ohour+ominute);
			//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> ();

			list<QIS_Report__c> allUpdateQISList = new list<QIS_Report__c>();
			// SWAG-BDV589 end

			for (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 (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);
					}
				}
			}
			// 虚拟维修合同  start
			// 虚拟维修合同
			Map <string, Maintenance_Contract__c> v_MCMap = new  map <string, Maintenance_Contract__c>();
			// 临时存储新规的虚拟维修合同，操作后放在v_MCMap
			Map <string, Maintenance_Contract__c> v_MCtempMap = new  map <string, Maintenance_Contract__c>();
			// 已经存在的虚拟维修合同保有设备, 退货用，包含用户变更的退货数据
			Map <string, List<Maintenance_Contract_Asset__c> > v_MCdetMap = new  map <string, List<Maintenance_Contract_Asset__c> >();
			//  需要插入的虚拟维修合同保有设备
			List<Maintenance_Contract_Asset__c> insertv_MCdetlList = new List<Maintenance_Contract_Asset__c>();
			//  退货的保有设备对应的维修合同保有设备
			List<Maintenance_Contract_Asset__c> returnv_MCdetlList = new List<Maintenance_Contract_Asset__c>();
			List<Maintenance_Contract__c> v_MCList =
			[select id, Opportunity__c, Opportunity__r.Opportunity_No__c
			 from Maintenance_Contract__c where
			 Opportunity__r.Opportunity_No__c IN :inquiryNoList];
			for (Maintenance_Contract__c vm : v_MCList) {
				v_MCMap.put(vm.Opportunity__r.Opportunity_No__c, vm);
			}
			// 维修合同保有设备获取，找到所有维修合同保有设备，包括已经用户变更的数据
			List<Maintenance_Contract_Asset__c> v_MCdetList =
			[select id, Maintenance_Contract__c, Maintenance_Contract__r.Opportunity__r.Opportunity_No__c,
			 Asset__c, Asset__r.SerialNumber, Asset__r.MDM_Model_No__c, endDateGurantee_changeAcc__c
			 from Maintenance_Contract_Asset__c where
			 Asset__r.SerialNumber in :productSerialNoList
			 and Asset__r.IsCompetitorProduct = false
			                                    and Asset__r.Information_From__c <> '失单'
			                                    and Return_Flag__c = false];
			for (Maintenance_Contract_Asset__c vmd : v_MCdetList) {
				List<Maintenance_Contract_Asset__c> mcaTemp = new List<Maintenance_Contract_Asset__c>();
				if (v_MCdetMap.containsKey(vmd.Asset__r.MDM_Model_No__c + vmd.Asset__r.SerialNumber)) {
					mcaTemp =
						v_MCdetMap.get(vmd.Asset__r.MDM_Model_No__c + vmd.Asset__r.SerialNumber).clone();
					mcaTemp.add(vmd);
					v_MCdetMap.put(vmd.Asset__r.MDM_Model_No__c + vmd.Asset__r.SerialNumber, mcaTemp);
				} else {
					mcaTemp.add(vmd);
					v_MCdetMap.put(vmd.Asset__r.MDM_Model_No__c + vmd.Asset__r.SerialNumber, mcaTemp);
				}
				//v_MCdetMap.put(vmd.Asset__r.MDM_Model_No__c + vmd.Asset__r.SerialNumber, vmd);
			}
			// 虚拟维修合同  end

			// SWAG-BDV589 start
			List<QIS_Report__c> ALLQISList =
			[select id, ReplaceDeliveryDate__c, OppNumberAndProductCode_Ext__c
			 from QIS_Report__c
			 where OppNumberAndProductCode_Ext__c in: OppNumberAndProductCodeList
			 and QIS_Status__c != '取消'
			 and ReplaceDeliveryDate__c = null
			                              order by OppNumberAndProductCode_Ext__c, createddate];
			for (QIS_Report__c tempQIS : ALLQISList) {
				list<QIS_Report__c> tempQISList = new list<QIS_Report__c>();
				if (tempQIS.OppNumberAndProductCode_Ext__c != null
				    && OppNumberAndProductCodetoQISMap.containskey(tempQIS.OppNumberAndProductCode_Ext__c)) {
					tempQISList = OppNumberAndProductCodetoQISMap.get(tempQIS.OppNumberAndProductCode_Ext__c);
				}
				tempQISList.add(tempQIS);
				OppNumberAndProductCodetoQISMap.put(tempQIS.OppNumberAndProductCode_Ext__c, tempQISList);
			}
			// SWAG-BDV589 end



			// 事前に（マスタ）データを取得
			// 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);
			}
			//经销商合同
			List<Account> agencyContractList = [select Id, Management_Code__c, Department_Class__c, Hospital__c,
			                                    ParentId, Parent.Name, RecordType.DeveloperName, Sales_Section__c
			                                    from Account
			                                    where Management_Code__c in :managementCodeList
			                                    and RecordType.DeveloperName = 'AgencyContract'];
			Map<String, Account> agencyContractMap = new Map<String, Account>();
			//经销商合同申请销售课
			Map<String, String> conSalesSectionMap = new Map<String, String>();
			List<String> agencyNameList = new List<String>();
			List<String> agencyIds = new List<String>();
			for (Account acc : agencyContractList) {
				agencyContractMap.put(acc.Management_Code__c, acc);
				agencyNameList.add(acc.Parent.Name);
				//conSalesSectionMap.put(acc.Management_Code__c, acc.ParentId + acc.Sales_Section__c);
				//agencyIds.add(acc.ParentId);
			}
			//接收订单类型判断是否不生成追溯系统相关内容  精琢技术 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);
			}
			//接收订单类型判断是否不生成追溯系统相关内容  精琢技术 thh 2021-10-11 end
			Map<String, String> boMap = new Map<String, String>();
			for (Statu_Achievements__c bo : boList) {
				boMap.put(bo.Name, bo.Id);
			}

			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
			                                   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<Asset> astList = [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,
			                       Extend_Gurantee_DateTo__c, guarantee_period__c, Proviston_period__c,RecordType.DeveloperName 
			                       from Asset
			                       where SerialNumber in :productSerialNoList
			                       and IsCompetitorProduct = false
			                                                 and Information_From__c <> '失单'];
			// HHOA-AGN2EH end
			Map<String, Asset> astsMap = new Map<String, Asset>();
			Map<String, Asset> consumableastsMap = new Map<String, Asset>();
			Map<String, Integer> astcheckMap = new Map<String, Integer>();
			for (Asset ast : astList) {
				// HHOA-AGN2EH start
				//astsMap.put(ast.Product_Serial_No__c, ast);
				//if((Product2.Dealer_Object__c || Product2.Dealer_special_Object__c) && String.isNotBlank(ass.TracingCode__c)){
				//    consumableastsMap.put(ast.MDM_Model_No__c + ast.SerialNumber + '(' + ass.TracingCode__c + ')', ast);
				//}else{
				astsMap.put(ast.MDM_Model_No__c + ast.SerialNumber, ast);
				//}
				if (astcheckMap.containsKey(ast.MDM_Model_No__c + ast.SerialNumber) == false) {
					astcheckMap.put(ast.MDM_Model_No__c + ast.SerialNumber, 1);
				} else {
					astcheckMap.put(ast.MDM_Model_No__c + ast.SerialNumber, astcheckMap.get(ast.MDM_Model_No__c + ast.SerialNumber) + 1);
				}
				// HHOA-AGN2EH end
			}
			List<Consumable_order__c> orderList = [Select Id, RecordType.Developername, Name, OwnerId From Consumable_order__c Where Name IN :inquiryNoList];
			Map<String, Consumable_order__c> orderMap = new Map<String, Consumable_order__c>();
			for (Consumable_order__c ord : orderList) {
				orderMap.put(ord.Name, ord);
			}
			//SFDCの询价产品の単価から取得
			List<Consumable_orderdetails__c> orderdet1List = [Select Id, Consumable_product__c, Intra_Trade_List_RMB__c From Consumable_orderdetails__c Where Consumable_order__r.Name IN :inquiryNoList];
			Map<String, Decimal> orderdet1priceMap = new Map<String, Decimal>();
			for (Consumable_orderdetails__c orddet : orderdet1List) {
				orderdet1priceMap.put(orddet.Consumable_product__c, orddet.Intra_Trade_List_RMB__c);
			}
			// HHOA-BLC8S6 update by vivek 2020-02-13 start
			// List<Opportunity> oppList = [Select Id, Purchase_Type__c, Opportunity_No__c, Sales_Root__c, SAP_Province__c, Trade__c, Agency1__c, Opportunity_Category__c From Opportunity Where Opportunity_No__c IN :inquiryNoList];
			// HHOA-BLC8S6 update by vivek 2020-02-13 start
			// update by gzw 2020-04-27 start
			// add Agency1__r.Name
			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__r.OCM_man_province_txt__c, Opportunity_Category__c
										//  ,SAP_Province__c //20230323 lt DB202303088261 两票制 add
			                             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
			}
			// 自动修改最终用户 update by vivek start
			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);
			}
			// 自动修改最终用户 update by vivek end
			//直接到货产品barcode Map做成
			////////////  追溯sql优化 20200514 start /////////////
			// 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
			//                                    from Consumable_order_details2__c
			//                                    where Consumable_order_minor__r.Name IN :inquiryNoList
			//                                    and Dealer_Arrive__c = true
			//                                            and Direct_Arrive_Product__c = true];
			// Map<String, Consumable_order_details2__c> orderDetailDeliveryMap = new Map<String, Consumable_order_details2__c>();
			// for (Consumable_order_details2__c ordD : orderDetails) {
			//     if (String.isBlank(ordD.TracingCode__c) == false) {
			//         orderDetailDeliveryMap.put(ordD.Consumable_order_minor__r.Name + ':' + ordD.TracingCode__c, ordD);
			//     }
			// }
			////////////  追溯sql优化 end /////////////
			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
			                                                   from Consumable_order_details2__c
			                                                   where TracingCode__c IN :tracingCodeList
			                                                   and Dealer_Arrive__c = true
			                                                                          and Direct_Arrive_Product__c = true];
			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.TracingCode__c, ordD);
				}
			}

			////////////  追溯sql优化 20200514 start /////////////
			List<Consumable_order_details2__c> detailsSendAgain = [Select Id,
			                                                       Consumable_order_minor__r.Name,
			                                                       Bar_Code__c,
			                                                       Deliver_date__c,
			                                                       Asset_Model_No__c,
			                                                       Dealer_Arrive__c,
			                                                       Direct_Arrive_Product__c,
			                                                       TracingCode__c
			                                                       from Consumable_order_details2__c
			                                                       where Consumable_order_minor__r.Name IN :inquiryNoList
			];
			// 经销商直接入库数据
			Map<String, Consumable_order_details2__c> orderDetailDeliveryMap = new Map<String, Consumable_order_details2__c>();
			// SAP 从发数据
			Map<String, Consumable_order_details2__c> detailsSendAgainMap = new Map<String, Consumable_order_details2__c>();
			for (Consumable_order_details2__c ordD : detailsSendAgain) {
				if (String.isBlank(ordD.Bar_Code__c) == false) {
					if (ordD.Dealer_Arrive__c && ordD.Direct_Arrive_Product__c) {
						orderDetailDeliveryMap.put(ordD.Consumable_order_minor__r.Name + ':' + ordD.TracingCode__c, ordD);
					}else if (!ordD.Direct_Arrive_Product__c) {
						detailsSendAgainMap.put(ordD.Consumable_order_minor__r.Name + ':' + ordD.Bar_Code__c, ordD);
					}
				}
			}

			////////////  追溯sql优化 end /////////////

			//NFM110发货产品barcode Map做成
			detailsSendAgain = [Select Id,
			                    Consumable_order_minor__r.Name,
			                    Bar_Code__c,
			                    Deliver_date__c,
			                    Asset_Model_No__c
			                    from Consumable_order_details2__c
			                    where (Dealer_Info_text__c IN :agencyNameList
			                           and Bar_Code__c in : barCodeList
			                           and Direct_Arrive_Product__c = false)
			                    or (Bar_Code__c in : barCodeList
			                        and Consumable_order_minor__c = null
			                                                        and Dealer_Saled__c = true)];
			Map<String, Consumable_order_details2__c> detailsSendAgainNoMap = new Map<String, Consumable_order_details2__c>();
			for (Consumable_order_details2__c ordD : detailsSendAgain) {
				if (String.isBlank(ordD.Bar_Code__c) == false) {
					detailsSendAgainNoMap.put(ordD.Bar_Code__c, ordD);
				}
			}
			// 更新対応配列をセット
			astList = new List<Asset>();
			Map<String, Asset> astUpdateMap = new Map<String, Asset>();
			List<Asset> astDelList = new List<Asset>();
			Map<String, Asset> astDelMap = new Map<String, Asset>();
			// 发货订单最新发货日等更新
			Map<String, Consumable_order__c> oUpdateMap = new Map<String, Consumable_order__c>();
			// 直销耗材，出库单新建
			Map<String, Consumable_order__c> orderOutMap = new Map<String, Consumable_order__c>();
			// 直销耗材，返品单新建
			//Map<String, Consumable_order__c> orderReturnMap = new Map<String, Consumable_order__c>();

			Map<String, Consumable_order_details2__c> odUpsertMap = new Map<String, Consumable_order_details2__c>();
			Map<String, Consumable_order_details2__c> odDetailUpsertMap = new Map<String, Consumable_order_details2__c>();
			// 直销耗材消耗品明细2
			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 (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 (DnInformation dnInfo : infoH.DnInformation) {
					dnInfo.SerialNoorLotNo = checkSerialNoorLotNo(dnInfo.SerialNoorLotNo);
					// CHAN-BBLAAP start
					Product2 prd = prdsMap.get(dnInfo.OTCode);
					Asset ast;
					if (dnInfo.SorLMark == 'S') {
						ast = astsMap.get(prd.MDM_Model_No__c + dnInfo.SerialNoorLotNo);
					} else {
						ast = astsMap.get(prd.MDM_Model_No__c + dnInfo.SerialNoorLotNo + '(' + dnInfo.TracingCode + ')');
					}
					//2021-10-14  zxk  精琢科技  start  SWAG-C7QARS  保有设备的记录类型是备品的时候跳过不进行处理
                    if (ast != null && String.isNotBlank(ast.id) && 'Shipment'.equals(ast.RecordType.DeveloperName)) {
                        iflog.ErrorLog__c += 'Warning! Asset[' + ast.Product_Serial_No__c + '] RecordType [' + ast.RecordType.DeveloperName + '] This asset is skipped.\n';
                        continue;
                    }
                    //2021-10-14  zxk  精琢科技  SWAG-C7QARS  end
					//  CHAN-BBLAAP 插入保有设备明细时插入对应DN start
					boolean tempReturnFlg = infoH.ReturnMark == '1' ? true : false;

					//注释by rentx 20210727 start
					// string tempSerialNumber = '';
					// if (dnInfo.SorLMark == 'S') {
					//     tempSerialNumber = dnInfo.SerialNoorLotNo;
					// } else {
					//     tempSerialNumber  = dnInfo.SerialNoorLotNo + '(' + dnInfo.TracingCode + ')';
					// }

					// if (String.isBlank(dnInfo.SorLMark) ||
					//         tempSerialNumber.equals('.') ) {
					//     continue;
					// }
					//注释by rentx 20210727 end
					/*if (orderMap.containsKey(InquiryNoStr) == false &&
					        //&& agencyContractMap.size() < 0
					        oppMap.containsKey(InquiryNoStr) == true
					        && oppMap.get(InquiryNoStr).Purchase_Type__c == 'ET24時間販売'
					        && dnInfo.SorLMark == 'S'){
					    // HHOA-AGN2EH start
					    //iflog.Log__c += 'SoNo[' + infoH.SoNo + '] DeliveryNote[' + infoH.DeliveryNote + '] Warning! [' + infoH.InquiryNo + ':Purchase_Type__c] is not ET24\n';
					    // HHOA-AGN2EH end
					    continue;
					   }*/
					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;
					}

					if (orderMap.containsKey(InquiryNoStr) == false &&
					    prd == null) {
						iflog.ErrorLog__c += 'Error! SoNo[' + infoH.SoNo + '] DeliveryNote[' + infoH.DeliveryNote + '] [' + dnInfo.SerialNoorLotNo + ']Product[' + dnInfo.OTCode + ']NotExist. 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 start
					if (astcheckMap.containsKey(prd.MDM_Model_No__c + dnInfo.SerialNoorLotNo) == true && astcheckMap.get(prd.MDM_Model_No__c + dnInfo.SerialNoorLotNo) > 1) {
						iflog.ErrorLog__c += 'Error! SoNo[' + infoH.SoNo + '] DeliveryNote[' + infoH.DeliveryNote + '] Asset[' + dnInfo.OTCode + ':' + dnInfo.SerialNoorLotNo + ']Exist more than one. This asset is skipped.\n';
						continue;
					}

					Boolean hasAst = true;
					// HHOA-AGN2EH end
					if (ast == null) {
						// 存在しないのに、delete 受信の場合
						if (infoH.ReturnMark == '1' && dnInfo.SorLMark != 'L') {
							iflog.ErrorLog__c += 'Warning! SoNo[' + infoH.SoNo + '] DeliveryNote[' + infoH.DeliveryNote + '] Delete Asset[' + dnInfo.OTCode + ':' + dnInfo.SerialNoorLotNo + ']NotExist. This asset is skipped.\n';
							continue;
						} else if (infoH.ReturnMark == '1' && dnInfo.SorLMark == 'L'
						           && oppMap.get(InquiryNoStr).Sales_Root__c == 'OCM直接販売'
						           && accsMap.get(infoH.EndUserNo) != null && String.isNotBlank( dnInfo.Barcode)) {
							Product2__c prdMap = prdSearchMap.get(dnInfo.OTCode);
							//订单类型为ZM16时不生成追溯系统相关内容  精琢技术 thh 2021-10-11 start
							if (!prdMap.Pro2_Dealer_Object__c && !prdMap.Pro2_Dealer_ENG__c && NameorderType.get(infoH.SoNo) == 'ZM16') {
								continue;
							}
							//订单类型为ZM16时不生成追溯系统相关内容  精琢技术 thh 2021-10-11 end
							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.Dealer_Returned_Label;
								autoOrder.Opportunity__c = oppMap.get(InquiryNoStr).Id;
								autoOrder.Dealer_Info__c = addressNameApiMap.get(oppMap.get(InquiryNoStr).SAP_Province__c);
								autoOrder.Order_ForHospital__c = accsMap.get(infoH.EndUserNo).Id;
								autoOrder.Order_type__c = '返品';
								autoOrder.ReturnGs_Uploader_ID__c = System.Label.User_OlympusSystem;
								autoOrder.ReturnGs_Upload_Date__c = NFMUtil.parseStr2Date(infoH.DeliveryDate);
								autoOrder.Order_status__c         = '批准';
								orderOutMap.put(InquiryNoStr, autoOrder);
							}
							Consumable_order_details2__c rac = detailsSendAgainNoMap.get(dnInfo.Barcode);
							if (rac == null) {
								rac = new Consumable_order_details2__c();
								if (String.isNotBlank(dnInfo.VALUE)) {
									rac.Intra_Trade_List_RMB__c = Decimal.valueOf(dnInfo.VALUE);
								} else if (orderdet1priceMap.containsKey(prdSearch.Id)) {
									rac.Intra_Trade_List_RMB__c = orderdet1priceMap.get(prdSearch.Id);
								} else {
									rac.Intra_Trade_List_RMB__c   = prdSearch.Intra_Trade_List_RMB__c;
								}

								// update by gzw 2020-04-27 start
								if (oppMap.containsKey(InquiryNoStr)) {
									rac.Agencyinfo_fromSAP__c     = oppMap.get(InquiryNoStr).Agency1__r.Name;
								}
								// update by gzw 2020-04-27 end

								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);
								rac.Arrive_date__c           = NFMUtil.parseStr2Date(infoH.DeliveryDate);
								rac.Used_date__c           = NFMUtil.parseStr2Date(infoH.DeliveryDate);
								// 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           = addressNameApiMap.get(oppMap.get(InquiryNoStr).SAP_Province__c);
								rac.Dealer_Info_IF__c         = addressNameApiMap.get(oppMap.get(InquiryNoStr).SAP_Province__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.Guarantee_period_for_products__c = NFMUtil.parseStr2Date(dnInfo.GuaranteePeriod);
								rac.TracingCode__c            = dnInfo.TracingCode;
								// HHOA-BFF53G IF来源
								rac.IF_Information_From__c    = true;
								//生成追溯明细时 记录SAP合同号 by rentx 2020-12-14
								if (String.isNotEmpty(InquiryNoStr2)) {
									rac.ContractNo_text__c  = InquiryNoStr2;
								}
								//生成追溯明细时 记录SAP合同号
								// 【委托】ET消耗品系统自动生成出库数量大于当月发货数量 精琢技术 tcm start 已测 a001m000002eBmV
								if (String.isNotEmpty(InquiryNoStr)) {
									rac.Opportunity_No__c = InquiryNoStr;
								}
								// 【委托】ET消耗品系统自动生成出库数量大于当月发货数量 精琢技术 tcm end

							}
							cod2List.add(rac);
							odDSUpsertMap.put(InquiryNoStr + ':' + dnInfo.Barcode, rac);
							odUpsertIdxMap.put(InquiryNoStr + ':' + dnInfo.Barcode, odDSUpsertMap.size());

							//odDSUpsertIdxMap.put(accsMap.get(infoH.EndUserNo).Id + ':' + oppMap.get(InquiryNoStr).Id + '', cod2List);
							// HHOA-BF25ZM 返品时不更新名称
							if (!detailsSendAgainNoMap.containsKey(dnInfo.Barcode)) {
								rac.Name                      = InquiryNoStr + ':' + ('000' + odUpsertIdxMap.get(InquiryNoStr + ':' + dnInfo.Barcode)).right(4);
							}
							rac.RecordTypeId              = System.Label.RT_ConOrderDetail2_Return;              // TODO 本番IDにする label
							rac.Box_Piece__c              = '盒';
							rac.Return_date__c            = NFMUtil.parseStr2Date(infoH.DeliveryDate);
							rac.Return_reason__c          = '医院退货';
							//全部System
							rac.OwnerId                   = System.Label.User_OlympusSystem;
							// HHOA-BF25ZM 同一个messageNo多个DN对应
							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());
							}
							continue;
						}
						ast = new Asset();
						hasAst = false;
					} else {
						if (infoH.ReturnMark == '1') {
							//System.debug('耗材退货+++++ ');
							// 物理削除用
							if (astDelMap.get(ast.Product_Serial_No__c) == null) {
								// HHOA-AGN2EH start
								Asset delAst = new Asset(Id = ast.Id);
								delAst.Product2Id = prdsMap.get(dnInfo.OTCode).Id;
								// HHOA-AGN2EH end
								delAst.SerialNumber = ast.SerialNumber;

								// CHAN-BGYE7C start
								delAst.ProductionDate__c   = NFMUtil.parseStr2Date(dnInfo.ProduceDate);
								// 20210108 gzw add 虚拟合同号追加 start
								// delAst.NetWorthNoProviston__c           = String.isBlank(dnInfo.NetWorthNoProviston) ?
								// 0 : Decimal.valueOf(dnInfo.NetWorthNoProviston.trim());
								delAst.NetWorthNoProviston__c           = 0;
								if (String.isNotBlank(dnInfo.NetWorthNoProviston)) {
									Decimal netProviston = Decimal.valueOf(dnInfo.NetWorthNoProviston.trim());
									delAst.NetWorthNoProviston__c   = oppMap.get(InquiryNoStr).Trade__c == '内貿'?
									                                  netProviston : netProviston * Decimal.valueOf(Label.Account_Exc);
								}
								// 20210108 gzw add 虚拟合同号追加 end

								//20230323 lt DB202303088261 两票制 Start
								// if(oppMap.get(InquiryNoStr).SAP_Province__c == 'OSH-安徽省'){
								// 	delAst.OSHFLG__c = true ;
								// }
								//20230323 lt DB202303088261 两票制 End

								// CHAN-BGYE7C end
								// CHAN-BJX9EQ Start
								delAst.NMPA_Approbation_No__c           = dnInfo.NMPA_NO;
								delAst.ProduceCompany__c                = dninfo.Provider;
								// CHAN-BJX9EQ End

								// 多年保修退货
								//System.debug('多年保修退货' + InquiryNoStr + ast.SerialNumber);
								//System.debug('多年保修退货v_MCdetMap' + v_MCdetMap);
								if (v_MCdetMap.containsKey(prd.MDM_Model_No__c + ast.SerialNumber)) {
									//System.debug('多年保修退货');
									List<Maintenance_Contract_Asset__c> v_MCdettempList = v_MCdetMap.get(prd.MDM_Model_No__c + ast.SerialNumber);
									for (Maintenance_Contract_Asset__c v_MCdet : v_MCdettempList ) {
										v_MCdet.V_MC_Name__c = InquiryNoStr;
										v_MCdet.Return_Flag__c = true;
										v_MCdet.Asset_SerialNumber__c = ast.SerialNumber;
										if (v_MCdet.endDateGurantee_changeAcc__c == null) {
											v_MCdet.endDateGurantee_changeAcc__c = NFMUtil.parseStr2Date(infoH.DeliveryDate);
										}
										v_MCdet.guarantee_period__c = ast.guarantee_period__c;
										v_MCdet.Extend_Gurantee_DateTo__c = ast.Extend_Gurantee_DateTo__c;
										v_MCdet.Proviston_period__c = ast.Proviston_period__c;
										// if (String.isNotBlank(dnInfo.GuaranteePrice)) {
										//     v_MCdet.Asset_GuaranteePrice__c = Decimal.valueOf(dnInfo.GuaranteePrice);
										// }
										returnv_MCdetlList.add(v_MCdet);
									}
								}
								astDelList.add(delAst);
								astDelMap.put(ast.Product_Serial_No__c, ast);

								if (dnInfo.SorLMark == 'L'
								    && oppMap.get(InquiryNoStr).Sales_Root__c == 'OCM直接販売'
								    && accsMap.get(infoH.EndUserNo) != null && String.isNotBlank( dnInfo.Barcode)) {
									Product2__c prdMap = prdSearchMap.get(dnInfo.OTCode);
									//订单类型为ZM16时不生成追溯系统相关内容  精琢技术 thh 2021-10-11 start
									if (!prdMap.Pro2_Dealer_Object__c && !prdMap.Pro2_Dealer_ENG__c && NameorderType.get(infoH.SoNo) == 'ZM16') {
										continue;
									}
									//订单类型为ZM16时不生成追溯系统相关内容  精琢技术 thh 2021-10-11 end
									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.Dealer_Returned_Label;
										autoOrder.Opportunity__c = oppMap.get(InquiryNoStr).Id;
										autoOrder.Dealer_Info__c = addressNameApiMap.get(oppMap.get(InquiryNoStr).SAP_Province__c);
										autoOrder.Order_ForHospital__c = accsMap.get(infoH.EndUserNo).Id;
										autoOrder.Order_type__c = '返品';
										autoOrder.ReturnGs_Uploader_ID__c = System.Label.User_OlympusSystem;
										autoOrder.ReturnGs_Upload_Date__c = NFMUtil.parseStr2Date(infoH.DeliveryDate);
										autoOrder.Order_status__c         = '批准';
										orderOutMap.put(InquiryNoStr, autoOrder);
									}

									Consumable_order_details2__c rac = detailsSendAgainNoMap.get(dnInfo.Barcode);
									if (rac == null) {
										rac = new Consumable_order_details2__c();
										//cod2List.add(rac);
										//odDSUpsertMap.put(InquiryNoStr + ':' + dnInfo.Barcode, rac);
										//odUpsertIdxMap.put(InquiryNoStr + ':' + dnInfo.Barcode, odDSUpsertMap.size());
										//odDSUpsertIdxMap.put(accsMap.get(infoH.EndUserNo).Id + ':' + oppMap.get(InquiryNoStr).Id + '', cod2List);
										//rac.Name                      = InquiryNoStr + ':' + ('000'+ odUpsertIdxMap.get(InquiryNoStr + ':' + dnInfo.Barcode)).right(4);
										if (String.isNotBlank(dnInfo.VALUE)) {
											rac.Intra_Trade_List_RMB__c = Decimal.valueOf(dnInfo.VALUE);
										} else if (orderdet1priceMap.containsKey(prdSearch.Id)) {
											rac.Intra_Trade_List_RMB__c = orderdet1priceMap.get(prdSearch.Id);
										} else {
											rac.Intra_Trade_List_RMB__c   = prdSearch.Intra_Trade_List_RMB__c;
										}

										// update by gzw 2020-04-27 start
										if (oppMap.containsKey(InquiryNoStr)) {
											rac.Agencyinfo_fromSAP__c     = oppMap.get(InquiryNoStr).Agency1__r.Name;
										}
										// update by gzw 2020-04-27 end


										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);
										rac.Arrive_date__c           = NFMUtil.parseStr2Date(infoH.DeliveryDate);
										rac.Used_date__c           = NFMUtil.parseStr2Date(infoH.DeliveryDate);
										// 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           = addressNameApiMap.get(oppMap.get(InquiryNoStr).SAP_Province__c);
										rac.Dealer_Info_IF__c         = addressNameApiMap.get(oppMap.get(InquiryNoStr).SAP_Province__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.Guarantee_period_for_products__c = NFMUtil.parseStr2Date(dnInfo.GuaranteePeriod);
										rac.TracingCode__c            = dnInfo.TracingCode;
										// HHOA-BFF53G IF来源
										rac.IF_Information_From__c    = true;
										//生成追溯明细时 记录SAP合同号 by rentx 2020-12-14
										if (String.isNotEmpty(InquiryNoStr2)) {
											rac.ContractNo_text__c  = InquiryNoStr2;
										}
										//生成追溯明细时 记录SAP合同号

										// 【委托】ET消耗品系统自动生成出库数量大于当月发货数量 精琢技术 tcm start 已测 a001m000002eEqS
										if (String.isNotEmpty(InquiryNoStr)) {
											rac.Opportunity_No__c = InquiryNoStr;
										}
										// 【委托】ET消耗品系统自动生成出库数量大于当月发货数量 精琢技术 tcm end
									}
									cod2List.add(rac);
									odDSUpsertMap.put(InquiryNoStr + ':' + dnInfo.Barcode, rac);
									odUpsertIdxMap.put(InquiryNoStr + ':' + dnInfo.Barcode, odDSUpsertMap.size());
									// HHOA-BF25ZM 返品时不更新名称
									if (!detailsSendAgainNoMap.containsKey(dnInfo.Barcode)) {
										rac.Name                      = InquiryNoStr + ':' + ('000' + odUpsertIdxMap.get(InquiryNoStr + ':' + dnInfo.Barcode)).right(4);
									}
									rac.RecordTypeId              = System.Label.RT_ConOrderDetail2_Return;              // TODO 本番IDにする label
									rac.Box_Piece__c              = '盒';
									rac.Return_date__c            = NFMUtil.parseStr2Date(infoH.DeliveryDate);
									rac.Return_reason__c          = '医院退货';
									//全部System
									rac.OwnerId                   = System.Label.User_OlympusSystem;
									// HHOA-BF25ZM 同一个messageNo多个DN对应
									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());
									}
								}
							}
							logstr += dnInfo.OTCode + ':' + dnInfo.SerialNoorLotNo + '(delete) ';
							// InstallDateがある場合、Warning! を出す
							if (ast.InstallDate != null) {
								// HHOA-AGN2EH start
								//iflog.ErrorLog__c += 'SoNo[' + infoH.SoNo + '] DeliveryNote[' + infoH.DeliveryNote + '] Warning! Delete Asset[' + dnInfo.OTCode + ':' + dnInfo.SerialNoorLotNo + '] is installed at ' + NFMUtil.formatDate2Str(ast.InstallDate) + '\n';
								// HHOA-AGN2EH end
							}
							// 修理がある場合、Warning! を出す
							if (ast.Repair_Count__c > 0) {
								// HHOA-AGN2EH start
								//iflog.ErrorLog__c += 'SoNo[' + infoH.SoNo + '] DeliveryNote[' + infoH.DeliveryNote + '] Warning! Delete Asset[' + dnInfo.OTCode + ':' + dnInfo.SerialNoorLotNo + '] with repair.\n';
								// HHOA-AGN2EH end
							}
							continue;
						}
					}
					//System.debug('开始end');
					// HHOA-AGN2EH start
					boolean clearflg = false;
					if (hasAst == true) {
						if (infoH.ReturnMark != '1' && ast.Delete_Flag__c == true) {
							iflog.ErrorLog__c += 'Warning! Asset' + '[' + ast.OT_CODE__c + ':' + ast.SerialNumber  + '] Delete Flag was cancelled.\n';
						}
						if (infoH.ReturnMark != '1' && ast.Return_Flag__c == true) {
							iflog.ErrorLog__c += 'Warning! Asset' + '[' + ast.OT_CODE__c + ':' + ast.SerialNumber  + '] Return Flag was cancelled.\n';
						}
						//update by rentx 20210622 start
						// if (accsMap.get(infoH.DepartmentNo).Id != ast.AccountId) {
						if (accsMap.get(infoH.DepartmentNo).Id != ast.AccountId && dnInfo.SerialNoorLotNo != '.') {
							//update by rentx 20210622 end
							if (accsMap.get(infoH.EndUserNo).RecordType.DeveloperName != 'Agency' && accsMap.get(infoH.EndUserNo).RecordType.DeveloperName != 'AgencyContract') {
								iflog.ErrorLog__c += 'Warning! Asset' + '[' + ast.OT_CODE__c + ':' + ast.SerialNumber  + '] DepartmentCode:' + ast.Account.Management_Code__c + ' is updated to ' + infoH.DepartmentNo + '.\n';
							}
						}
						if (accsMap.get(infoH.DepartmentNo).Id != ast.AccountId && ast.InstallDate != null && NFMUtil.parseStr2Date(infoH.DeliveryDate) > ast.InstallDate) {
							clearflg = true;
							iflog.ErrorLog__c += 'Warning! Asset' + '[' + ast.OT_CODE__c + ':' + ast.SerialNumber  + '] Install Date:' + ast.InstallDate + 'is cleared.\n';
						}
						if (ast.SerialNumber == dnInfo.SerialNoorLotNo && ast.MDM_Model_No__c == prd.MDM_Model_No__c && ast.OT_CODE__c != dnInfo.OTCode) {
							iflog.ErrorLog__c += 'Warning! Asset' + '[' + ast.OT_CODE__c + ':' + ast.SerialNumber  + '] is updated to [' + dnInfo.OTCode + ':' + dnInfo.SerialNoorLotNo + '].\n';
						}
					}
					// HHOA-AGN2EH end
					// 消耗品订单
					if (orderMap.containsKey(InquiryNoStr)) {
						System.debug('step 1');
						Consumable_order__c order = orderMap.get(InquiryNoStr);
						if (oUpdateMap.containsKey(InquiryNoStr) == false
						    && order.RecordType.Developername == 'Order') {
							order.RecordTypeId = System.Label.RT_ConOrder_Delivery;
							oUpdateMap.put(InquiryNoStr, order);
						}
						// 消耗品直接到货，NFM110再入库对应
						Consumable_order_details2__c orderdetInfo = orderDetailTCDeliveryMap.get(dnInfo.TracingCode);
						if (orderdetInfo != null && String.isNotBlank( dnInfo.Barcode)) {
							odUpsertMap.put(InquiryNoStr + ':' + dnInfo.Barcode, orderdetInfo);
							odUpsertIdxMap.put(InquiryNoStr + ':' + dnInfo.Barcode, odUpsertMap.size());
							//System.debug('消耗品直接到货，NFM110再入库对应' + orderdetInfo);
							iflog.ErrorLog__c += 'Warning! Consumable Asset [' + orderdetInfo.Asset_Model_No__c + '] DN [' + infoH.DeliveryNote + '] DeliveryDate[' + orderdetInfo.Deliver_date__c + '] is updated to [' + NFMUtil.parseStr2Date(infoH.DeliveryDate) + '].\n';
							orderdetInfo.Deliver_date__c = NFMUtil.parseStr2Date(infoH.DeliveryDate);
							orderdetInfo.Name = InquiryNoStr + ':' + ('000' + odUpsertIdxMap.get(InquiryNoStr + ':' + dnInfo.Barcode)).right(4);
							orderdetInfo.Direct_Arrive_Product__c = false;
							if (String.isNotBlank(dnInfo.VALUE)) {
								orderdetInfo.Intra_Trade_List_RMB__c = Decimal.valueOf(dnInfo.VALUE);
							}
							orderdetInfo.Consumable_order_minor__c = order.Id;
							orderdetInfo.Used_account__c           = accsMap.get(infoH.EndUserNo).Id;
							// update by vivek srart 2020-02-13
							// orderdetInfo.Account_province_txt__c = accsMap.get(infoH.EndUserNo).OCM_man_province_txt__c;
							// update by vivek end 2020-02-13
							// gzw DB202301244151 保修期限验证日期可行性调整 start
							if (dnInfo.ValidTo !=null && dnInfo.ValidTo.length() == 8
										&& Integer.valueOf(dnInfo.ValidTo.substring(0, 4)) <= Integer.valueOf(Date.today().Year())) {
								orderdetInfo.Sterilization_limit__c = null;
							}else{
								orderdetInfo.Sterilization_limit__c    = NFMUtil.parseStr2Date(dnInfo.ValidTo);
							}
							// orderdetInfo.Sterilization_limit__c    = NFMUtil.parseStr2Date(dnInfo.ValidTo);
							// gzw DB202301244151 保修期限验证日期可行性调整 end
							//orderdetInfo.Bar_Code__c               = dnInfo.Barcode;
							orderdetInfo.DeliveryNote__c           = infoH.DeliveryNote;
							// update by Gaozw start 20200514
							orderdetInfo.SerialLotNo__c            = dnInfo.SerialNoorLotNo == '.'? datestr : dnInfo.SerialNoorLotNo;
							// update by Gaozw end 20200514
							// HHOA-BLK55J IF来源
							orderdetInfo.IF_Information_From__c    = true;
							//orderdetInfo.Guarantee_period_for_products__c = NFMUtil.parseStr2Date(dnInfo.GuaranteePeriod);
							//生成追溯明细时 记录SAP合同号 by rentx 2020-12-14
							if (String.isNotEmpty(InquiryNoStr2)) {
								orderdetInfo.ContractNo_text__c = InquiryNoStr2;
							}
							//生成追溯明细时 记录SAP合同号
							// 【委托】ET消耗品系统自动生成出库数量大于当月发货数量 精琢技术 tcm start
							if (String.isNotEmpty(InquiryNoStr)) {
								orderdetInfo.Opportunity_No__c = InquiryNoStr;
							}
							// 【委托】ET消耗品系统自动生成出库数量大于当月发货数量 精琢技术 tcm end

							odDetailUpsertMap.put(InquiryNoStr + ':' + dnInfo.Barcode, orderdetInfo);
							orderDetailDeliveryMap.put(InquiryNoStr + ':' + dnInfo.TracingCode, orderdetInfo);

							// upsert用、項目転送
							if (dnInfo.SorLMark == 'S') {
								ast.AssetMark__c = '主机';
								//ast = astsMap.get(ANY key)
								//update by rentx 20210624 start 传入的数据中有多条机身号为.的机身号的问题
								// ast.Product_Serial_No__c = prdsMap.get(dnInfo.OTCode).MDM_Model_No__c + dnInfo.SerialNoorLotNo;
								//为了防治系统中存在 产品 + 机体编码 为当前日期 然后导致添加失败的问题 在datestr后加上当前行的OTCode
								// ast.Product_Serial_No__c = prdsMap.get(dnInfo.OTCode).MDM_Model_No__c + (dnInfo.SerialNoorLotNo == '.' ? datestr : dnInfo.SerialNoorLotNo);
								ast.Product_Serial_No__c = prdsMap.get(dnInfo.OTCode).MDM_Model_No__c + (dnInfo.SerialNoorLotNo == '.' ? odatestr+dnInfo.OTCode : dnInfo.SerialNoorLotNo);
								//update by rentx 20210624 end
							} else {
								ast.AssetMark__c = '耗材';
								//update by rentx 20210624 start
								// ast.Product_Serial_No__c = prdsMap.get(dnInfo.OTCode).MDM_Model_No__c + dnInfo.SerialNoorLotNo + '(' + dnInfo.TracingCode + ')';
								ast.Product_Serial_No__c = prdsMap.get(dnInfo.OTCode).MDM_Model_No__c + (dnInfo.SerialNoorLotNo == '.' ? odatestr +dnInfo.OTCode : dnInfo.SerialNoorLotNo ) +'(' + dnInfo.TracingCode + ')';
								//update by rentx 20210624 end
							}
							if (astsMap.get(ast.Product_Serial_No__c ) == null) {
								ast = new Asset();
								//20230323 lt DB202303088261 两票制 Start
								if(oppMap.get(InquiryNoStr).SAP_Province__c == 'OSH-安徽省'){
									ast.OSHFLG__c = true ;
								}
								//20230323 lt DB202303088261 两票制 End
								astList.add(ast);

								//astUpdateMap.put(ast.Product_Serial_No__c, ast);
								logstr += dnInfo.OTCode + ':' + dnInfo.SerialNoorLotNo + '(' + dnInfo.TracingCode + ')' + ' ';
							} else {
								iflog.ErrorLog__c += 'Warning! Asset' + '[' + dnInfo.OTCode + ':' + dnInfo.SerialNoorLotNo  + '] Exist. This asset is skipped.\n';
								continue;
								//ast = astUpdateMap.get(ast.Product_Serial_No__c);
							}
							ast.Name                             = prd.Name;
							if (String.isNotEmpty(InquiryNoStr2)) {
								ast.Order_No__c                  = InquiryNoStr2;
							} else {
								ast.Order_No__c                  = InquiryNoStr;
							}
							ast.Backorder__c                     = String.isBlank(infoH.SoNo) ? null : boMap.get(infoH.SoNo);
							ast.Posting_Date__c                  = NFMUtil.parseStr2Date(infoH.DeliveryDate);
							ast.DeliveryNote__c                  = infoH.DeliveryNote;
							//if (accsMap.get(infoH.EndUserNo).RecordType.DeveloperName == 'Agency') {
							// default AccountId を設定しない
							//if(!hasAst){
							ast.Asset_Owner__c                   = '经销商资产';
							ast.Asset_owner_delaer_name__c       = accsMap.get(infoH.EndUserNo).ParentId;
							ast.AccountId                        = accsMap.get(infoH.EndUserNo).Id;
							ast.Department_Class__c              = accsMap.get(infoH.EndUserNo).Id;
							ast.Hospital__c                      = accsMap.get(infoH.EndUserNo).ParentId;
							ast.Product2Id                       = prdsMap.get(dnInfo.OTCode).Id;
							// CHAN-BGYE7C start
							ast.ProductionDate__c                = NFMUtil.parseStr2Date(dnInfo.ProduceDate);
							// 20210108 gzw add 虚拟合同号追加 start
							// ast.NetWorthNoProviston__c           = String.isBlank(dnInfo.NetWorthNoProviston) ?
							// 0 : Decimal.valueOf(dnInfo.NetWorthNoProviston.trim());
							ast.NetWorthNoProviston__c           = 0;
							if (String.isNotBlank(dnInfo.NetWorthNoProviston)) {
								Decimal netProviston = Decimal.valueOf(dnInfo.NetWorthNoProviston.trim());
								ast.NetWorthNoProviston__c   = oppMap.get(InquiryNoStr).Trade__c == '内貿'?
								                               netProviston : netProviston * Decimal.valueOf(Label.Account_Exc);
							}
							// 20210108 gzw add 虚拟合同号追加 end
							// CHAN-BGYE7C end
							// CHAN-BJX9EQ Start
							ast.NMPA_Approbation_No__c           = dnInfo.NMPA_NO;
							ast.ProduceCompany__c                = dninfo.Provider;
							// CHAN-BJX9EQ End
							//}

							//ast.Quantity                         = String.isBlank(dnInfo.VALUE) ? null : Decimal.valueOf(dnInfo.VALUE);
							if (dnInfo.SorLMark == 'S') {
								ast.AssetMark__c = '主机';
								//ast.Guarantee_period_for_products__c = NFMUtil.parseStr2Date(dnInfo.GuaranteePeriod);
								// update by Gaozw start 20200514
								// ast.SerialNumber                     = dnInfo.SerialNoorLotNo == '.'? datestr : dnInfo.SerialNoorLotNo;
								ast.SerialNumber                     = dnInfo.SerialNoorLotNo == '.'? odatestr +dnInfo.OTCode: dnInfo.SerialNoorLotNo;
								// update by Gaozw end 20200514
							} else {
								ast.AssetMark__c = '耗材';
								//ast.Guarantee_period_for_products__c = NFMUtil.parseStr2Date(infoH.DeliveryDate);
								// update by Gaozw start 20200514
								// ast.SerialNumber                     = (dnInfo.SerialNoorLotNo == '.'? datestr : dnInfo.SerialNoorLotNo) + '(' + dnInfo.TracingCode + ')';
								ast.SerialNumber                     = (dnInfo.SerialNoorLotNo == '.'? odatestr+dnInfo.OTCode : dnInfo.SerialNoorLotNo) + '(' + dnInfo.TracingCode + ')';
								// update by Gaozw end 20200514
							}
							ast.SLMark__c                        = 'Serial Number';         // 固定 dnInfo.SorLMark;
							//HWAG-B9AAD9 当保有设备 的 保有设备标记 =耗材时，保修期限 =发货日
							//ast.Guarantee_period_for_products__c = NFMUtil.parseStr2Date(dnInfo.GuaranteePeriod);
							if (String.isNotBlank(dnInfo.GuaranteePeriod)) {
								if (dnInfo.GuaranteePeriod.trim().length() == 2) {
									ast.New_logic_data__c            = true;
									ast.Guarantee_period_year__c     =  dnInfo.SorLMark == 'L' ? 0 : Decimal.valueOf(dnInfo.GuaranteePeriod);
								} else {
									ast.Guarantee_period_for_products__c = NFMUtil.parseStr2Date(dnInfo.GuaranteePeriod);
								}
								//ast.Guarantee_period_year__c     =  dnInfo.SorLMark == 'L' ? 0 :Decimal.valueOf(dnInfo.GuaranteePeriod);
							} else {
								ast.New_logic_data__c            = true;
							}
							if (String.isNotBlank(dnInfo.ProvistonPeriod)) {
								ast.ProvistonPeriod__c     =  dnInfo.SorLMark == 'L' ? 0 : Decimal.valueOf(dnInfo.ProvistonPeriod);
							}
							if (String.isNotBlank(dnInfo.GuaranteePrice)) {
								// 20210108 gzw add 虚拟合同号追加 start
								// ast.Asset_GuaranteePrice__c = Decimal.valueOf(dnInfo.GuaranteePrice.trim());
								Decimal gPrice = Decimal.valueOf(dnInfo.GuaranteePrice.trim());
								ast.Asset_GuaranteePrice__c = oppMap.get(InquiryNoStr).Trade__c == '内貿'?
								                              gPrice : gPrice * Decimal.valueOf(Label.Account_Exc);
								// 20210108 gzw add 虚拟合同号追加 start
							}
							ast.TracingCode__c                   = dnInfo.TracingCode;
							ast.Guaranteen_end__c                = NFMUtil.parseStr2Date(dnInfo.ValidTo);
							ast.Barcode__c                       = dnInfo.Barcode;
							ast.IF_Information_From__c           = true;
							// HHOA-AGN2EH start
							ast.Return_Flag__c = false;
							ast.Delete_Flag__c = false;
							// SWAG-BDV589 start
							if (infoH.ReturnMark == '3') {
								if (OppNumberAndProductCodetoQISMap.containskey(tempInquiryNo + ':' + dnInfo.OTCode)) {
									list<QIS_Report__c> tempQISList =
										OppNumberAndProductCodetoQISMap.get(tempInquiryNo + ':' + dnInfo.OTCode);
									if (tempQISList.size() > 0) {
										QIS_Report__c tempQIS = tempQISList.remove(0);
										tempQIS.ReplaceDeliveryDate__c =
											NFMUtil.parseStr2Date(infoH.DeliveryDate);
										allUpdateQISList.add(tempQIS);
									}

								}
							}
							// SWAG-BDV589 end
							if (clearflg == true) {
								ast.InstallDate = null;
							}
							continue;
						}
						if (detailsSendAgainMap.containsKey(InquiryNoStr + ':' + dnInfo.Barcode) == true) {
							iflog.ErrorLog__c += 'Error! SoNo[' + infoH.SoNo + '] DeliveryNote[' + infoH.DeliveryNote + '] [' + InquiryNoStr + '] Barcode[' + dnInfo.Barcode + ']Duplicate. This asset is skipped.\n';
							continue;
						}
						// gzw 20211207 追溯跳过ZM16 start
						// if (orderDetailDeliveryMap.containsKey(InquiryNoStr + ':' + dnInfo.TracingCode) == false
						//     && String.isNotBlank( dnInfo.Barcode)) {
						if (orderDetailDeliveryMap.containsKey(InquiryNoStr + ':' + dnInfo.TracingCode) == false
						    && String.isNotBlank( dnInfo.Barcode)  && NameorderType.get(infoH.SoNo) != 'ZM16') {
						// gzw 20211207 追溯跳过ZM16 end
							Product2__c prdMap = prdSearchMap.get(dnInfo.OTCode);
							//订单类型为ZM16时不生成追溯系统相关内容  精琢技术 thh 2021-10-11 start
							if (!prdMap.Pro2_Dealer_Object__c && !prdMap.Pro2_Dealer_ENG__c && NameorderType.get(infoH.SoNo) == 'ZM16') {
								continue;
							}
							//订单类型为ZM16时不生成追溯系统相关内容  精琢技术 thh 2021-10-11 end
							Consumable_order_details2__c rac = odUpsertMap.get(InquiryNoStr + ':' + dnInfo.Barcode);
							if (rac == null) {
								rac = new Consumable_order_details2__c();
								odUpsertMap.put(InquiryNoStr + ':' + dnInfo.Barcode, rac);
								odUpsertIdxMap.put(InquiryNoStr + ':' + dnInfo.Barcode, odUpsertMap.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 if (orderdet1priceMap.containsKey(prdSearch.Id)) {
								rac.Intra_Trade_List_RMB__c = orderdet1priceMap.get(prdSearch.Id);
							} else {
								rac.Intra_Trade_List_RMB__c = prdSearch.Intra_Trade_List_RMB__c;
							}
							// update by gzw 2020-04-27 start
							if (oppMap.containsKey(InquiryNoStr)) {
								rac.Agencyinfo_fromSAP__c     = oppMap.get(InquiryNoStr).Agency1__r.Name;
							}
							// update by gzw 2020-04-27 end
							rac.Asset_Model_No__c         = prdSearch.Asset_Model_No__c;
							rac.Consumable_order_minor__c = order.Id;
							rac.Deliver_date__c           = NFMUtil.parseStr2Date(infoH.DeliveryDate);
							// 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           = accsMap.get(infoH.EndUserNo).Id;
							// update by vivek srart 2020-02-13
							// rac.Account_province_txt__c = accsMap.get(infoH.EndUserNo).OCM_man_province_txt__c;
							// update by vivek end 2020-02-13
							//rac.Dealer_Info_IF__c         = accsMap.get(infoH.EndUserNo).Id;
							rac.DeliveryNote__c           = infoH.DeliveryNote;
							// update by Gaozw start 20200514
							rac.SerialLotNo__c            = dnInfo.SerialNoorLotNo == '.'? datestr : dnInfo.SerialNoorLotNo;
							// update by Gaozw end 20200514
							//rac.Guarantee_period_for_products__c = NFMUtil.parseStr2Date(dnInfo.GuaranteePeriod);
							rac.TracingCode__c            = dnInfo.TracingCode;
							// HHOA-BFF53G IF来源
							rac.IF_Information_From__c    = true;
							// ====lw edit start ====
							if (order.OwnerId != null) {
								rac.OwnerId               = order.OwnerId;
							}
							//生成追溯明细时 记录SAP合同号 by rentx 2020-12-14
							if (String.isNotEmpty(InquiryNoStr2)) {
								rac.ContractNo_text__c  = InquiryNoStr2;
							}
							//生成追溯明细时 记录SAP合同号
							// 【委托】ET消耗品系统自动生成出库数量大于当月发货数量 精琢技术 tcm start 已测 a001m000002Zfk1
							if (String.isNotEmpty(InquiryNoStr)) {
								rac.Opportunity_No__c = InquiryNoStr;
							}
							// 【委托】ET消耗品系统自动生成出库数量大于当月发货数量 精琢技术 tcm end
						}
						// 设备、以下 ET24小时 Asset
						// upsert用、項目転送
						if (dnInfo.SorLMark == 'S') {
							ast.AssetMark__c = '主机';
							//ast = astsMap.get(ANY key)
							//update by rentx 20210624 start 传入的数据中有多条机身号为.的机身号的问题
							// ast.Product_Serial_No__c = prdsMap.get(dnInfo.OTCode).MDM_Model_No__c + dnInfo.SerialNoorLotNo;
							// ast.Product_Serial_No__c = prdsMap.get(dnInfo.OTCode).MDM_Model_No__c + (dnInfo.SerialNoorLotNo == '.' ? datestr : dnInfo.SerialNoorLotNo);
							ast.Product_Serial_No__c = prdsMap.get(dnInfo.OTCode).MDM_Model_No__c + (dnInfo.SerialNoorLotNo == '.' ? odatestr+dnInfo.OTCode : dnInfo.SerialNoorLotNo);
							//update by rentx 20210624 end

						} else {
							ast.AssetMark__c = '耗材';

							//update by rentx 20210624 start
							// ast.Product_Serial_No__c = prdsMap.get(dnInfo.OTCode).MDM_Model_No__c + dnInfo.SerialNoorLotNo + '(' + dnInfo.TracingCode + ')';
							// ast.Product_Serial_No__c = prdsMap.get(dnInfo.OTCode).MDM_Model_No__c + (dnInfo.SerialNoorLotNo == '.' ? datestr : dnInfo.SerialNoorLotNo +'(' + dnInfo.TracingCode + ')' ) ;
							ast.Product_Serial_No__c = prdsMap.get(dnInfo.OTCode).MDM_Model_No__c + (dnInfo.SerialNoorLotNo == '.' ? odatestr+dnInfo.OTCode : dnInfo.SerialNoorLotNo)  +'(' + dnInfo.TracingCode + ')';
							//update by rentx 20210624 end
						}
						if (astsMap.get(ast.Product_Serial_No__c ) == null) {
							ast = new Asset();
							//20230323 lt DB202303088261 两票制 Start
							if(oppMap.get(InquiryNoStr).SAP_Province__c == 'OSH-安徽省'){
								ast.OSHFLG__c = true ;
							}
							//20230323 lt DB202303088261 两票制 End
							astList.add(ast);
							//astUpdateMap.put(ast.Product_Serial_No__c, ast);
							logstr += dnInfo.OTCode + ':' + dnInfo.SerialNoorLotNo + '(' + dnInfo.TracingCode + ')' + ' ';
						} else {
							iflog.ErrorLog__c += 'Warning! Asset' + '[' + dnInfo.OTCode + ':' + dnInfo.SerialNoorLotNo  + '] Exist. This asset is skipped.\n';
							continue;
							//ast = astUpdateMap.get(ast.Product_Serial_No__c);
						}
						ast.Name                             = prd.Name;
						if (String.isNotEmpty(InquiryNoStr2)) {
							ast.Order_No__c                  = InquiryNoStr2;
						} else {
							ast.Order_No__c                  = InquiryNoStr;
						}
						ast.Backorder__c                     = String.isBlank(infoH.SoNo) ? null : boMap.get(infoH.SoNo);
						ast.Posting_Date__c                  = NFMUtil.parseStr2Date(infoH.DeliveryDate);
						ast.DeliveryNote__c                  = infoH.DeliveryNote;
						//if (accsMap.get(infoH.EndUserNo).RecordType.DeveloperName == 'Agency') {
						// default AccountId を設定しない
						//if(!hasAst){
						// gzw 20211207 追溯跳过ZM16 start
						if(NameorderType.get(infoH.SoNo) == 'ZM16'){
							ast.Asset_Owner__c                   = '病院資産';
							ast.AccountId                        = accsMap.get(infoH.DepartmentNo).Id;
							ast.Department_Class__c              = accsMap.get(infoH.DepartmentNo).Department_Class__c;
							ast.Hospital__c                      = accsMap.get(infoH.EndUserNo).Id;
						}else{
							ast.Asset_Owner__c                   = '经销商资产';
							ast.Asset_owner_delaer_name__c       = accsMap.get(infoH.EndUserNo).ParentId;
							ast.AccountId                        = accsMap.get(infoH.EndUserNo).Id;
							ast.Department_Class__c              = accsMap.get(infoH.EndUserNo).Id;
							ast.Hospital__c                      = accsMap.get(infoH.EndUserNo).ParentId;
						}
						// ast.Asset_Owner__c                   = '经销商资产';
						// ast.Asset_owner_delaer_name__c       = accsMap.get(infoH.EndUserNo).ParentId;
						// ast.AccountId                        = accsMap.get(infoH.EndUserNo).Id;
						// ast.Department_Class__c              = accsMap.get(infoH.EndUserNo).Id;
						// ast.Hospital__c                      = accsMap.get(infoH.EndUserNo).ParentId;
						// gzw 20211207 追溯跳过ZM16 end
						ast.Product2Id                       = prdsMap.get(dnInfo.OTCode).Id;
						// CHAN-BGYE7C start
						ast.ProductionDate__c   = NFMUtil.parseStr2Date(dnInfo.ProduceDate);
						// 20210108 gzw add 虚拟合同号追加 start
						// ast.NetWorthNoProviston__c           = String.isBlank(dnInfo.NetWorthNoProviston) ?
						// 0 : Decimal.valueOf(dnInfo.NetWorthNoProviston.trim());
						ast.NetWorthNoProviston__c           = 0;
						if (String.isNotBlank(dnInfo.NetWorthNoProviston)) {
							Decimal netProviston = Decimal.valueOf(dnInfo.NetWorthNoProviston.trim());
							ast.NetWorthNoProviston__c   = oppMap.get(InquiryNoStr).Trade__c == '内貿'?
							                               netProviston : netProviston * Decimal.valueOf(Label.Account_Exc);
						}
						// CHAN-BGYE7C end
						// CHAN-BJX9EQ Start
						ast.NMPA_Approbation_No__c           = dnInfo.NMPA_NO;
						ast.ProduceCompany__c                = dninfo.Provider;
						// CHAN-BJX9EQ End
						//ast.Quantity                         = String.isBlank(dnInfo.VALUE) ? null : Decimal.valueOf(dnInfo.VALUE);
						if (dnInfo.SorLMark == 'S') {
							ast.AssetMark__c = '主机';
							//ast.Guarantee_period_for_products__c = NFMUtil.parseStr2Date(dnInfo.GuaranteePeriod);
							// update by Gaozw start 20200514
							// ast.SerialNumber                     = dnInfo.SerialNoorLotNo == '.'? datestr : dnInfo.SerialNoorLotNo;
							ast.SerialNumber                     = dnInfo.SerialNoorLotNo == '.'? odatestr+dnInfo.OTCode : dnInfo.SerialNoorLotNo;
							// update by Gaozw end 20200514
						} else {
							ast.AssetMark__c = '耗材';
							//ast.Guarantee_period_for_products__c = NFMUtil.parseStr2Date(infoH.DeliveryDate);
							// update by Gaozw start 20200514
							// ast.SerialNumber                     = (dnInfo.SerialNoorLotNo == '.'? datestr : dnInfo.SerialNoorLotNo) + '(' + dnInfo.TracingCode + ')';
							ast.SerialNumber                     = (dnInfo.SerialNoorLotNo == '.'? odatestr+dnInfo.OTCode : dnInfo.SerialNoorLotNo) + '(' + dnInfo.TracingCode + ')';
							// update by Gaozw end 20200514
						}
						ast.SLMark__c                        = 'Serial Number';         // 固定 dnInfo.SorLMark;
						//HWAG-B9AAD9 当保有设备 的 保有设备标记 =耗材时，保修期限 =发货日
						//ast.Guarantee_period_for_products__c = NFMUtil.parseStr2Date(dnInfo.GuaranteePeriod);
						if (String.isNotBlank(dnInfo.GuaranteePeriod)) {
							if (dnInfo.GuaranteePeriod.trim().length() == 2) {
								ast.New_logic_data__c            = true;
								ast.Guarantee_period_year__c     =  dnInfo.SorLMark == 'L' ? 0 : Decimal.valueOf(dnInfo.GuaranteePeriod);
							} else {
								ast.Guarantee_period_for_products__c = NFMUtil.parseStr2Date(dnInfo.GuaranteePeriod);
							}
							//ast.Guarantee_period_year__c     =  dnInfo.SorLMark == 'L' ? 0 :Decimal.valueOf(dnInfo.GuaranteePeriod);
						} else {
							ast.New_logic_data__c            = true;
						}
						if (String.isNotBlank(dnInfo.ProvistonPeriod)) {
							ast.ProvistonPeriod__c     =  dnInfo.SorLMark == 'L' ? 0 : Decimal.valueOf(dnInfo.ProvistonPeriod);
						}
						if (String.isNotBlank(dnInfo.GuaranteePrice)) {
							// 20210108 gzw add 虚拟合同号追加 start
							// ast.Asset_GuaranteePrice__c = Decimal.valueOf(dnInfo.GuaranteePrice.trim());
							Decimal gPrice = Decimal.valueOf(dnInfo.GuaranteePrice.trim());
							ast.Asset_GuaranteePrice__c = oppMap.get(InquiryNoStr).Trade__c == '内貿'?
							                              gPrice : gPrice * Decimal.valueOf(Label.Account_Exc);
							// 20210108 gzw add 虚拟合同号追加 start
						}
						ast.TracingCode__c                   = dnInfo.TracingCode;
						ast.Guaranteen_end__c                = NFMUtil.parseStr2Date(dnInfo.ValidTo);
						ast.Barcode__c                       = dnInfo.Barcode;
						ast.IF_Information_From__c           = true;
						// HHOA-AGN2EH start
						ast.Return_Flag__c = false;
						ast.Delete_Flag__c = false;
						// SWAG-BDV589 start
						if (infoH.ReturnMark == '3') {
							if (OppNumberAndProductCodetoQISMap.containskey(tempInquiryNo + ':' + dnInfo.OTCode)) {
								list<QIS_Report__c> tempQISList =
									OppNumberAndProductCodetoQISMap.get(tempInquiryNo + ':' + dnInfo.OTCode);
								if (tempQISList.size() > 0) {
									QIS_Report__c tempQIS = tempQISList.remove(0);
									tempQIS.ReplaceDeliveryDate__c =
										NFMUtil.parseStr2Date(infoH.DeliveryDate);
									allUpdateQISList.add(tempQIS);
								}

							}
						}
						// SWAG-BDV589 end
						if (clearflg == true) {
							ast.InstallDate = null;
						}
					}
					// 经销商合同 包含 ET和非ET24小时
					else if (oppMap.get(InquiryNoStr) != null
					         //&& oppMap.get(InquiryNoStr).Purchase_Type__c == 'ET24時間販売'
					         && oppMap.get(InquiryNoStr).Sales_Root__c == '販売店'
					         && agencyContractMap.get(infoH.EndUserNo) != null
					         && agencyContractMap.get(infoH.EndUserNo).RecordType.Developername == 'AgencyContract'
					         && String.isNotBlank( dnInfo.Barcode)) {
						System.debug('经销商合同');
						// 设备、以下 ET24小时 Asset 非追溯系统订单
						// upsert用、項目転送
						if (dnInfo.SorLMark == 'S') {
							ast.AssetMark__c = '主机';
							//update by rentx 20210624 start 传入的数据中有多条机身号为.的机身号的问题
							// ast.Product_Serial_No__c = prdsMap.get(dnInfo.OTCode).MDM_Model_No__c + dnInfo.SerialNoorLotNo;
							// ast.Product_Serial_No__c = prdsMap.get(dnInfo.OTCode).MDM_Model_No__c + (dnInfo.SerialNoorLotNo == '.' ? datestr : dnInfo.SerialNoorLotNo);
							ast.Product_Serial_No__c = prdsMap.get(dnInfo.OTCode).MDM_Model_No__c + (dnInfo.SerialNoorLotNo == '.' ? odatestr+dnInfo.OTCode : dnInfo.SerialNoorLotNo);
							//update by rentx 20210624 end

						} else {
							ast.AssetMark__c = '耗材';
							//update by rentx 20210624 start
							// ast.Product_Serial_No__c = prdsMap.get(dnInfo.OTCode).MDM_Model_No__c + dnInfo.SerialNoorLotNo + '(' + dnInfo.TracingCode + ')';
							// ast.Product_Serial_No__c = prdsMap.get(dnInfo.OTCode).MDM_Model_No__c + (dnInfo.SerialNoorLotNo == '.' ? datestr : dnInfo.SerialNoorLotNo +'(' + dnInfo.TracingCode + ')' ) ;
							ast.Product_Serial_No__c = prdsMap.get(dnInfo.OTCode).MDM_Model_No__c + (dnInfo.SerialNoorLotNo == '.' ? odatestr +dnInfo.OTCode: dnInfo.SerialNoorLotNo) +'(' + dnInfo.TracingCode + ')';
							//update by rentx 20210624 end

						}
						if (astsMap.get(ast.Product_Serial_No__c ) == null) {
							ast = new Asset();
							//20230323 lt DB202303088261 两票制 Start
							if(oppMap.get(InquiryNoStr).SAP_Province__c == 'OSH-安徽省'){
								ast.OSHFLG__c = true ;
							}
							//20230323 lt DB202303088261 两票制 End
							astList.add(ast);
							logstr += dnInfo.OTCode + ':' + dnInfo.SerialNoorLotNo + '(' + dnInfo.TracingCode + ')' + ' ';
						} else {
							iflog.ErrorLog__c += 'Warning! Asset' + '[' + dnInfo.OTCode + ':' + dnInfo.SerialNoorLotNo  + '] Exist. This asset is skipped.\n';
							continue;
						}
						ast.Name                             = prd.Name;
						if (String.isNotEmpty(InquiryNoStr2)) {
							ast.Order_No__c                  = InquiryNoStr2;
						} else {
							ast.Order_No__c                  = InquiryNoStr;
						}
						ast.Backorder__c                     = String.isBlank(infoH.SoNo) ? null : boMap.get(infoH.SoNo);
						ast.Posting_Date__c                  = NFMUtil.parseStr2Date(infoH.DeliveryDate);
						ast.DeliveryNote__c                  = infoH.DeliveryNote;
						ast.Asset_Owner__c                   = '经销商资产';
						ast.Asset_owner_delaer_name__c       = accsMap.get(infoH.EndUserNo).ParentId;
						ast.AccountId                        = accsMap.get(infoH.EndUserNo).Id;
						ast.Department_Class__c              = accsMap.get(infoH.EndUserNo).Id;
						ast.Hospital__c                      = accsMap.get(infoH.EndUserNo).ParentId;
						ast.Product2Id                       = prdsMap.get(dnInfo.OTCode).Id;
						// CHAN-BGYE7C start
						ast.ProductionDate__c   = NFMUtil.parseStr2Date(dnInfo.ProduceDate);
						// 20210108 gzw add 虚拟合同号追加 start
						// ast.NetWorthNoProviston__c           = String.isBlank(dnInfo.NetWorthNoProviston) ?
						// 0 : Decimal.valueOf(dnInfo.NetWorthNoProviston.trim());
						ast.NetWorthNoProviston__c           = 0;
						if (String.isNotBlank(dnInfo.NetWorthNoProviston)) {
							Decimal netProviston = Decimal.valueOf(dnInfo.NetWorthNoProviston.trim());
							ast.NetWorthNoProviston__c   = oppMap.get(InquiryNoStr).Trade__c == '内貿'?
							                               netProviston : netProviston * Decimal.valueOf(Label.Account_Exc);
						}
						// CHAN-BGYE7C end
						// CHAN-BJX9EQ Start
						ast.NMPA_Approbation_No__c           = dnInfo.NMPA_NO;
						ast.ProduceCompany__c                = dninfo.Provider;
						// CHAN-BJX9EQ End
						//ast.Quantity                         = String.isBlank(dnInfo.VALUE) ? null : Decimal.valueOf(dnInfo.VALUE);
						if (dnInfo.SorLMark == 'S') {
							ast.AssetMark__c = '主机';
							//ast.Guarantee_period_for_products__c = NFMUtil.parseStr2Date(dnInfo.GuaranteePeriod);
							// update by Gaozw start 20200514
							// ast.SerialNumber                     = dnInfo.SerialNoorLotNo == '.'? datestr : dnInfo.SerialNoorLotNo;
							ast.SerialNumber                     = dnInfo.SerialNoorLotNo == '.'? odatestr+dnInfo.OTCode : dnInfo.SerialNoorLotNo;
							// update by Gaozw end 20200514
						} else {
							ast.AssetMark__c = '耗材';
							//ast.Guarantee_period_for_products__c = NFMUtil.parseStr2Date(infoH.DeliveryDate);
							// update by Gaozw start 20200514
							// ast.SerialNumber                     = (dnInfo.SerialNoorLotNo == '.'? datestr : dnInfo.SerialNoorLotNo) + '(' + dnInfo.TracingCode + ')';
							ast.SerialNumber                     = (dnInfo.SerialNoorLotNo == '.'? odatestr+dnInfo.OTCode : dnInfo.SerialNoorLotNo) + '(' + dnInfo.TracingCode + ')';
							// update by Gaozw end 20200514
						}
						ast.SLMark__c                        = 'Serial Number';         // 固定 dnInfo.SorLMark;
						//HWAG-B9AAD9 当保有设备 的 保有设备标记 =耗材时，保修期限 =发货日
						//ast.Guarantee_period_for_products__c = NFMUtil.parseStr2Date(dnInfo.GuaranteePeriod);
						if (String.isNotBlank(dnInfo.GuaranteePeriod)) {
							if (dnInfo.GuaranteePeriod.trim().length() == 2) {
								ast.New_logic_data__c            = true;
								ast.Guarantee_period_year__c     =  dnInfo.SorLMark == 'L' ? 0 : Decimal.valueOf(dnInfo.GuaranteePeriod);
							} else {
								ast.Guarantee_period_for_products__c = NFMUtil.parseStr2Date(dnInfo.GuaranteePeriod);
							}
						} else {
							ast.New_logic_data__c            = true;
						}
						if (String.isNotBlank(dnInfo.ProvistonPeriod)) {
							ast.ProvistonPeriod__c     =  dnInfo.SorLMark == 'L' ? 0 : Decimal.valueOf(dnInfo.ProvistonPeriod);
						}
						if (String.isNotBlank(dnInfo.GuaranteePrice)) {
							// 20210108 gzw add 虚拟合同号追加 start
							// ast.Asset_GuaranteePrice__c = Decimal.valueOf(dnInfo.GuaranteePrice.trim());
							Decimal gPrice = Decimal.valueOf(dnInfo.GuaranteePrice.trim());
							ast.Asset_GuaranteePrice__c = oppMap.get(InquiryNoStr).Trade__c == '内貿'?
							                              gPrice : gPrice * Decimal.valueOf(Label.Account_Exc);
							// 20210108 gzw add 虚拟合同号追加 start
						}
						// 20210108 gzw add 虚拟合同号追加 start
						// WLIG-CCT9UG 20220512 lt start
						//ast.warrantyType__c                  = dnInfo.GuaranteeType;
						ast.warrantyType__c                  = NFMUtil.getMapValue(transferMap, 'warrantyType__c', string.valueof(dnInfo.GuaranteeType), iflog);
						// WLIG-CCT9UG 20220512 lt end
						if (String.isNotBlank(dnInfo.MaintenancePrice)) {
							Decimal mPrice = Decimal.valueOf(dnInfo.MaintenancePrice.trim());
							ast.Maintenance_Price_Year__c = oppMap.get(InquiryNoStr).Trade__c == '内貿'?
							                                mPrice : mPrice * Decimal.valueOf(Label.Account_Exc) * Decimal.valueOf(Label.Account_Rate);
						}
						if (String.isNotBlank(dnInfo.ServicePrice)) {
							// ast.No_discount__c = Decimal.valueOf(dnInfo.ServicePrice.trim());
							Decimal nodiscount = Decimal.valueOf(dnInfo.ServicePrice.trim());
							ast.No_discount__c = oppMap.get(InquiryNoStr).Trade__c == '内貿'?
							                     nodiscount : nodiscount * Decimal.valueOf(Label.Account_Exc) * Decimal.valueOf(Label.Account_Rate);
						}
						// 20210108 gzw add 虚拟合同号追加 end
						ast.TracingCode__c                   = dnInfo.TracingCode;
						ast.Guaranteen_end__c                = NFMUtil.parseStr2Date(dnInfo.ValidTo);
						ast.Barcode__c                       = dnInfo.Barcode;
						ast.IF_Information_From__c           = true;
						// SWAG-BDV589 start
						if (infoH.ReturnMark == '3') {
							if (OppNumberAndProductCodetoQISMap.containskey(tempInquiryNo + ':' + dnInfo.OTCode)) {
								list<QIS_Report__c> tempQISList =
									OppNumberAndProductCodetoQISMap.get(tempInquiryNo + ':' + dnInfo.OTCode);
								if (tempQISList.size() > 0) {
									QIS_Report__c tempQIS = tempQISList.remove(0);
									tempQIS.ReplaceDeliveryDate__c =
										NFMUtil.parseStr2Date(infoH.DeliveryDate);
									allUpdateQISList.add(tempQIS);
								}

							}
						}
						// SWAG-BDV589 end
						// HHOA-AGN2EH start
						ast.Return_Flag__c = false;
						ast.Delete_Flag__c = false;
						if (clearflg == true) {
							ast.InstallDate = null;
						}
						// HHOA-BFF53G 经销商合同 生成追溯明细2
						Product2__c prdMap = prdSearchMap.get(dnInfo.OTCode);
						//订单类型为ZM16时不生成追溯系统相关内容  精琢技术 thh 2021-10-11 start
						if (!prdMap.Pro2_Dealer_Object__c  && !prdMap.Pro2_Dealer_ENG__c && NameorderType.get(infoH.SoNo) == 'ZM16') {
							continue;
						}
						//订单类型为ZM16时不生成追溯系统相关内容  精琢技术 thh 2021-10-11 end
						// HHOA-BFF53G 不是ET24小时 且 询价科室分类 不是ET，跳过
						if (oppMap.get(InquiryNoStr).Purchase_Type__c != 'ET24時間販売'  && oppMap.get(InquiryNoStr).Opportunity_Category__c != 'ET') {
							continue;
						}
						if (detailsSendAgainNoMap.containsKey(dnInfo.Barcode) == true) {
							iflog.ErrorLog__c += 'Error! SoNo[' + infoH.SoNo + '] DeliveryNote[' + infoH.DeliveryNote + '] [' + InquiryNoStr + '] Barcode[' + dnInfo.Barcode + ']Duplicate. This asset is skipped.\n';
							continue;
						}
						Consumable_order_details2__c rac = odUpsertMap.get(InquiryNoStr + ':' + dnInfo.Barcode);
						if (rac == null) {
							rac = new Consumable_order_details2__c();
							odUpsertMap.put(InquiryNoStr + ':' + dnInfo.Barcode, rac);
							odUpsertIdxMap.put(InquiryNoStr + ':' + dnInfo.Barcode, odUpsertMap.size());
						}

						// update by gzw 2020-04-27 start
						if (oppMap.containsKey(InquiryNoStr)) {
							rac.Agencyinfo_fromSAP__c     = oppMap.get(InquiryNoStr).Agency1__r.Name;
						}
						// update by gzw 2020-04-27 end


						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 if (orderdet1priceMap.containsKey(prdSearch.Id)) {
							rac.Intra_Trade_List_RMB__c = orderdet1priceMap.get(prdSearch.Id);
						} else {
							rac.Intra_Trade_List_RMB__c   = prdSearch.Intra_Trade_List_RMB__c;
						}
						rac.Asset_Model_No__c         = prdSearch.Asset_Model_No__c;
						rac.Deliver_date__c           = NFMUtil.parseStr2Date(infoH.DeliveryDate);
						// 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           = accsMap.get(infoH.EndUserNo).Id;
						// update by vivek srart 2020-02-13
						// rac.Account_province_txt__c = accsMap.get(infoH.EndUserNo).OCM_man_province_txt__c;
						// update by vivek end 2020-02-13
						rac.Dealer_Info_IF__c         = agencyContractMap.get(infoH.EndUserNo).ParentId;
						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;
						}
						// 【委托】ET消耗品系统自动生成出库数量大于当月发货数量 精琢技术 tcm end
					}
					// HHOA-BBACNL 直销耗材信息  OCM直销 包括ET和非ET24小时
					else if (oppMap.get(InquiryNoStr) != null && infoH.ReturnMark != '1'
					         && oppMap.get(InquiryNoStr).Sales_Root__c == 'OCM直接販売'
					         && accsMap.get(infoH.EndUserNo) != null
					         //&& agencyContractMap.get(infoH.EndUserNo).RecordType.Developername == 'AgencyContract'
					         && String.isNotBlank( dnInfo.Barcode)) {
						System.debug('OCM直接販売');

						// 耗材直销
						// upsert用、項目転送
						if (dnInfo.SorLMark == 'S') {
							ast.AssetMark__c = '主机';
							//ast = astsMap.get(ANY key)
							//update by rentx 20210624 start
							// ast.Product_Serial_No__c = prdsMap.get(dnInfo.OTCode).MDM_Model_No__c + dnInfo.SerialNoorLotNo;
							// ast.Product_Serial_No__c = prdsMap.get(dnInfo.OTCode).MDM_Model_No__c + (dnInfo.SerialNoorLotNo == '.' ? datestr : dnInfo.SerialNoorLotNo);
							ast.Product_Serial_No__c = prdsMap.get(dnInfo.OTCode).MDM_Model_No__c + (dnInfo.SerialNoorLotNo == '.' ? odatestr+dnInfo.OTCode : dnInfo.SerialNoorLotNo);

							//update by rentx 20210624 end

						} else {
							ast.AssetMark__c = '耗材';
							//update by rentx 20210624 start 传入的数据中有多条机身号为.的机身号的问题
							// ast.Product_Serial_No__c = prdsMap.get(dnInfo.OTCode).MDM_Model_No__c + dnInfo.SerialNoorLotNo + '(' + dnInfo.TracingCode + ')';
							// ast.Product_Serial_No__c = prdsMap.get(dnInfo.OTCode).MDM_Model_No__c + (dnInfo.SerialNoorLotNo == '.' ? datestr : dnInfo.SerialNoorLotNo +'(' + dnInfo.TracingCode + ')' ) ;
							ast.Product_Serial_No__c = prdsMap.get(dnInfo.OTCode).MDM_Model_No__c + (dnInfo.SerialNoorLotNo == '.' ? odatestr+dnInfo.OTCode : dnInfo.SerialNoorLotNo )+'(' + dnInfo.TracingCode + ')';
							//update by rentx 20210624 end
						}
						if (astsMap.get(ast.Product_Serial_No__c ) == null) {
							ast = new Asset();
							//20230323 lt DB202303088261 两票制 Start
							if(oppMap.get(InquiryNoStr).SAP_Province__c == 'OSH-安徽省'){
								ast.OSHFLG__c = true ;
							}
							//20230323 lt DB202303088261 两票制 End
							astList.add(ast);
							//astUpdateMap.put(ast.Product_Serial_No__c, ast);
							logstr += dnInfo.OTCode + ':' + dnInfo.SerialNoorLotNo + '(' + dnInfo.TracingCode + ')' + ' ';
						} else {
							// CHAN-BUY3GV start
							// 高章伟修改的时候需要注意，对于一般询价来说
							// 保有设备可以进行先退后发，
							// 对于追溯系统来说，不能修改保有设备的信息，直接进入下一条发货明细的循环；
							ast = astsMap.get(ast.Product_Serial_No__c);
							if(ast.Return_Flag__c != true) {
								iflog.ErrorLog__c += 'Warning! Asset' + '[' + dnInfo.OTCode + ':' + dnInfo.SerialNoorLotNo  + '] Exist. This asset is skipped.\n';
								continue;
							}
							Product2__c prdMap = prdSearchMap.get(dnInfo.OTCode);

							if ((prdMap.Pro2_Dealer_Object__c == true
							     || prdMap.Pro2_Dealer_ENG__c == true)
							    &&
							    (oppMap.get(InquiryNoStr).Purchase_Type__c == 'ET24時間販売'
							     || oppMap.get(InquiryNoStr).Opportunity_Category__c == 'ET')
							    ) {
								continue;
							}
							//20230323 lt DB202303088261 两票制 Start
							if(oppMap.get(InquiryNoStr).SAP_Province__c == 'OSH-安徽省'){
								ast.OSHFLG__c = true ;
							}
							//20230323 lt DB202303088261 两票制 End
							astList.add(ast);
							/* 原代码
							   iflog.ErrorLog__c += 'Warning! Asset' + '[' + dnInfo.OTCode + ':' + dnInfo.SerialNoorLotNo  + '] Exist. This asset is skipped.\n';
							   continue;
							 */
							// CHAN-BUY3GV end
							//ast = astUpdateMap.get(ast.Product_Serial_No__c);
						}
						// 市场多年保修 新建虚拟维修合同
						// if(String.isNotBlank(dnInfo.GuaranteeType) && dnInfo.GuaranteeType.contains('市场多年保修') && oppMap.get(InquiryNoStr).Trade__c == '内貿') vmcCount ++;

						ast.Name                             = prd.Name;
						if (String.isNotEmpty(InquiryNoStr2)) {
							ast.Order_No__c                  = InquiryNoStr2;
						} else {
							ast.Order_No__c                  = InquiryNoStr;
						}
						ast.Backorder__c                     = String.isBlank(infoH.SoNo) ? null : boMap.get(infoH.SoNo);
						ast.Posting_Date__c                  = NFMUtil.parseStr2Date(infoH.DeliveryDate);
						ast.DeliveryNote__c                  = infoH.DeliveryNote;
						ast.Asset_Owner__c                   = '病院資産';
						ast.AccountId                        = accsMap.get(infoH.DepartmentNo).Id;
						ast.Department_Class__c              = accsMap.get(infoH.DepartmentNo).Department_Class__c;
						ast.Hospital__c                      = accsMap.get(infoH.EndUserNo).Id;
						ast.Product2Id                       = prdsMap.get(dnInfo.OTCode).Id;
						// CHAN-BGYE7C start
						ast.ProductionDate__c   = NFMUtil.parseStr2Date(dnInfo.ProduceDate);
						// 20210108 gzw add 虚拟合同号追加 start
						// ast.NetWorthNoProviston__c           = String.isBlank(dnInfo.NetWorthNoProviston) ?
						// 0 : Decimal.valueOf(dnInfo.NetWorthNoProviston.trim());
						ast.NetWorthNoProviston__c           = 0;
						if (String.isNotBlank(dnInfo.NetWorthNoProviston)) {
							Decimal netProviston = Decimal.valueOf(dnInfo.NetWorthNoProviston.trim());
							ast.NetWorthNoProviston__c   = oppMap.get(InquiryNoStr).Trade__c == '内貿'?
							                               netProviston : netProviston * Decimal.valueOf(Label.Account_Exc);
						}
						// CHAN-BGYE7C end
						// CHAN-BJX9EQ Start
						ast.NMPA_Approbation_No__c           = dnInfo.NMPA_NO;
						ast.ProduceCompany__c                = dninfo.Provider;
						// CHAN-BJX9EQ End

						//ast.Quantity                         = String.isBlank(dnInfo.VALUE) ? null : Decimal.valueOf(dnInfo.VALUE);
						if (dnInfo.SorLMark == 'S') {
							ast.AssetMark__c = '主机';
							//ast.Guarantee_period_for_products__c = NFMUtil.parseStr2Date(dnInfo.GuaranteePeriod);
							// update by Gaozw start 20200514
							// ast.SerialNumber                     = dnInfo.SerialNoorLotNo == '.'? datestr : dnInfo.SerialNoorLotNo;
							ast.SerialNumber                     = dnInfo.SerialNoorLotNo == '.'? odatestr+dnInfo.OTCode : dnInfo.SerialNoorLotNo;
							// update by Gaozw end 20200514
						} else {
							ast.AssetMark__c = '耗材';
							//ast.Guarantee_period_for_products__c = NFMUtil.parseStr2Date(infoH.DeliveryDate);
							// update by Gaozw start 20200514
							// ast.SerialNumber                     = (dnInfo.SerialNoorLotNo == '.'? datestr : dnInfo.SerialNoorLotNo) + '(' + dnInfo.TracingCode + ')';
							ast.SerialNumber                     = (dnInfo.SerialNoorLotNo == '.'? odatestr+dnInfo.OTCode : dnInfo.SerialNoorLotNo) + '(' + dnInfo.TracingCode + ')';
							// update by Gaozw end 20200514
						}
						ast.SLMark__c                        = 'Serial Number';         // 固定 dnInfo.SorLMark;
						//HWAG-B9AAD9 当保有设备 的 保有设备标记 =耗材时，保修期限 =发货日
						//ast.Guarantee_period_for_products__c = NFMUtil.parseStr2Date(dnInfo.GuaranteePeriod);
						if (String.isNotBlank(dnInfo.GuaranteePeriod)) {
							if (dnInfo.GuaranteePeriod.trim().length() == 2) {
								ast.New_logic_data__c            = true;
								ast.Guarantee_period_year__c     =  dnInfo.SorLMark == 'L' ? 0 : Decimal.valueOf(dnInfo.GuaranteePeriod);
							} else {
								ast.Guarantee_period_for_products__c = NFMUtil.parseStr2Date(dnInfo.GuaranteePeriod);
							}
							//ast.Guarantee_period_year__c     =  dnInfo.SorLMark == 'L' ? 0 :Decimal.valueOf(dnInfo.GuaranteePeriod);
						} else {
							ast.New_logic_data__c            = true;
						}
						if (String.isNotBlank(dnInfo.ProvistonPeriod)) {
							ast.ProvistonPeriod__c     =  dnInfo.SorLMark == 'L' ? 0 : Decimal.valueOf(dnInfo.ProvistonPeriod);
						}
						if (String.isNotBlank(dnInfo.GuaranteePrice)) {
							// 20210108 gzw add 虚拟合同号追加 start
							// ast.Asset_GuaranteePrice__c = Decimal.valueOf(dnInfo.GuaranteePrice.trim());
							Decimal gPrice = Decimal.valueOf(dnInfo.GuaranteePrice.trim());
							ast.Asset_GuaranteePrice__c = oppMap.get(InquiryNoStr).Trade__c == '内貿'?
							                              gPrice : gPrice * Decimal.valueOf(Label.Account_Exc);
							// 20210108 gzw add 虚拟合同号追加 start
						}
						// WLIG-CCT9UG 20220512 lt start
						//ast.warrantyType__c                  = dnInfo.GuaranteeType;
						ast.warrantyType__c                  = NFMUtil.getMapValue(transferMap, 'warrantyType__c', string.valueof(dnInfo.GuaranteeType), iflog);
						// WLIG-CCT9UG 20220512 lt end
						if (String.isNotBlank(dnInfo.MaintenancePrice)) {
							// 20210108 gzw add 虚拟合同号追加 start
							Decimal mPrice = Decimal.valueOf(dnInfo.MaintenancePrice.trim());
							ast.Maintenance_Price_Year__c = oppMap.get(InquiryNoStr).Trade__c == '内貿'?
							                                mPrice : mPrice * Decimal.valueOf(Label.Account_Exc) * Decimal.valueOf(Label.Account_Rate);
							// 20210108 gzw add 虚拟合同号追加 start
						}
						if (String.isNotBlank(dnInfo.ServicePrice)) {
							// 20210108 gzw add 虚拟合同号追加 start
							// ast.No_discount__c = Decimal.valueOf(dnInfo.ServicePrice.trim());
							Decimal nodiscount = Decimal.valueOf(dnInfo.ServicePrice.trim());
							ast.No_discount__c = oppMap.get(InquiryNoStr).Trade__c == '内貿'?
							                     nodiscount : nodiscount * Decimal.valueOf(Label.Account_Exc) * Decimal.valueOf(Label.Account_Rate);
							// 20210108 gzw add 虚拟合同号追加 end
						}

						ast.TracingCode__c                   = dnInfo.TracingCode;
						ast.Guaranteen_end__c                = NFMUtil.parseStr2Date(dnInfo.ValidTo);
						ast.Barcode__c                       = dnInfo.Barcode;
						ast.IF_Information_From__c           = true;


						// SWAG-BDV589 start
						if (infoH.ReturnMark == '3') {
							if (OppNumberAndProductCodetoQISMap.containskey(tempInquiryNo + ':' + dnInfo.OTCode)) {
								list<QIS_Report__c> tempQISList =
									OppNumberAndProductCodetoQISMap.get(tempInquiryNo + ':' + dnInfo.OTCode);
								if (tempQISList.size() > 0) {
									QIS_Report__c tempQIS = tempQISList.remove(0);
									tempQIS.ReplaceDeliveryDate__c =
										NFMUtil.parseStr2Date(infoH.DeliveryDate);
									allUpdateQISList.add(tempQIS);
								}

							}
						}
						// SWAG-BDV589 end
						// HHOA-AGN2EH start


						// 虚拟维修产品计数
						// 修改虚拟合同生成逻辑 gzw 20210324 start
						// if (String.isNotBlank(dnInfo.GuaranteeType) && dnInfo.GuaranteeType.contains('市场多年保修') && oppMap.get(InquiryNoStr).Trade__c == '内貿') {
						if (String.isNotBlank(dnInfo.GuaranteeType) && String.isNotBlank(dnInfo.GuaranteePeriod)
						    && Decimal.valueOf(dnInfo.GuaranteePeriod) > 1 && prdsMap.get(dnInfo.OTCode).Virtual_Contract__c) {
							// if (String.isNotBlank(dnInfo.GuaranteeType) && oppMap.get(InquiryNoStr).Trade__c == '内貿' && prdsMap.get(dnInfo.OTCode).Virtual_Contract__c
							//     && Decimal.valueOf(dnInfo.GuaranteePeriod) > 1 &&
							//     ((dnInfo.GuaranteeType.contains('市场多年保修') && prdsMap.get(dnInfo.OTCode).GuranteeType__c == '市场')
							//         ||(dnInfo.GuaranteeType.contains('服务多年保修') && prdsMap.get(dnInfo.OTCode).GuranteeType__c == '服务'))) {
							// 修改虚拟合同生成逻辑 gzw 20210324 end
							if (!v_MCdetMap.containsKey(prd.MDM_Model_No__c + ast.SerialNumber)) {
								Maintenance_Contract_Asset__c v_MCdet = new Maintenance_Contract_Asset__c();
								//v_MCdet.Name = ast.SerialNumber;
								v_MCdet.V_MC_Name__c = InquiryNoStr;
								//v_MCdet.Backorder__c = String.isBlank(infoH.SoNo) ? null : boMap.get(infoH.SoNo);
								v_MCdet.Return_Flag__c = tempReturnFlg;
								v_MCdet.DeliveryDate__c = NFMUtil.parseStr2Date(infoH.DeliveryDate);
								v_MCdet.Asset_SerialNumber__c = ast.SerialNumber;
								if (String.isNotBlank(dnInfo.ServicePrice)) {
									// 20210108 gzw add 虚拟合同号追加 start
									// v_MCdet.No_discount__c = Decimal.valueOf(dnInfo.ServicePrice.trim());
									// ast.No_discount__c = Decimal.valueOf(dnInfo.ServicePrice.trim());
									Decimal nodiscount = Decimal.valueOf(dnInfo.ServicePrice.trim());
									v_MCdet.No_discount__c = oppMap.get(InquiryNoStr).Trade__c == '内貿'?
									                         nodiscount : nodiscount * Decimal.valueOf(Label.Account_Exc) * Decimal.valueOf(Label.Account_Rate);
									// 20210108 gzw add 虚拟合同号追加 end
								}
								insertv_MCdetlList.add(v_MCdet);
								vmcCount++;
							}
						}

						ast.Return_Flag__c = false;
						ast.Delete_Flag__c = false;
						if (clearflg == true) {
							ast.InstallDate = null;
						}

						Product2__c prdMap = prdSearchMap.get(dnInfo.OTCode);
						//订单类型为ZM16时不生成追溯系统相关内容  精琢技术 thh 2021-10-11 start
						if (!prdMap.Pro2_Dealer_Object__c && !prdMap.Pro2_Dealer_ENG__c && NameorderType.get(infoH.SoNo) == 'ZM16') {
							continue;
						}
						//订单类型为ZM16时不生成追溯系统相关内容  精琢技术 thh 2021-10-11 end
						// HHOA-BFF53G 不是ET24小时 且 询价科室分类 不是ET，跳过
						if (oppMap.get(InquiryNoStr).Purchase_Type__c != 'ET24時間販売'  && oppMap.get(InquiryNoStr).Opportunity_Category__c != 'ET') {
							continue;
						}

						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 = addressNameApiMap.get(oppMap.get(InquiryNoStr).SAP_Province__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);
						}

						Consumable_order_details2__c rac = odDSUpsertMap.get(InquiryNoStr + ':' + dnInfo.Barcode);
						if (rac == null) {
							rac = new Consumable_order_details2__c();
							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());
							}
						}

						// update by gzw 2020-04-27 start
						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
						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 if (orderdet1priceMap.containsKey(prdSearch.Id)) {
							rac.Intra_Trade_List_RMB__c = orderdet1priceMap.get(prdSearch.Id);
						} 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.Consumable_order_minor__c = order.Id;
						rac.Deliver_date__c           = NFMUtil.parseStr2Date(infoH.DeliveryDate);
						rac.Arrive_date__c           = NFMUtil.parseStr2Date(infoH.DeliveryDate);
						rac.Used_date__c           = NFMUtil.parseStr2Date(infoH.DeliveryDate);
						// 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           = addressNameApiMap.get(oppMap.get(InquiryNoStr).SAP_Province__c);
						rac.Dealer_Info_IF__c         = addressNameApiMap.get(oppMap.get(InquiryNoStr).SAP_Province__c);
						//rac.Used_account__c           = accsMap.get(infoH.EndUserNo).Id;
						//rac.Dealer_Info_IF__c         = agencyContractMap.get(infoH.EndUserNo).ParentId;
						rac.DeliveryNote__c           = infoH.DeliveryNote;
						// update by Gaozw start 20200514
						rac.SerialLotNo__c            = dnInfo.SerialNoorLotNo == '.'? datestr : dnInfo.SerialNoorLotNo;
						//rac.Guarantee_period_for_products__c = NFMUtil.parseStr2Date(dnInfo.GuaranteePeriod);
						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;
						}
						// 【委托】ET消耗品系统自动生成出库数量大于当月发货数量 精琢技术 tcm end
					}
					// 销售渠道=经销商 包含 ET和非ET24小时
					else 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('销售渠道=经销商');
						if (dnInfo.SorLMark == 'S') {
							ast.AssetMark__c = '主机';
							//ast = astsMap.get(ANY key)
							//update by rentx 20210624 start 传入的数据中有多条为.的机身号的问题
							// ast.Product_Serial_No__c = prdsMap.get(dnInfo.OTCode).MDM_Model_No__c + dnInfo.SerialNoorLotNo;
							// ast.Product_Serial_No__c = prdsMap.get(dnInfo.OTCode).MDM_Model_No__c + (dnInfo.SerialNoorLotNo == '.' ? datestr : dnInfo.SerialNoorLotNo);
							ast.Product_Serial_No__c = prdsMap.get(dnInfo.OTCode).MDM_Model_No__c + (dnInfo.SerialNoorLotNo == '.' ? odatestr+dnInfo.OTCode : dnInfo.SerialNoorLotNo);
							//update by rentx 20210624 end
						} else {
							ast.AssetMark__c = '耗材';
							//update by rentx 20210624 start
							// ast.Product_Serial_No__c = prdsMap.get(dnInfo.OTCode).MDM_Model_No__c + dnInfo.SerialNoorLotNo + '(' + dnInfo.TracingCode + ')';
							// ast.Product_Serial_No__c = prdsMap.get(dnInfo.OTCode).MDM_Model_No__c + (dnInfo.SerialNoorLotNo == '.' ? datestr : dnInfo.SerialNoorLotNo +'(' + dnInfo.TracingCode + ')' ) ;
							ast.Product_Serial_No__c = prdsMap.get(dnInfo.OTCode).MDM_Model_No__c + (dnInfo.SerialNoorLotNo == '.' ?odatestr+dnInfo.OTCode : dnInfo.SerialNoorLotNo )+'(' + dnInfo.TracingCode + ')';
							//update by rentx 20210624 end
						}
						if (astsMap.get(ast.Product_Serial_No__c ) == null) {
							ast = new Asset();
							//20230323 lt DB202303088261 两票制 Start
							if(oppMap.get(InquiryNoStr).SAP_Province__c == 'OSH-安徽省'){
								ast.OSHFLG__c = true ;
							}
							//20230323 lt DB202303088261 两票制 End
							astList.add(ast);
							//astUpdateMap.put(ast.Product_Serial_No__c, ast);
							logstr += dnInfo.OTCode + ':' + dnInfo.SerialNoorLotNo + '(' + dnInfo.TracingCode + ')' + ' ';
						} else {
							// CHAN-BUY3GV start
							// 高章伟修改的时候需要注意，对于一般询价来说
							// 保有设备可以进行先退后发，
							// 对于追溯系统来说，不能修改保有设备的信息，直接进入下一条发货明细的循环；
							ast = astsMap.get(ast.Product_Serial_No__c);
							if(ast.Return_Flag__c != true) {
								iflog.ErrorLog__c += 'Warning! Asset' + '[' + dnInfo.OTCode + ':' + dnInfo.SerialNoorLotNo  + '] Exist. This asset is skipped.\n';
								continue;
							}
							Product2__c prdMap = prdSearchMap.get(dnInfo.OTCode);

							if ((prdMap.Pro2_Dealer_Object__c == true
							     || prdMap.Pro2_Dealer_ENG__c == true)
							    &&
							    (oppMap.get(InquiryNoStr).Purchase_Type__c == 'ET24時間販売'
							     || oppMap.get(InquiryNoStr).Opportunity_Category__c == 'ET')
							    ) {
								continue;
							}
							//20230323 lt DB202303088261 两票制 Start
							if(oppMap.get(InquiryNoStr).SAP_Province__c == 'OSH-安徽省'){
								ast.OSHFLG__c = true ;
							}
							//20230323 lt DB202303088261 两票制 End
							astList.add(ast);

							//原代码：
							/*
							   iflog.ErrorLog__c += 'Warning! Asset' + '[' + dnInfo.OTCode + ':' + dnInfo.SerialNoorLotNo  + '] Exist. This asset is skipped.\n';
							   continue;
							 */
							// CHAN-BUY3GV end
							//ast = astUpdateMap.get(ast.Product_Serial_No__c);
						}
						// Gzw 20200928 如果不是ET24小时 且 询价科室分类 不是ET，跳过  最终用户为医院  产品信息查询提前
						Product2__c prdMap = prdSearchMap.get(dnInfo.OTCode);
						// 修改虚拟合同生成逻辑 gzw 20210324 start
						// 市场多年保修 新建虚拟维修合同
						// if (String.isNotBlank(dnInfo.GuaranteeType) && dnInfo.GuaranteeType.contains('市场多年保修') && oppMap.get(InquiryNoStr).Trade__c == '内貿') vmcCount ++;
						if (String.isNotBlank(dnInfo.GuaranteeType) && String.isNotBlank(dnInfo.GuaranteePeriod)
						    && Decimal.valueOf(dnInfo.GuaranteePeriod) > 1  && prdsMap.get(dnInfo.OTCode).Virtual_Contract__c) vmcCount++;
						// if (String.isNotBlank(dnInfo.GuaranteeType) && oppMap.get(InquiryNoStr).Trade__c == '内貿' && prdsMap.get(dnInfo.OTCode).Virtual_Contract__c
						//     && Decimal.valueOf(dnInfo.GuaranteePeriod) > 1 &&
						//     ((dnInfo.GuaranteeType.contains('市场多年保修') && prdsMap.get(dnInfo.OTCode).GuranteeType__c == '市场')
						//         ||(dnInfo.GuaranteeType.contains('服务多年保修') && prdsMap.get(dnInfo.OTCode).GuranteeType__c == '服务'))) vmcCount ++;
						// 修改虚拟合同生成逻辑 gzw 20210324 end

						ast.Name                             = prd.Name;
						if (String.isNotEmpty(InquiryNoStr2)) {
							ast.Order_No__c                  = InquiryNoStr2;
						} else {
							ast.Order_No__c                  = InquiryNoStr;
						}
						ast.Backorder__c                     = String.isBlank(infoH.SoNo) ? null : boMap.get(infoH.SoNo);
						ast.Posting_Date__c                  = NFMUtil.parseStr2Date(infoH.DeliveryDate);
						ast.DeliveryNote__c                  = infoH.DeliveryNote;
						// 自动修改最终用户 update by vivek start
						// ast.Asset_Owner__c                   = '病院資産';
						// ast.AccountId                        = accsMap.get(infoH.DepartmentNo).Id;
						// ast.Department_Class__c              = accsMap.get(infoH.DepartmentNo).Department_Class__c;
						// ast.Hospital__c                      = accsMap.get(infoH.EndUserNo).Id;
						// 如果有经销商ET合同，并且合同未到期
						// Gzw 20200928 如果不是ET24小时 且 询价科室分类 不是ET，跳过  最终用户为医院 start
						if (oppMap.get(InquiryNoStr) != null && agencyContractETMap.get(oppMap.get(InquiryNoStr).Agency1__c) != null ) {

							if (!(!prdMap.Pro2_Dealer_Object__c && !prdMap.Pro2_Dealer_ENG__c) && !(oppMap.get(InquiryNoStr).Purchase_Type__c != 'ET24時間販売'  && oppMap.get(InquiryNoStr).Opportunity_Category__c != 'ET')) {
								ast.Asset_Owner__c                   = '经销商资产';
								ast.AccountId                        = agencyContractETMap.get(oppMap.get(InquiryNoStr).Agency1__c);
								ast.Department_Class__c              = agencyContractETMap.get(oppMap.get(InquiryNoStr).Agency1__c);
								ast.Hospital__c                      = oppMap.get(InquiryNoStr).Agency1__c;
								ast.Asset_owner_delaer_name__c       = oppMap.get(InquiryNoStr).Agency1__c;
							}else{
								ast.Asset_Owner__c                   = '病院資産';
								ast.AccountId                        = accsMap.get(infoH.DepartmentNo).Id;
								ast.Department_Class__c              = accsMap.get(infoH.DepartmentNo).Department_Class__c;
								ast.Hospital__c                      = accsMap.get(infoH.EndUserNo).Id;
							}


							// ast.Asset_Owner__c                   = '经销商资产';
							// ast.AccountId                        = agencyContractETMap.get(oppMap.get(InquiryNoStr).Agency1__c);
							// ast.Department_Class__c              = agencyContractETMap.get(oppMap.get(InquiryNoStr).Agency1__c);
							// ast.Hospital__c                      = oppMap.get(InquiryNoStr).Agency1__c;
							// ast.Asset_owner_delaer_name__c       = oppMap.get(InquiryNoStr).Agency1__c;
							// Gzw 20200928 如果不是ET24小时 且 询价科室分类 不是ET，跳过  最终用户为医院 end
						} else {
							ast.Asset_Owner__c                   = '病院資産';
							ast.AccountId                        = accsMap.get(infoH.DepartmentNo).Id;
							ast.Department_Class__c              = accsMap.get(infoH.DepartmentNo).Department_Class__c;
							ast.Hospital__c                      = accsMap.get(infoH.EndUserNo).Id;
						}
						// 自动修改最终用户 update by vivek end
						ast.Product2Id                       = prdsMap.get(dnInfo.OTCode).Id;
						// CHAN-BGYE7C start
						ast.ProductionDate__c   = NFMUtil.parseStr2Date(dnInfo.ProduceDate);
						// 20210108 gzw add 虚拟合同号追加 start
						// ast.NetWorthNoProviston__c           = String.isBlank(dnInfo.NetWorthNoProviston) ?
						// 0 : Decimal.valueOf(dnInfo.NetWorthNoProviston.trim());
						ast.NetWorthNoProviston__c           = 0;
						if (String.isNotBlank(dnInfo.NetWorthNoProviston)) {
							Decimal netProviston = Decimal.valueOf(dnInfo.NetWorthNoProviston.trim());
							ast.NetWorthNoProviston__c   = oppMap.get(InquiryNoStr).Trade__c == '内貿'?
							                               netProviston : netProviston * Decimal.valueOf(Label.Account_Exc);
						}
						// CHAN-BGYE7C end
						// CHAN-BJX9EQ Start
						ast.NMPA_Approbation_No__c           = dnInfo.NMPA_NO;
						ast.ProduceCompany__c                = dninfo.Provider;
						// CHAN-BJX9EQ End

						if (dnInfo.SorLMark == 'S') {
							ast.AssetMark__c = '主机';
							// update by Gaozw start 20200514
							// ast.SerialNumber                     = dnInfo.SerialNoorLotNo == '.'? datestr : dnInfo.SerialNoorLotNo;
							ast.SerialNumber                     = dnInfo.SerialNoorLotNo == '.'? odatestr +dnInfo.OTCode : dnInfo.SerialNoorLotNo;
							// update by Gaozw end 20200514
						} else {
							ast.AssetMark__c = '耗材';
							// update by Gaozw start 20200514
							// ast.SerialNumber                     = (dnInfo.SerialNoorLotNo == '.'? datestr : dnInfo.SerialNoorLotNo) + '(' + dnInfo.TracingCode + ')';
							ast.SerialNumber                     = (dnInfo.SerialNoorLotNo == '.'? odatestr+dnInfo.OTCode : dnInfo.SerialNoorLotNo) + '(' + dnInfo.TracingCode + ')';
							// update by Gaozw end 20200514
						}
						ast.SLMark__c                        = 'Serial Number';         // 固定 dnInfo.SorLMark;
						//HWAG-B9AAD9 当保有设备 的 保有设备标记 =耗材时，保修期限 =发货日
						//ast.Guarantee_period_for_products__c = NFMUtil.parseStr2Date(dnInfo.GuaranteePeriod);
						if (String.isNotBlank(dnInfo.GuaranteePeriod)) {
							if (dnInfo.GuaranteePeriod.trim().length() == 2) {
								ast.New_logic_data__c            = true;
								ast.Guarantee_period_year__c     =  dnInfo.SorLMark == 'L' ? 0 : Decimal.valueOf(dnInfo.GuaranteePeriod);
							} else {
								ast.Guarantee_period_for_products__c = NFMUtil.parseStr2Date(dnInfo.GuaranteePeriod);
							}
						} else {
							ast.New_logic_data__c            = true;
						}
						if (String.isNotBlank(dnInfo.ProvistonPeriod)) {
							ast.ProvistonPeriod__c     =  dnInfo.SorLMark == 'L' ? 0 : Decimal.valueOf(dnInfo.ProvistonPeriod);
						}
						if (String.isNotBlank(dnInfo.GuaranteePrice)) {
							// 20210108 gzw add 虚拟合同号追加 start
							// ast.Asset_GuaranteePrice__c = Decimal.valueOf(dnInfo.GuaranteePrice.trim());
							Decimal gPrice = Decimal.valueOf(dnInfo.GuaranteePrice.trim());
							ast.Asset_GuaranteePrice__c = oppMap.get(InquiryNoStr).Trade__c == '内貿'?
							                              gPrice : gPrice * Decimal.valueOf(Label.Account_Exc);
							// 20210108 gzw add 虚拟合同号追加 start
						}
						// WLIG-CCT9UG 20220512 lt start
						//ast.warrantyType__c                  = dnInfo.GuaranteeType;
						ast.warrantyType__c                  = NFMUtil.getMapValue(transferMap, 'warrantyType__c', string.valueof(dnInfo.GuaranteeType), iflog);
						// WLIG-CCT9UG 20220512 lt end
						if (String.isNotBlank(dnInfo.MaintenancePrice)) {
							// 20210108 gzw add 虚拟合同号追加 start
							Decimal mPrice = Decimal.valueOf(dnInfo.MaintenancePrice.trim());
							ast.Maintenance_Price_Year__c = oppMap.get(InquiryNoStr).Trade__c == '内貿'?
							                                mPrice : mPrice * Decimal.valueOf(Label.Account_Exc) * Decimal.valueOf(Label.Account_Rate);
							// 20210108 gzw add 虚拟合同号追加 start
						}
						if (String.isNotBlank(dnInfo.ServicePrice)) {
							// 20210108 gzw add 虚拟合同号追加 start
							// ast.No_discount__c = Decimal.valueOf(dnInfo.ServicePrice.trim());
							Decimal nodiscount = Decimal.valueOf(dnInfo.ServicePrice.trim());
							ast.No_discount__c = oppMap.get(InquiryNoStr).Trade__c == '内貿'?
							                     nodiscount : nodiscount * Decimal.valueOf(Label.Account_Exc) * Decimal.valueOf(Label.Account_Rate);
							// 20210108 gzw add 虚拟合同号追加 end
						}

						ast.TracingCode__c                   = dnInfo.TracingCode;
						ast.Guaranteen_end__c                = NFMUtil.parseStr2Date(dnInfo.ValidTo);
						ast.Barcode__c                       = dnInfo.Barcode;
						ast.IF_Information_From__c           = true;

						// SWAG-BDV589 start
						if (infoH.ReturnMark == '3') {
							if (OppNumberAndProductCodetoQISMap.containskey(tempInquiryNo + ':' + dnInfo.OTCode)) {
								list<QIS_Report__c> tempQISList =
									OppNumberAndProductCodetoQISMap.get(tempInquiryNo + ':' + dnInfo.OTCode);
								if (tempQISList.size() > 0) {
									QIS_Report__c tempQIS = tempQISList.remove(0);
									tempQIS.ReplaceDeliveryDate__c =
										NFMUtil.parseStr2Date(infoH.DeliveryDate);
									allUpdateQISList.add(tempQIS);
								}

							}
						}
						// SWAG-BDV589 end
						// HHOA-AGN2EH start
						// 虚拟维修产品计数
						// 修改虚拟合同生成逻辑 gzw 20210324 start
						// if (String.isNotBlank(dnInfo.GuaranteeType) && dnInfo.GuaranteeType.contains('市场多年保修') && oppMap.get(InquiryNoStr).Trade__c == '内貿') {
						if (String.isNotBlank(dnInfo.GuaranteeType) && String.isNotBlank(dnInfo.GuaranteePeriod)
						    && Decimal.valueOf(dnInfo.GuaranteePeriod) > 1  && prdsMap.get(dnInfo.OTCode).Virtual_Contract__c) {
							// if (String.isNotBlank(dnInfo.GuaranteeType) && oppMap.get(InquiryNoStr).Trade__c == '内貿' && prdsMap.get(dnInfo.OTCode).Virtual_Contract__c
							//     && Decimal.valueOf(dnInfo.GuaranteePeriod) > 1 &&
							//     ((dnInfo.GuaranteeType.contains('市场多年保修') && prdsMap.get(dnInfo.OTCode).GuranteeType__c == '市场')
							//         ||(dnInfo.GuaranteeType.contains('服务多年保修') && prdsMap.get(dnInfo.OTCode).GuranteeType__c == '服务'))) {
							// 修改虚拟合同生成逻辑 gzw 20210324 end
							if (!v_MCdetMap.containsKey(prd.MDM_Model_No__c + ast.SerialNumber)) {
								Maintenance_Contract_Asset__c v_MCdet = new Maintenance_Contract_Asset__c();
								//v_MCdet.Name = ast.SerialNumber;
								v_MCdet.V_MC_Name__c = InquiryNoStr;
								//v_MCdet.Backorder__c = String.isBlank(infoH.SoNo) ? null : boMap.get(infoH.SoNo);
								v_MCdet.Return_Flag__c = tempReturnFlg;
								v_MCdet.DeliveryDate__c = NFMUtil.parseStr2Date(infoH.DeliveryDate);
								v_MCdet.Asset_SerialNumber__c = ast.SerialNumber;
								if (String.isNotBlank(dnInfo.ServicePrice)) {
									// 20210108 gzw add 虚拟合同号追加 start
									// v_MCdet.No_discount__c = Decimal.valueOf(dnInfo.ServicePrice.trim());
									// ast.No_discount__c = Decimal.valueOf(dnInfo.ServicePrice.trim());
									Decimal nodiscount = Decimal.valueOf(dnInfo.ServicePrice.trim());
									v_MCdet.No_discount__c = oppMap.get(InquiryNoStr).Trade__c == '内貿'?
									                         nodiscount : nodiscount * Decimal.valueOf(Label.Account_Exc) * Decimal.valueOf(Label.Account_Rate);
									// 20210108 gzw add 虚拟合同号追加 end
								}
								// if (String.isNotBlank(dnInfo.GuaranteePrice)) {
								//     v_MCdet.Asset_GuaranteePrice__c = Decimal.valueOf(dnInfo.GuaranteePrice);
								// }
								insertv_MCdetlList.add(v_MCdet);

								vmcCount++;
							}
						}


						ast.Return_Flag__c = false;
						ast.Delete_Flag__c = false;
						if (clearflg == true) {
							ast.InstallDate = null;
						}

						//订单类型为ZM16时不生成追溯系统相关内容  精琢技术 thh 2021-10-11 start
						// Product2__c prdMap = prdSearchMap.get(dnInfo.OTCode);
						if (!prdMap.Pro2_Dealer_Object__c && !prdMap.Pro2_Dealer_ENG__c && NameorderType.get(infoH.SoNo) == 'ZM16') {
							continue;
						}
						//订单类型为ZM16时不生成追溯系统相关内容  精琢技术 thh 2021-10-11 end

						// HHOA-BFF53G 不是ET24小时 且 询价科室分类 不是ET，跳过
						if (oppMap.get(InquiryNoStr).Purchase_Type__c != 'ET24時間販売'  && oppMap.get(InquiryNoStr).Opportunity_Category__c != 'ET') {
							continue;
						}

						// 自动修改最终用户 update by vivek start
						// 如果是最终用户的修改，跳过创建销售订单
						if (!(oppMap.get(InquiryNoStr) != null && agencyContractETMap.get(oppMap.get(InquiryNoStr).Agency1__c) != null )) {
							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);
							}
						}
						// 自动修改最终用户 update by vivek end

						Consumable_order_details2__c rac = odDSUpsertMap.get(InquiryNoStr + ':' + dnInfo.Barcode);
						if (rac == null) {
							rac = new Consumable_order_details2__c();
							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());
							}
						}

						// update by gzw 2020-04-27 start
						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

						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 if (orderdet1priceMap.containsKey(prdSearch.Id)) {
							rac.Intra_Trade_List_RMB__c = orderdet1priceMap.get(prdSearch.Id);
						} 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
						if (!(oppMap.get(InquiryNoStr) != null && agencyContractETMap.get(oppMap.get(InquiryNoStr).Agency1__c) != null) ) {
							rac.Arrive_date__c           = NFMUtil.parseStr2Date(infoH.DeliveryDate);
							rac.Used_date__c           = NFMUtil.parseStr2Date(infoH.DeliveryDate);
							rac.Delivery_List_RMB__c = Decimal.valueOf(dnInfo.VALUE);
						}
						// 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;
						}
						// 【委托】ET消耗品系统自动生成出库数量大于当月发货数量 精琢技术 tcm end
					} else {
						System.debug('正常询价');
						//upsert用、項目転送
						if (dnInfo.SorLMark == 'S') {
							ast.AssetMark__c = '主机';
							//update by rentx 20210622 start
							// ast.Product_Serial_No__c = prdsMap.get(dnInfo.OTCode).MDM_Model_No__c + dnInfo.SerialNoorLotNo;
							// ast.Product_Serial_No__c = prdsMap.get(dnInfo.OTCode).MDM_Model_No__c + (dnInfo.SerialNoorLotNo == '.' ? datestr : dnInfo.SerialNoorLotNo);
							ast.Product_Serial_No__c = prdsMap.get(dnInfo.OTCode).MDM_Model_No__c + (dnInfo.SerialNoorLotNo == '.' ? odatestr +dnInfo.OTCode : dnInfo.SerialNoorLotNo);
							//update by rentx 20210622 end
						} else {
							ast.AssetMark__c = '耗材';
							//update by rentx 20210622 start 传入的数据中有多条为.的机身号的问题
							// ast.Product_Serial_No__c = prdsMap.get(dnInfo.OTCode).MDM_Model_No__c + dnInfo.SerialNoorLotNo + '(' + dnInfo.TracingCode + ')';

							// ast.Product_Serial_No__c = prdsMap.get(dnInfo.OTCode).MDM_Model_No__c + (dnInfo.SerialNoorLotNo == '.' ? datestr : dnInfo.SerialNoorLotNo +'(' + dnInfo.TracingCode + ')' ) ;
							ast.Product_Serial_No__c = prdsMap.get(dnInfo.OTCode).MDM_Model_No__c + (dnInfo.SerialNoorLotNo == '.' ? odatestr+dnInfo.OTCode : dnInfo.SerialNoorLotNo )+'(' + dnInfo.TracingCode + ')';
						}   //update by rentx 20210622 end

						if (astsMap.get(ast.Product_Serial_No__c ) == null) {
							ast = new Asset();
							//20230323 lt DB202303088261 两票制 Start
							if(oppMap.get(InquiryNoStr).SAP_Province__c == 'OSH-安徽省'){
								ast.OSHFLG__c = true ;
							}
							//20230323 lt DB202303088261 两票制 End
							astList.add(ast);
							logstr += dnInfo.SorLMark == 'S' ? dnInfo.OTCode + ':' + dnInfo.SerialNoorLotNo : dnInfo.OTCode + ':' + dnInfo.SerialNoorLotNo + '(' + dnInfo.TracingCode + ')';
						} else {
							System.debug('2156::::'+ast);
							// CHAN-BUY3GV start
							// 高章伟修改的时候需要注意，对于一般询价来说
							// 保有设备可以进行先退后发，
							// 对于追溯系统来说，不能修改保有设备的信息，直接进入下一条发货明细的循环；
							ast = astsMap.get(ast.Product_Serial_No__c);
							if(ast.Return_Flag__c != true) {
								String errMes = dnInfo.SorLMark == 'S' ? dnInfo.OTCode + ':' + dnInfo.SerialNoorLotNo : dnInfo.OTCode + ':' + dnInfo.SerialNoorLotNo + '(' + dnInfo.TracingCode + ')';
								iflog.ErrorLog__c += 'Warning! Asset' + '[' + errMes + '] Exist. This asset is skipped.\n';
								continue;
							}
							//20230323 lt DB202303088261 两票制 Start
							if(oppMap.get(InquiryNoStr).SAP_Province__c == 'OSH-安徽省'){
								ast.OSHFLG__c = true ;
							}
							//20230323 lt DB202303088261 两票制 End
							astList.add(ast);
							// CHAN-BUY3GV end
							// 原代码
							/*String errMes = dnInfo.SorLMark == 'S' ? dnInfo.OTCode + ':' + dnInfo.SerialNoorLotNo : dnInfo.OTCode + ':' + dnInfo.SerialNoorLotNo + '(' + dnInfo.TracingCode + ')';
							   iflog.ErrorLog__c += 'Warning! Asset' + '[' + errMes + '] Exist. This asset is skipped.\n';
							   continue;
							 */
							// CHAN-BUY3GV end
						}
						if (dnInfo.SorLMark == 'S') {
							ast.AssetMark__c = '主机';
							//update by rentx 20210622 start
							// ast.SerialNumber                     = dnInfo.SerialNoorLotNo;
							// ast.SerialNumber                     = dnInfo.SerialNoorLotNo == '.' ? datestr : dnInfo.SerialNoorLotNo;
							ast.SerialNumber                     = dnInfo.SerialNoorLotNo == '.' ? odatestr+dnInfo.OTCode : dnInfo.SerialNoorLotNo;
							//update by rentx 20210622 end
						} else {
							ast.AssetMark__c = '耗材';
							//update by rentx 20210622 start
							// ast.SerialNumber                     = dnInfo.SerialNoorLotNo + '(' + dnInfo.TracingCode + ')';
							// ast.SerialNumber                     = (dnInfo.SerialNoorLotNo == '.' ? datestr : dnInfo.SerialNoorLotNo)  + (dnInfo.TracingCode == '' ? '' :'('+dnInfo.TracingCode+')' ) ;
							ast.SerialNumber                     = (dnInfo.SerialNoorLotNo == '.' ? odatestr+dnInfo.OTCode : dnInfo.SerialNoorLotNo)  + '('+dnInfo.TracingCode+')';
							//update by rentx 20210622 end
						}
						// 修改虚拟合同生成逻辑 gzw 20210324 start
						// 市场多年保修 新建虚拟维修合同
						// if (String.isNotBlank(dnInfo.GuaranteeType) && dnInfo.GuaranteeType.contains('市场多年保修') && oppMap.get(InquiryNoStr).Trade__c == '内貿') vmcCount ++;
						if (String.isNotBlank(dnInfo.GuaranteeType) && String.isNotBlank(dnInfo.GuaranteePeriod)
						    && Decimal.valueOf(dnInfo.GuaranteePeriod) > 1  && prdsMap.get(dnInfo.OTCode).Virtual_Contract__c) vmcCount++;
						// if (String.isNotBlank(dnInfo.GuaranteeType) && oppMap.get(InquiryNoStr).Trade__c == '内貿' && prdsMap.get(dnInfo.OTCode).Virtual_Contract__c
						//     && Decimal.valueOf(dnInfo.GuaranteePeriod) > 1 &&
						//     ((dnInfo.GuaranteeType.contains('市场多年保修') && prdsMap.get(dnInfo.OTCode).GuranteeType__c == '市场')
						//         ||(dnInfo.GuaranteeType.contains('服务多年保修') && prdsMap.get(dnInfo.OTCode).GuranteeType__c == '服务'))) vmcCount ++;
						// 修改虚拟合同生成逻辑 gzw 20210324 end
						ast.Name                             = prd.Name;
						if (String.isNotEmpty(InquiryNoStr2)) {
							ast.Order_No__c                  = InquiryNoStr2;
						} else {
							ast.Order_No__c                  = InquiryNoStr;
						}
						ast.Backorder__c                     = String.isBlank(infoH.SoNo) ? null : boMap.get(infoH.SoNo);
						ast.Posting_Date__c                  = NFMUtil.parseStr2Date(infoH.DeliveryDate);
						ast.DeliveryNote__c                  = infoH.DeliveryNote;
						// CHAN-BGYE7C start
						ast.ProductionDate__c   = NFMUtil.parseStr2Date(dnInfo.ProduceDate);
						// 20210108 gzw add 虚拟合同号追加 start
						// ast.NetWorthNoProviston__c           = String.isBlank(dnInfo.NetWorthNoProviston) ?
						// 0 : Decimal.valueOf(dnInfo.NetWorthNoProviston.trim());
						ast.NetWorthNoProviston__c           = 0;
						if (String.isNotBlank(dnInfo.NetWorthNoProviston)) {
							Decimal netProviston = Decimal.valueOf(dnInfo.NetWorthNoProviston.trim());
							//增加没有询价时，默认内贸的判断 精琢技术 wql 2021/05/08 start
							//注释原逻辑
							// ast.NetWorthNoProviston__c   = oppMap.get(InquiryNoStr).Trade__c == '内貿'?
							// netProviston : netProviston * Decimal.valueOf(Label.Account_Exc);
							//如果没询价
							if(!oppMap.containsKey(InquiryNoStr)) {
								ast.NetWorthNoProviston__c   =netProviston;
							}else{
								ast.NetWorthNoProviston__c   = oppMap.get(InquiryNoStr).Trade__c == '内貿'?
								                               netProviston : netProviston * Decimal.valueOf(Label.Account_Exc);
							}
							//增加没有询价时，默认内贸的判断 精琢技术 wql 2021/05/08 end
						}
						// CHAN-BGYE7C end
						// CHAN-BJX9EQ Start
						ast.NMPA_Approbation_No__c           = dnInfo.NMPA_NO;
						ast.ProduceCompany__c                = dninfo.Provider;
						// CHAN-BJX9EQ End
						if (accsMap.get(infoH.EndUserNo).RecordType.DeveloperName == 'Agency') {
							// default AccountId を設定しない
							ast.Asset_Owner__c                   = '经销商资产';
							ast.Asset_owner_delaer_name__c       = accsMap.get(infoH.EndUserNo).Id;
							ast.AccountId                        = ocm.Id;
							ast.Department_Class__c              = null;
							ast.Hospital__c                      = accsMap.get(infoH.EndUserNo).Id;
						} else if (accsMap.get(infoH.EndUserNo).RecordType.DeveloperName == 'AgencyContract') {
							// default AccountId を設定しない
							ast.Asset_Owner__c                   = '经销商资产';
							ast.Asset_owner_delaer_name__c       = accsMap.get(infoH.EndUserNo).ParentId;
							ast.AccountId                        = accsMap.get(infoH.EndUserNo).Id;
							ast.Department_Class__c              = accsMap.get(infoH.EndUserNo).Id;
							ast.Hospital__c                      = accsMap.get(infoH.EndUserNo).ParentId;
						} else {
							// 前提：備品こない
							ast.Asset_Owner__c                   = '病院資産';
							ast.AccountId                        = accsMap.get(infoH.DepartmentNo).Id;
							ast.Department_Class__c              = accsMap.get(infoH.DepartmentNo).Department_Class__c;
							ast.Hospital__c                      = accsMap.get(infoH.EndUserNo).Id;

							// 虚拟维修产品计数
							// 修改虚拟合同生成逻辑 gzw 20210324 start
							// if (String.isNotBlank(dnInfo.GuaranteeType) && dnInfo.GuaranteeType.contains('市场多年保修') && oppMap.get(InquiryNoStr).Trade__c == '内貿') {
							if (String.isNotBlank(dnInfo.GuaranteeType) && String.isNotBlank(dnInfo.GuaranteePeriod)
							    && Decimal.valueOf(dnInfo.GuaranteePeriod) > 1  && prdsMap.get(dnInfo.OTCode).Virtual_Contract__c) {
								// if (String.isNotBlank(dnInfo.GuaranteeType) && oppMap.get(InquiryNoStr).Trade__c == '内貿' && prdsMap.get(dnInfo.OTCode).Virtual_Contract__c
								//     && Decimal.valueOf(dnInfo.GuaranteePeriod) > 1 &&
								// ((dnInfo.GuaranteeType.contains('市场多年保修') && prdsMap.get(dnInfo.OTCode).GuranteeType__c == '市场')
								//     ||(dnInfo.GuaranteeType.contains('服务多年保修') && prdsMap.get(dnInfo.OTCode).GuranteeType__c == '服务'))) {
								// 修改虚拟合同生成逻辑 gzw 20210324 end
								if (!v_MCdetMap.containsKey(prd.MDM_Model_No__c + ast.SerialNumber)) {
									Maintenance_Contract_Asset__c v_MCdet = new Maintenance_Contract_Asset__c();
									//v_MCdet.Name = ast.SerialNumber;
									v_MCdet.V_MC_Name__c = InquiryNoStr;
									//v_MCdet.Backorder__c = String.isBlank(infoH.SoNo) ? null : boMap.get(infoH.SoNo);
									v_MCdet.Return_Flag__c = tempReturnFlg;
									v_MCdet.DeliveryDate__c = NFMUtil.parseStr2Date(infoH.DeliveryDate);
									v_MCdet.Asset_SerialNumber__c = ast.SerialNumber;
									if (String.isNotBlank(dnInfo.ServicePrice)) {
										// 20210108 gzw add 虚拟合同号追加 start
										// v_MCdet.No_discount__c = Decimal.valueOf(dnInfo.ServicePrice.trim());
										// ast.No_discount__c = Decimal.valueOf(dnInfo.ServicePrice.trim());
										Decimal nodiscount = Decimal.valueOf(dnInfo.ServicePrice.trim());
										v_MCdet.No_discount__c = oppMap.get(InquiryNoStr).Trade__c == '内貿'?
										                         nodiscount : nodiscount * Decimal.valueOf(Label.Account_Exc) * Decimal.valueOf(Label.Account_Rate);
										// 20210108 gzw add 虚拟合同号追加 end
									}
									// if (String.isNotBlank(dnInfo.GuaranteePrice)) {
									//     v_MCdet.Asset_GuaranteePrice__c = Decimal.valueOf(dnInfo.GuaranteePrice);
									// }
									insertv_MCdetlList.add(v_MCdet);
									vmcCount++;
								}
							}
						}
						ast.Product2Id                       = prdsMap.get(dnInfo.OTCode).Id;
						//ast.Quantity                         = String.isBlank(dnInfo.VALUE) ? null : Decimal.valueOf(dnInfo.VALUE);
						ast.SLMark__c                        = 'Serial Number';         // 固定 dnInfo.SorLMark;
						//ast.Guarantee_period_for_products__c = NFMUtil.parseStr2Date(dnInfo.GuaranteePeriod);
						if (String.isNotBlank(dnInfo.GuaranteePeriod)) {
							if (dnInfo.GuaranteePeriod.trim().length() == 2) {
								ast.New_logic_data__c            = true;
								ast.Guarantee_period_year__c     =  dnInfo.SorLMark == 'L' ? 0 : Decimal.valueOf(dnInfo.GuaranteePeriod);
							} else {
								ast.Guarantee_period_for_products__c = NFMUtil.parseStr2Date(dnInfo.GuaranteePeriod);
							}
							//ast.Guarantee_period_year__c     =  dnInfo.SorLMark == 'L' ? 0 :Decimal.valueOf(dnInfo.GuaranteePeriod);
						} else {
							ast.New_logic_data__c            = true;
						}
						if (String.isNotBlank(dnInfo.ProvistonPeriod)) {
							ast.ProvistonPeriod__c     =  dnInfo.SorLMark == 'L' ? 0 : Decimal.valueOf(dnInfo.ProvistonPeriod);
						}
						if (String.isNotBlank(dnInfo.GuaranteePrice)) {
							// 20210108 gzw add 虚拟合同号追加 start
							// ast.Asset_GuaranteePrice__c = Decimal.valueOf(dnInfo.GuaranteePrice.trim());
							Decimal gPrice = Decimal.valueOf(dnInfo.GuaranteePrice.trim());
							ast.Asset_GuaranteePrice__c = oppMap.get(InquiryNoStr).Trade__c == '内貿'?
							                              gPrice : gPrice * Decimal.valueOf(Label.Account_Exc);
							// 20210108 gzw add 虚拟合同号追加 start
						}
						// WLIG-CCT9UG 20220512 lt start
						//ast.warrantyType__c                  = dnInfo.GuaranteeType;
						ast.warrantyType__c                  = NFMUtil.getMapValue(transferMap, 'warrantyType__c', string.valueof(dnInfo.GuaranteeType), iflog);
						// WLIG-CCT9UG 20220512 lt end
						if (String.isNotBlank(dnInfo.MaintenancePrice)) {
							// 20210108 gzw add 虚拟合同号追加 start
							Decimal mPrice = Decimal.valueOf(dnInfo.MaintenancePrice.trim());
							ast.Maintenance_Price_Year__c = oppMap.get(InquiryNoStr).Trade__c == '内貿'?
							                                mPrice : mPrice * Decimal.valueOf(Label.Account_Exc) * Decimal.valueOf(Label.Account_Rate);
							// 20210108 gzw add 虚拟合同号追加 start
						}
						if (String.isNotBlank(dnInfo.ServicePrice)) {
							// 20210108 gzw add 虚拟合同号追加 start
							// ast.No_discount__c = Decimal.valueOf(dnInfo.ServicePrice.trim());
							Decimal nodiscount = Decimal.valueOf(dnInfo.ServicePrice.trim());
							ast.No_discount__c = oppMap.get(InquiryNoStr).Trade__c == '内貿'?
							                     nodiscount : nodiscount * Decimal.valueOf(Label.Account_Exc) * Decimal.valueOf(Label.Account_Rate);
							// 20210108 gzw add 虚拟合同号追加 end
						}
						ast.TracingCode__c                   = dnInfo.TracingCode;
						ast.Guaranteen_end__c                = NFMUtil.parseStr2Date(dnInfo.ValidTo);
						ast.Barcode__c                       = dnInfo.Barcode;
						ast.IF_Information_From__c           = true;
						// HHOA-AGN2EH start
						ast.Return_Flag__c = false;
						ast.Delete_Flag__c = false;

						// SWAG-BDV589 start
						if (infoH.ReturnMark == '3') {
							if (OppNumberAndProductCodetoQISMap.containskey(tempInquiryNo + ':' + dnInfo.OTCode)) {
								list<QIS_Report__c> tempQISList =
									OppNumberAndProductCodetoQISMap.get(tempInquiryNo + ':' + dnInfo.OTCode);
								if (tempQISList.size() > 0) {
									QIS_Report__c tempQIS = tempQISList.remove(0);
									tempQIS.ReplaceDeliveryDate__c =
										NFMUtil.parseStr2Date(infoH.DeliveryDate);
									allUpdateQISList.add(tempQIS);
								}

							}
						}
						// SWAG-BDV589 end
						if (clearflg == true) {
							ast.InstallDate = null;
						}
						// HHOA-AGN2EH end
					}
				}
				if (vmcCount > 0) {
					Maintenance_Contract__c vmc = v_MCMap.get(InquiryNoStr);
					if (vmc == null) {
						vmc = new Maintenance_Contract__c();
						vmc.Name = accsMap.get(infoH.EndUserNo).Name + '多年保修';
						vmc.Status__c = '契約';
						//vmc.DeliveryDate__c = NFMUtil.parseStr2Date(infoH.DeliveryDate);
						//vmc.DeliveryNote__c = infoH.DeliveryNote;
						vmc.Department__c = accsMap.get(infoH.DepartmentNo).Id;
						vmc.Department_Class__c = accsMap.get(infoH.DepartmentNo).Department_Class__c;
						//vmc.ReturnMark__c = infoH.ReturnMark;
						vmc.Hospital__c = accsMap.get(infoH.EndUserNo).Id;
						vmc.Opportunity__c = oppMap.get(InquiryNoStr).Id;
						// 如果询价中有经销商信息，自动带出 2019/09/25 修改
						if (String.isNotBlank(oppMap.get(InquiryNoStr).Agency1__c)) {
							vmc.Estimate_Target__c = '经销商';
							vmc.Dealer__c = oppMap.get(InquiryNoStr).Agency1__c;
						}
						vmc.RecordTypeId = System.Label.VM_ContractType;
						// gzw 对应多年保合同生成后，合同状态直接结束问题 start
						vmc.Contract_End_Date__c = Date.today().addDays(1);
						// gzw 对应多年保合同生成后，合同状态直接结束问题 end
						v_MCtempMap.put(InquiryNoStr, vmc);
					}
				}

			}
			if (returnv_MCdetlList.size() > 0) {
				update returnv_MCdetlList;
			}
			// HHOA-AGN2EH 先退后发
			if (astDelList.size() > 0) {
				//delete astDelList;
				// TODO 今後 返品設備の科室に移動する可能性がある
				// TODO 消耗品の出荷 return があるか？
				for (Asset ast : astDelList) {
					ast.Return_Flag__c = true;
					ast.Delete_Flag__c = true;
					// HHOA-AGN2EH start
					ast.Hospital__c = olympus.Id;                      //'Olympus社内'
					ast.Department_Class__c = olympus_return.ParentId; //'Olympus社内 其他'
					ast.AccountID = olympus_return.Id;                 //'Olympus社内 其他 退货'
					ast.Order_No__c = '';
					// CHAN-CCR6MW gzw 【委托】【保有设备】保有设备发货日逻辑 start
					// ast.Posting_Date__c = null;
					ast.Posting_Date__c = Date.today();
					// CHAN-CCR6MW gzw 【委托】【保有设备】保有设备发货日逻辑 end
					ast.DeliveryNote__c = '';
					ast.InstallDate = null;
					ast.Guarantee_period_for_products__c = null;
					ast.Install_Account_Name__c = '';
					ast.Install_Account_Code__c = '';
					ast.Install_Hospital_code__c = '';
					ast.Install_Hospital_Name__c = '';
					// HHOA-AGN2EH end
				}
				update astDelList;
			}
			if (astList.size() > 0) {
				//add by rentx 20210621 start
				Map<String,Asset> tempMap = new Map<String,Asset>();
				Integer a = 0;
				System.debug('2402: datestr:::'+datestr);
				System.debug('2402: astList:::'+astList.size());
				for (Asset ass : astList) {
					String assStr = ass.SerialNumber;
					tempMap.put(ass.SerialNumber, ass);
				}
				astList = tempMap.values();
				System.debug('2415::::'+tempMap.values());
				System.debug('2416::::'+tempMap.size() );
				//add by rentx 20210621 end
				upsert astList;
			}
			//CHAN-BBLAAP start

			// key 为 SerialNumber， value 为保有设备的ID
			Map<string, string> upsertAstMap = new  Map<string, string>();
			for (Asset tempAst : astDelList) {
				upsertAstMap.put(tempAst.SerialNumber, tempAst.id);
			}
			for (Asset tempAst : astList) {
				upsertAstMap.put(tempAst.SerialNumber, tempAst.id);
			}
			//CHAN-BBLAAP end

			//明细2直接到货，再入库更新
			if (odDetailUpsertMap.size() > 0) {
				upsert odDetailUpsertMap.values();
			}
			// 消耗品订单更新，最新发货日、记录类型
			if (oUpdateMap.size() > 0) {
				update oUpdateMap.values();
			}
			// 消耗品明细2更新
			if (odUpsertMap.size() > 0) {
				upsert odUpsertMap.values();
			}
			//直销耗材 明细2
			if (odDSUpsertMap.size() > 0) {
				upsert odDSUpsertMap.values();
			}
			//直销耗材 返品单、出库单新建
			if (orderOutMap.size() > 0) {
				insert orderOutMap.values();
				for (Consumable_order__c co : orderOutMap.values()) {
					orderReturnIdList.add(co.Id);
				}
			}

			// 自动生成出库单信息
			if (odDSUpsertIdxMap.size() > 0) {
				addReturnOrderAuto(odDSUpsertIdxMap);
			}

			// SWAG-BDV589 start
			if (allUpdateQISList.size() > 0) {
				update allUpdateQISList;
			}
			// SWAG-BDV589 end

			// 生成新的虚拟维修合同
			if (v_MCtempMap.size() > 0) {
				insert v_MCtempMap.values();
				v_MCMap.putAll(v_MCtempMap);
			}

			if (insertv_MCdetlList.size() > 0) {
				for (Maintenance_Contract_Asset__c vma : insertv_MCdetlList) {
					if (vma.Return_Flag__c) continue;
					vma.Maintenance_Contract__c = v_MCMap.get(vma.V_MC_Name__c).Id;
					vma.Asset__c = upsertAstMap.get(vma.Asset_SerialNumber__c);

					//add by rentx 20210621 start 上面为保有设备赋值的操作不需要删除 只有SerialNoorLotNo为.时保有设备的SerialNumber才会以当前日期开头
					String tempstr = vma.Asset_SerialNumber__c;
					if (tempstr.startsWith(odatestr)) {
						vma.Asset__c = upsertAstMap.get(odatestr);
					}
					//add by rentx 20210621 end
				}
				upsert insertv_MCdetlList;
			}


			logstr += '\nend';
			rowData.retry_cnt__c = 0;
			rowData.IsUpsertDN__c = true;
		} 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.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(!Test.isRunningTest()) LogAutoSendSchedule.assignOneMinute();
			}
			if (rowData.retry_cnt__c >= batch_retry_max_cnt) {
				rowData.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + rowData.ErrorLog__c + '错误次数已经超过自动收信设定的最大次数，请手动收信';
			}
		}
		update rowData;
		// gzw 20211207 追溯跳过ZM16 start
		if(!Test.isRunningTest()){
			DNUpsertSchedule.assignOneMinute();
		}
		// DNUpsertSchedule.assignOneMinute();
		// gzw 20211207 追溯跳过ZM16 end
		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
		List<Consumable_order_details2__c> updDetail2List = new List<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;
				}
				updDetail2List.add(dtl2);
				i++;
			}
		}
		update updDetail2List;
	}

	private static Map<String, String> addressNameApiMap = new Map<String, String> {
		'湖南省' => '0011000000V9SLSAA3',
		'四川省' => '0011000000V9SLSAA3',
		'广东省' => '0011000000V9SLSAA3',
		'贵州省' => '0011000000V9SLSAA3',
		'云南省' => '0011000000V9SLSAA3',
		'广西自治区' => '0011000000V9SLSAA3',
		'深圳市' => '0011000000V9SLSAA3',
		'湖北省' => '0011000000V9SLSAA3',
		'重庆市' => '0011000000V9SLSAA3',
		'北京市' => '0011000001HfVL2AAN',
		'吉林省' => '0011000001HfVL2AAN',
		'大连市' => '0011000001HfVL2AAN',
		'黑龙江省' => '0011000001HfVL2AAN',
		'内蒙古' => '0011000001HfVL2AAN',
		'山东省' => '0011000001HfVL2AAN',
		'甘肃省' => '0011000001HfVL2AAN',
		'青岛市' => '0011000001HfVL2AAN',
		'辽宁省' => '0011000001HfVL2AAN',
		'河北省' => '0011000001HfVL2AAN',
		'山西省' => '0011000001HfVL2AAN',
		'天津市' => '0011000001HfVL2AAN',
		'新疆自治区' => '0011000001HfVL2AAN',
		'陕西省' => '0011000001HfVL2AAN',
		'青海省' => '0011000001HfVL2AAN',
		'宁夏自治区' => '0011000001HfVL2AAN',
		'河南省' => '0011000001HfVL2AAN',
		'浙江省' => '0011000000V9SLTAA3', // 上线前修改
		'安徽省' => '0011000000V9SLTAA3',
		'江西省' => '0011000000V9SLTAA3',
		'福建省' => '0011000000V9SLTAA3',
		'江苏省' => '0011000000V9SLTAA3',
		'上海市' => '0011000000V9SLTAA3'
	};

	// CHAN-AXQBDY: 传过来的机身号最后5位都是字母并且倒数6,7,8位是052, SFDC删除机身号的最后8位
	private static String checkSerialNoorLotNo(String sn) {
		if (sn == null || sn == '' || sn.length() < 8) {
			return sn;
		}
		String regEx = '[a-zA-Z]';
		Pattern pattern = Pattern.compile(regEx);
		boolean strCheck = true;
		boolean numCheck = true;
		for (Integer i = 0; i < 8; i++) {
			String s = sn.substring(sn.length() - i - 1, sn.length() - i);
			if (i < 5) {
				Matcher matcher = pattern.matcher(s);
				if (!matcher.matches()) {
					strCheck = false;
					break;
				}
			} else {
				if (i == 5) {
					if (s != '0') {
						numCheck = false;
						break;
					}
				} else if (i == 6) {
					if (s != '5') {
						numCheck = false;
						break;
					}
				} else if (i == 7) {
					if (s != '2') {
						numCheck = false;
						break;
					}
				}
			}
		}
		if (strCheck && numCheck) {
			return sn.substring(0, sn.length() - 8);
		}
		return sn;
	}
}