public with sharing class lexPCLLostReportLwcController {



	public static string oppId { get; set; }
	
	public static string lostReportId { get; set; }
	// 当前页面状态 Create,View and Edit, MarketEdit
	
	public static string pageStatus { get; set; }
	// 失单，部分失单
	
	public static string lostType {get; set;}
	public  static Set<ID> deleteBrandIDSet = new Set<ID>();
	
	public static string submitFlag {get; set;}
	
	public static LostReport LostReport {get; set;}
	
	public static integer brandNo {get; set;}
	
	public static integer brandCount {get; set;}
	// add tcm 20211122 start
	
	
	// add tcm 20211122 end
	
	@AuraEnabled(cacheable=true)
	  public static Id getUserProfileId() {
		Id profileId = [SELECT ProfileId FROM User WHERE Id = :UserInfo.getUserId()].ProfileId;
		return profileId;
	  }
	@AuraEnabled
	  public static String getPickList(String objectName, String fieldName) {
	  List<Map<String, String>> lstPickvals = new List<Map<String, String>>();
		List<Schema.DescribeSobjectResult> results = Schema.describeSObjects(new List<String>{objectName});
		
		for(Schema.DescribeSobjectResult res : results) {
		  for (Schema.PicklistEntry entry : res.fields.getMap().get(fieldName).getDescribe().getPicklistValues()) {
			if (entry.isActive()) {
			  lstPickvals.add(new Map<String, String>{'label' => entry.getValue(), 'value' => entry.getValue()});
			}
		  }
		}
	  Map<string,List<Map<String, String>>> pickList =  new Map<string,List<Map<String, String>>>();
	  List<Map<String, String>> zhuji = new List<Map<String, String>>();
	  List<Map<String, String>> jingzi = new List<Map<String, String>>();
	  List<Map<String, String>> xixiaoji = new List<Map<String, String>>();
	  List<Map<String, String>> guangyuan = new List<Map<String, String>>();
	  List<Map<String, String>> xiaojingzhong = new List<Map<String, String>>();
	  List<Map<String, String>> nengliang = new List<Map<String, String>>();
	  List<Map<String, String>> qita = new List<Map<String, String>>();
	  Map<String, String> empty = new Map<String, String>{'label' => '--无--', 'value' => ''};
	  zhuji.add(empty);
	  jingzi.add(empty);
	  xiaojingzhong.add(empty);
	  nengliang.add(empty);
	  qita.add(empty);
	  for (Integer i = 0; i < lstPickvals.size(); i++) {
	  if ((i >= 0 && i <= 6) || i == 38) {
		zhuji.add(lstPickvals[i]);
	  }
	  if ((i >= 7 && i <= 23) || i == 38) {
		jingzi.add(lstPickvals[i]);
	  }
	  if ((i >= 24 && i <= 29) || i == 35|| i == 38) {
		xiaojingzhong.add(lstPickvals[i]);
	  }
	  if ((i >= 30 && i <= 34) || i == 38) {
		nengliang.add(lstPickvals[i]);
	  }
	  if (i == 36) {
		guangyuan.add(lstPickvals[i]);
	  }
	  if (i == 37) {
		xixiaoji.add(lstPickvals[i]);
	  }
	  if (i == 38) {
		qita.add(lstPickvals[i]);
	  }
	  }
	  pickList.put('主机', zhuji);
	  pickList.put('镜子', jingzi);
	  pickList.put('小镜种', xiaojingzhong);
	  pickList.put('能量', nengliang);
	  pickList.put('洗消机', xixiaoji);
	  pickList.put('光源', guangyuan);
	  pickList.put('其他', qita);
	  pickList.put('全部',lstPickvals);
		return JSON.serialize(pickList);
	  }
	@AuraEnabled
	public static Map<string,object> init (string oppId1,string lostReportId1,string pageStatus1,string lostType1,string submitFlag1){
	  try {
	  oppId = oppId1;
	  lostReportId = lostReportId1;
	  pageStatus = pageStatus1;
	  lostType = lostType1;
	  submitFlag = submitFlag1;
	  return init1();
	  } catch (Exception e) {
	  return new Map<string,object>();
	  }
	}
	// 初始化
	public static Map<string,object> init1(){
	  Map<string,object> maps = new Map<string,object>();
	  if(string.isblank(pageStatus)) {
	  // 这里需要报错没有传参数
	  maps.put('message', '页面出错，请刷新后重试！');
	  return maps;
	  }
	  else if(pageStatus.equals('Create')) {
	  if(string.isBlank(oppId)) {
		// 这里报错创建时候必须有询价
		maps.put('message', '创建失单报告时，请重询价页面创建');
		return maps;
	  }
	  list<opportunity> opplist =
	  [select id,Name,
	   Sales_assistant_ID__c,
	   //chenjingwu 20231108 Start
	   StageName,
	   //chenjingwu 20231108 End
	   Sales_manager_departmentID__c,Sales_owner_buchangID__c
	   from opportunity
	   where id =: oppId
			limit 1];
	  if( opplist.size() == 0) {
		pageStatus = null;
		maps.put('message', '您没有询价的查看权限，无法创建失单报告！');
		return maps;
	  }
	  Schema.DescribeSObjectResult s = Lost_cancel_report__c.sObjectType.getDescribe();
	  if( !s.isCreateable()) {
		maps.put('message', '您不能创建失单/部分失单报告！');
		return maps;
	  }
	  Lost_cancel_report__c tempLostReport =
		new Lost_cancel_report__c(LostType__c= lostType,
					Opportunity__c = oppId,
					Sales_assistant__c = opplist[0].Sales_assistant_ID__c,
					Manager_sales__c = opplist[0].Sales_manager_departmentID__c,
					Buchang_sales__c = opplist[0].Sales_owner_buchangID__c,
					Submit_Day__c = date.today(),
					Report_Status__c = '草案');
	  LostReport = new LostReport(tempLostReport);
	  brandCount = 1;
	  //chenjingwu 20231108 Start
	  RecordType recordType1 = [select Id from RecordType where Name = '询价取消报告'];
		  List<Lost_cancel_report__c> lostList = [select Id from Lost_cancel_report__c where Opportunity__c =: oppId and RecordTypeId !=: recordType1.Id];
	  List<Lost_cancel_report__c> cancelList = [select Id from Lost_cancel_report__c where Opportunity__c =: oppId and RecordTypeId =: recordType1.Id and Report_Status__c != '草案'];
	  if(lostList.size() > 0){
		maps.put('message', '该询价已有失单报告');
		return maps;
	  }
	  if(cancelList.size() > 0){
		maps.put('message', '已经有提交的取消报告，不可新建失单报告');
		return maps;
	  }
	  //chenjingwu 0116 start
	  Id systemManger =  (ID)System.label.lexPcl_1;
	  if(userinfo.getProfileId() == systemManger){
		LostReport.isManger = true;
	  }
	  //chenjingwu 0116 end
	  if(opplist[0].StageName == '注残' || opplist[0].StageName == '出荷' || opplist[0].StageName == '完了'){
		LostReport.isPartOfLost = true;
	  }
	  //chenjingwu 20231108 End
	  }
	  else if(pageStatus.equals('View') ||  pageStatus.equals('Edit')) {
	  system.debug('edit1');
	  if(string.isBlank(lostReportId)) {
		pageStatus = null;
		maps.put('message', '您没有查看这个失单/部分失单报告的权限！');
		return maps;
	  }
	  // //chenjingwu 20231108 Start
	  // list<opportunity> opplist =
	  // [select id,Name,
	  //  Sales_assistant_ID__c,
	  //  StageName,
	  //  Sales_manager_departmentID__c,Sales_owner_buchangID__c
	  //  from opportunity
	  //  where id =: oppId
	  //       limit 1];
	  // if(opplist[0].StageName == '注残' || opplist[0].StageName == '出荷' || opplist[0].StageName == '完了'){
	  //   LostReport.isPartOfLost = true;
	  // }
	  // //chenjingwu 20231108 Start      
	  system.debug('edit2');
	  list<Lost_cancel_report__c> lostReportList =
	  [select id,of_lost_system_processor__c,
	   Lost_reason_main__c,
	   Lost_Reason_Sub__c,Lost_By_Company__c,
	   LostTotalAmount__c,LostType__c,
	   Report_Status__c,Sales_assistant__c,
	   TotalAmountLost__c,
	   InclusionUltrasound__c, //20230506 lt DB202304618804  包含超声
	   ModifyAfterApproval__c,Approved_Day__c,//20230814 lt DB202308068183 失单报告审批节点增加助理审批节点 add
	   Opportunity__c, Opportunity__r.Sales_assistant_ID__c,
	   //chenjingwu 20231108 Start
	   Opportunity__r.StageName,
	   //chenjingwu 20231108 End
	   Opportunity__r.Sales_manager_departmentID__c,
	   Manager_sales__c,recordtypeid,recordtype.DeveloperName
	   from Lost_cancel_report__c
	   where id =: lostReportId limit 1];
	  System.debug('chenjingwu' + lostReportList);
	  if(lostReportList.size() == 0) {
		pageStatus = null;
		maps.put('message', '您没有查看这个失单/部分失单报告的权限！');
		return maps;
	  }
	  lostReportList[0].Sales_assistant__c =
		lostReportList[0].Opportunity__r.Sales_assistant_ID__c;
	  lostReportList[0].Manager_sales__c =
		lostReportList[0].Opportunity__r.Sales_manager_departmentID__c;
	  if(lostReportList[0].recordtype.DeveloperName.equals('PCL_Lost_report')) {
		lostReportList[0].LostType__c ='失单';
	
	  }else if(lostReportList[0].recordtype.DeveloperName.equals('PCL_PartLost_report')) {
		lostReportList[0].LostType__c ='部分失单';
	  }
	  // 权限，如果当前状态不是草案中，那么需要跳转到只读页面
	  //原：!'草案'.equals(lostReportList[0].Report_Status__c) && userinfo.getProfileId() != (ID) '00e10000000Y3o5AAC'
	
	  // 20230814 lt DB202308068183 失单报告审批节点增加助理审批节点 end 改if条件
	  Id systemManger =  (ID)System.label.lexPcl_1;
	  Id system2S1 = (ID)System.label.lexPcl_2;
	  Id system2S6 = (ID)System.label.lexPcl_3;
	  Id system2S4 = (ID)System.label.lexPcl_4;
	  if(
	  !('草案'.equals(lostReportList[0].Report_Status__c) 
	  || userinfo.getProfileId() == systemManger
	  ||('批准'.equals(lostReportList[0].Report_Status__c) && 
		(userinfo.getProfileId() == system2S1 ||
		userinfo.getProfileId() == system2S6 ||
		userinfo.getProfileId() == system2S4))
	  )
	  ){
		pageStatus = 'View';
	  }
	  oppId = lostReportList[0].Opportunity__c;
	  system.debug('edit3');
	  list<PCLLostBrand__c> selectlostBrandList =
	  [
		select id, LostPrice__c, Lost_By_Company__c,
		Lost_reason_main__c,Lost_Reason_Sub__c,Name,Agency__c, AgencyMannual__c,
		Lost_cancel_report__c,Lost_By_Company_Mannual__c,ChannelSpecificReasons__c,
		( select id,PCLLostBrand__c,LostProduct__c,
		isSpec__c,
		LostProduct__r.Name,
		LostProductMannual__c,            //SWAG-C6P9PX lt 20210913 add
		ProductCategory__c,
		//chenjingwu 20231109 Start
		LostProduct__r.isDomestic__c,
		//chenjingwu 20231109 End
			//chenjingwu 20231225 Start
			Function__c,
			//chenjingwu 20231225 End
		ProductClass__c, //add tcm 20211123
		Quantity__c,Name, LostBrandName__c 
		from PCLLostBrand__c.PCLLostBrandProduct__r)
		from PCLLostBrand__c
		where Lost_cancel_report__c =: lostReportId
	  ];
	  if(selectlostBrandList.size() == 0 ) {
		LostReport = new LostReport(lostReportList[0]);
		brandCount = 1;
	  }else{
		system.debug('edit4:'+selectlostBrandList[0]);
		brandCount = 0;
		list<LostBrand> LostBrandList = new list<LostBrand>();
		for(PCLLostBrand__c templostBrand : selectlostBrandList) {
		list<PCLLostProducts> tempProductList = new list<PCLLostProducts>();
		integer productCount = 0;
		system.debug('check products:'+ (templostBrand.PCLLostBrandProduct__r != null) + '|' + (templostBrand.PCLLostBrandProduct__r.size() > 0));
		if (templostBrand.PCLLostBrandProduct__r != null && templostBrand.PCLLostBrandProduct__r.size() > 0) {
		  for( PCLLostProduct__c tempProduct: templostBrand.PCLLostBrandProduct__r) {
		  PCLLostProducts pro = new PCLLostProducts(productCount,tempProduct);
		  if(tempProduct.LostProduct__r.Name != null){
			pro.productName = tempProduct.LostProduct__r.Name;
		  }
				//chenjingwu 20231225 Start
				if(tempProduct.ProductCategory__c == 'SP主机'){
					pro.gongNengFlag = true;
				}
				//chenjingwu 20231225 End
		  //chenjingwu 20231109 Start
		  // if(tempProduct.LostProduct__r.isDomestic__c == '进口' ||  tempProduct.LostProduct__r.isDomestic__c == '' || tempProduct.LostProduct__r.isDomestic__c == null){
		  //   pro.isJinKou = true;
		  // }
		  if(tempProduct.LostProduct__r.isDomestic__c == false){
			pro.isJinKou = true;
		  }
		  //chenjingwu 20231109 Start
		  tempProductList.add(pro);
		  productCount++;
		  }
		} else {
		  PCLLostProducts newProduct = new PCLLostProducts();
		  if ('其他'.equals(templostBrand.Lost_By_Company__c) && 
		  templostBrand.Lost_By_Company_Mannual__c != null && 
		  !''.equals(templostBrand.Lost_By_Company_Mannual__c)) {
			newProduct.LostProductss.LostBrandName__c = templostBrand.Lost_By_Company_Mannual__c;
		  } else {
			newProduct.LostProductss.LostBrandName__c = templostBrand.Lost_By_Company__c;
		  }
		  system.debug('aaa4+++'+templostBrand.Lost_By_Company_Mannual__c);
		  
		  tempProductList.add(newProduct);
		  productCount++;
		}
		LostBrand br = new LostBrand(brandCount,tempProductList, templostBrand);
		// chenjingwu 20240118 start
		for(PCLLostProducts pro:tempProductList){
			if(true == pro.gongNengFlag){
				br.brandGongNengFlag = true;
			}
		}
		// chenjingwu 20240118 end
			//chenjingwu 20231221 start
			// if(tempLostBrand.ChannelSpecificReasons__c != null){
			//   br.reasonFlag = true;
			// }
			if(tempLostBrand.ChannelSpecificReasons__c != null ||tempLostBrand.Lost_reason_main__c == '渠道因素' || tempLostBrand.Lost_Reason_Sub__c == '渠道因素'){
		  br.reasonFlag = true;
		}
			//chenjingwu 20231221 end
		LostBrandList.add(br);
		brandCount++;
		}
	
		LostReport = new LostReport(lostReportList[0],LostBrandList);
		system.debug('LostReport.LostBrands:'+LostReport.LostBrands);
	  }
	  //chenjingwu 0116 start
	  Id systemManger1 =  (ID)System.label.lexPcl_1;
	  if(userinfo.getProfileId() == systemManger1){
		LostReport.isManger = true;
	  }
	  //chenjingwu 0116 end
	  //chenjingwu 20231108 Start
	  if(lostReportList[0].Opportunity__r.StageName == '注残' || lostReportList[0].Opportunity__r.StageName == '出荷' || lostReportList[0].Opportunity__r.StageName == '完了'){
		LostReport.isPartOfLost = true;
	  }
	  //chenjingwu 20231108 End
	  }
	  brandNo = 0;
	  // 读取竞争对手品牌
	  // BrandmapSet();
	  
	  if (lostReportId != null) {
	  // List<ProcessInstance> pros = [
	  // SELECT 
	  // ProcessDefinition.Name,
	  //   (
	  //   SELECT 
	  //   Id,
	  //   StepStatus, 
	  //   IsPending,
	  //   Comments,
	  //   CreatedDate,
	  //   Actor.Name,  
	  //   OriginalActor.Name,
	  //   ProcessNode.Name FROM StepsAndWorkitems order by IsPending DESC, CreatedDate DESC 
	  // )
	  // FROM ProcessInstance where TargetObjectId =:LostReport.lostReport.id order by CreatedDate DESC
	  // ];
	  // List<ProcessInstanceHistory> items = new List<ProcessInstanceHistory>();
	  // for(ProcessInstance pro: pros){
	  //   items.add(pro.StepsAndWorkitems);
	  // }
	  // LostReport.approvalHistorys = items;
	  List<ProcessInstance> pros = [
	  SELECT 
	  ProcessDefinition.Name,
		(
		SELECT 
		Id,
		StepStatus, 
		IsPending,
		Comments,
		CreatedDate,
		Actor.Name,  
		OriginalActor.Name,
		ProcessNode.Name FROM StepsAndWorkitems order by IsPending DESC, CreatedDate DESC 
	  )
	  FROM ProcessInstance where TargetObjectId =:LostReport.lostReport.id order by CreatedDate DESC
	  ];
	  if(pros.size() > 0){
		
		List<ProcessInstanceHistory> items = new List<ProcessInstanceHistory>();
		maps.put('allowUserId',pros[0].StepsAndWorkitems[0].Actor.Id);
		maps.put('userProfileId',UserInfo.getProfileId());
		for(ProcessInstance pro: pros){
		items.addAll(pro.StepsAndWorkitems);
		}
		for(ProcessInstanceHistory pro: pros[0].StepsAndWorkitems){
		if(pro.StepStatus == 'Started'){
		  maps.put('submitUserId',pro.ActorId);
		}
		}
		LostReport.approvalHistorys = items;
	  }else{
		List<ProcessInstanceHistory> items = new List<ProcessInstanceHistory>();
		LostReport.approvalHistorys = items;
	  }
	  
	  }else{
	  List<ProcessInstanceHistory> items = new List<ProcessInstanceHistory>();
	  LostReport.approvalHistorys = items;
	  }
	  if(string.isNotEmpty(submitFlag)) {
	  maps.put('message', '提交成功！');
	  maps.put('LostReport', LostReport);
	  return maps;
	
	  }
	  // List<Map<String,String>> col = new List<Map<String,String>>();
	  // Map<String,String> ele = new Map<String,String>();
	  // LostReport.LostBrands[0].columns.add();
	  maps.put('LostReport', LostReport);
	  maps.put('userId',UserInfo.getUserId());
	  return maps;
	}
	@AuraEnabled
	public static String searchBrands(){
	  String ObjectApi_name = 'PCLLostBrand__c';
	  String Field_name = 'Lost_By_Company__c';
		//From the Object Api name retrieving the SObject
		Schema.SObjectType targetType = Schema.getGlobalDescribe().get(ObjectApi_name);
		Sobject Object_name = targetType.newSObject();
		 //grab the sobject that was passed
		Schema.sObjectType sobject_type = Object_name.getSObjectType();
		//describe the sobject
		Schema.DescribeSObjectResult sobject_describe = sobject_type.getDescribe(); 
		 //get a map of fields for the passed sobject
		Map<String, Schema.SObjectField> field_map = sobject_describe.fields.getMap();
		//grab the list of picklist values for the passed field on the sobject
		List<Schema.PicklistEntry> pick_list_values = field_map.get(Field_name).getDescribe().getPickListValues(); 
		List<Map<String, Object>> lstPickvals = new List<Map<String, Object>>();
		for (Schema.PicklistEntry a : pick_list_values) 
		{ //for all values in the picklist list
	  lstPickvals.add(new Map<String, Object>{'label' => a.getValue(), 'value' => a.getValue()});
		}
	  String jsonStr = JSON.serialize(lstPickvals);
		return jsonStr;
	}
	@AuraEnabled
	public static string searchBatchIfForProduct(String productName){
	  try {
	  List<BatchIF_Transfer__c> transfer = [select
					Internal_value__c
					from BatchIF_Transfer__c
					where Dropped_Flag__c = false
						and Table__c = 'PCLLostBrand__c' and Column__c = 'Lost_By_Company__c' and External_value__c =: productName];
	  if(transfer.size() > 0){
		return transfer[0].Internal_value__c;
	  }else{
		return null;
	  }
	  
	  } catch (Exception e) {
	  return e.getMessage();
	  }
	}
	// 数据录入
	@AuraEnabled
	public static Map<String,String> dataEntry(String report1,List<Id> deleteBrandIdList,List<Id> deleteProductIdList){
	  // LostReport report = (LostReport)JSON.deserializeUntyped(report1, LostReport.class);
	  LostReport report = (LostReport)JSON.deserialize(report1, LostReport.class);
	  Map<String,String> messageMap = new Map <String,String>();
	  system.debug('save---start:');
	  Savepoint sp = Database.setSavepoint();
	  
	  // 待完成，这里需要把第一个品牌的信息赋值到这个失单报告上去，还有需要把各个品牌金额汇总加起来；
	  //system.debug('LostReport.LostBrands:'+LostReport.LostBrands);
	  // 设置记录类型
	  report.lostReport.recordTypeID  =  report.lostReport.LostType__c== '失单'?Schema.SObjectType.Lost_cancel_report__c.getRecordTypeInfosByDeveloperName().get('PCL_Lost_report').getRecordTypeId() : Schema.SObjectType.Lost_cancel_report__c.getRecordTypeInfosByDeveloperName().get('PCL_PartLost_report').getRecordTypeId();
	  report.lostReport.LostTotalAmount__c    = 0;
	  report.lostReport.of_lost_system_processor__c   = 0;
	  report.lostReport.TotalAmountLost__c    = 0;
	  report.lostReport.Lost_reason_main__c = null;
	  report.lostReport.Lost_Reason_Sub__c  = null;
	  report.lostReport.Lost_By_Company__c = null;
		//批准日不为空时给修改后再批准赋值
	  if(report.lostReport.Approved_Day__c != null){
		report.lostReport.ModifyAfterApproval__c = true;
	  }
	  for(LostBrand tempLostBrand : report.LostBrands) {
		if(string.isNotBlank(tempLostBrand.lostBrand.Lost_By_Company__c)) {
		report.lostReport.LostTotalAmount__c += tempLostBrand.lostBrand.LostPrice__c;
		Decimal med = tempLostBrand.lostBrand.LostPrice__c/1.13/1000;
		Decimal med1 = med.setScale(2);
		// System.debug('---lt123不含税数值(人工)Decimal---'+med);
		// System.debug('---lt123不含税数值(人工)Decimal两位小数---'+med1);
		report.lostReport.TotalAmountLost__c += med1;
		report.lostReport.Lost_reason_main__c =
		report.lostReport.Lost_reason_main__c == null
		  ? tempLostBrand.lostBrand.Lost_reason_main__c
		  : report.lostReport.Lost_reason_main__c;
		  report.lostReport.Lost_Reason_Sub__c  =
		  report.lostReport.Lost_Reason_Sub__c == null
		  ? tempLostBrand.lostBrand.Lost_Reason_Sub__c
		  : report.lostReport.Lost_Reason_Sub__c;
		  report.lostReport.Lost_By_Company__c =
		  report.lostReport.Lost_By_Company__c == null
		  ? tempLostBrand.lostBrand.Lost_By_Company__c
		  : report.lostReport.Lost_By_Company__c;
	
		for( PCLLostProducts tempLostProduct : tempLostBrand.LostProducts) {
		  if(tempLostProduct.LostProductss.Quantity__c !=null && tempLostProduct.LostProductss.Quantity__c >0) {
		  report.lostReport.of_lost_system_processor__c   += tempLostProduct.LostProductss.Quantity__c;
		  }
		}
		}
	  }
	  upsert report.lostReport;
	  String reportId = report.lostReport.Id;
	  messageMap.put('reportId', reportId);
	  // 需要插入更新的失单品牌
	  map<integer,PCLLostBrand__c> upsertLostBrandMap = new map<integer,PCLLostBrand__c>();
	  // 需要删掉的失单品牌
	  map<integer,PCLLostBrand__c> deleteLostBrandMap = new map<integer,PCLLostBrand__c>();
	  // 需要插入更新的失单型号，key是品牌编号+型号编号，value是需要更新的失单型号
	  map<string,PCLLostProduct__c> upsertLostProductMap = new map<string,PCLLostProduct__c>();
	  // 需要删掉的失单品牌
	  list<PCLLostProduct__c> deleteLostProductList = new list<PCLLostProduct__c>();
	  Integer lineNo = 0;
	  for(LostBrand tempLostBrand : report.LostBrands ) {
		// 如果有失单品牌，那么就要插入更新；
		system.debug('tempLostBrand.lostBrand.Lost_By_Company__c:'+tempLostBrand.lostBrand.Lost_By_Company__c);
		if(string.isNotBlank(tempLostBrand.lostBrand.Lost_By_Company__c)) {
		upsertLostBrandMap.put(lineNo,tempLostBrand.lostBrand);
		tempLostBrand.lostBrand.Lost_cancel_report__c = report.lostReport.Id;
		tempLostBrand.lostBrand.Name = tempLostBrand.lostBrand.Lost_By_Company__c;
		integer tempNo = 0;
		for( PCLLostProducts tempLostProduct : tempLostBrand.LostProducts) {
		  system.debug('Name:'+ tempLostProduct.LostProductss.Name );
		  if(tempLostProduct.LostProductss.Quantity__c !=null && tempLostProduct.LostProductss.Quantity__c >0) {
		  tempLostProduct.LostProductss.Name = tempLostBrand.lostBrand.Name + tempLostProduct.LostProductss.Quantity__c;
		  upsertLostProductMap.put(lineNo +':'+ tempNo,tempLostProduct.LostProductss);
		  }else if(string.isNotBlank(tempLostProduct.LostProductss.Id)) {
		  deleteLostProductList.add(tempLostProduct.LostProductss);
		  }
		  tempNo++;
		}
		}
		// 如果没有品牌，但是有id， 这样数据需要删除
		else if(string.isNotBlank(tempLostBrand.lostBrand.Id )) {
		deleteLostBrandMap.put(lineNo,tempLostBrand.lostBrand);
		// 这里可能需要也判断一下失单型号有没有需要删掉
		}
		lineNo++;
	  }
	  if(upsertLostBrandMap.size()>0) {
		upsert upsertLostBrandMap.values();
	  }
	  for( string productNo :upsertLostProductMap.keyset()) {
		PCLLostProduct__c tempLostProduct = upsertLostProductMap.get(productNo);
		integer brandNo = integer.valueof(productNo.split(':')[0]);
		tempLostProduct.PCLLostBrand__c = upsertLostBrandMap.get(brandNo).Id;
	  }
	  if(upsertLostProductMap.size()>0) {
		upsert upsertLostProductMap.values();
	  }
	  if(deleteLostBrandMap.size()>0) {
		delete deleteLostBrandMap.values();
		for(PCLLostBrand__c pcl: deleteLostBrandMap.values()) {
		pcl.Id = null;
		}
	  }
	  if (deleteProductIdList.size()>0) {
		database.delete(deleteProductIdList);
		
	  }
	  if (deleteBrandIdList.size()>0) {
		database.delete(deleteBrandIdList);
	  }
	  if(deleteLostProductList.size()>0) {
		delete deleteLostProductList;
		for(PCLLostProduct__c pclp: deleteLostProductList) {
		pclp.Id = null;
		}
	  }
	  if(deleteBrandIDSet.size() > 0) {
		list<id> tempdeleteIDlist = new list<id>();
		tempdeleteIDlist.addall(deleteBrandIDSet);
		database.delete(tempdeleteIDlist);
	
	  }
	
	  for(integer brandNumber =0; brandNumber< report.LostBrands.size(); brandNumber++) {
	
		LostBrand tempLostBrand = report.LostBrands.get(brandNumber);
		if(tempLostBrand.lostBrand.Id == null) {
		report.LostBrands.remove(brandNumber);
		brandNumber--;
		continue;
		}
		for(integer productNumber = 0; productNumber< tempLostBrand.LostProducts.size(); productNumber++) {
		PCLLostProducts tempLostProduct = tempLostBrand.LostProducts.get(productNumber);
		if(tempLostProduct.LostProductss.Id == null) {
		  tempLostBrand.LostProducts.remove(productNumber);
		  productNumber--;
		  continue;
		}
		}
	  }
	  
		List<ProcessInstance> pros = [
		SELECT 
		ProcessDefinition.Name,
		 (
		SELECT 
		Id,
		StepStatus, 
		IsPending,
		Comments,
		CreatedDate,
		Actor.Name,  
		OriginalActor.Name,
		ProcessNode.Name FROM StepsAndWorkitems order by IsPending DESC, CreatedDate DESC 
		)
		FROM ProcessInstance where TargetObjectId =:reportId order by CreatedDate DESC
		];
		List<ProcessInstanceHistory> items = new List<ProcessInstanceHistory>();
		for(ProcessInstance pro: pros){
		items.addAll(pro.StepsAndWorkitems);
		}
		if(items.size() > 0){
		report.approvalHistorys = items;
		}else{
		List<ProcessInstanceHistory> items1 = new List<ProcessInstanceHistory>();
		report.approvalHistorys = items1;
		}
		
	  
		
	  
	  // lostReportId = report.lostReport.id;
	  system.debug('save---end:');
	  messageMap.put('LostReport',JSON.serialize(report));
	  
	  return messageMap;
	}
	
	// 提交
	@AuraEnabled
	public static Map<string,Object> submit(String reportStatus,Boolean modifyAfterApproval,String reportId){
	  // LostReport report = (LostReport)JSON.deserialize(report1, LostReport.class);
	  Savepoint sp = Database.setSavepoint();
	  Map<string,Object> objs = new Map<string,Object>();
	  try{
	  Map<string,string> messages = new Map<string,string>();
	  if(!'草案'.equals(reportStatus) && modifyAfterApproval == false) {
	  messages.put('error', '只有在草案中才能提交申请！');
	  return messages;
	  }
	  //生产环境bug修改 陈京武 20231105 Start
	  Lost_Cancel_Report__c report1 = [
				  select
				  Opportunity__c
				  from Lost_Cancel_Report__c where Id =: reportId
			  ];
			  Opportunity opp = [
				  select
				  Cnt_Lost_cancel_report__c,
				  Cnt_Lost_cancel_Draft__c
				  from Opportunity where Id =: report1.Opportunity__c
			  ];
			  RecordType recordType1 = [select Id from RecordType where Name = '询价取消报告'];
			  List<Lost_cancel_report__c> repList = [select Id from Lost_cancel_report__c where Opportunity__c =: opp.Id and RecordTypeId =: recordType1.Id and Report_Status__c != '草案'];
			  if(repList.size() > 0){
		  messages.put('error', '已经有提交的取消报告，不可提交失单报告');
		  return messages;
			  }
		  //生产环境bug修改 陈京武 20231105 End
	  Lost_cancel_report__c report = new Lost_cancel_report__c();
	  report.Id = reportId;
	  report.Report_Status__c = '提交';
	  update report;
	  // Approval.ProcessSubmitRequest psr = new Approval.ProcessSubmitRequest();
	  // psr.setObjectId(reportId);
	  // Approval.ProcessResult submitResult = Approval.process(psr);
	  objs.put('uri', '/apex/PCLLostReportPage');
	  objs.put('Id', reportId);
	  objs.put('pageStatus', 'View');
	  objs.put('submitFlag', '1');
	  List<ProcessInstance> pros = [
		SELECT 
		ProcessDefinition.Name,
		 (
		SELECT 
		Id,
		StepStatus, 
		IsPending,
		Comments,
		CreatedDate,
		Actor.Name,  
		OriginalActor.Name,
		ProcessNode.Name FROM StepsAndWorkitems order by IsPending DESC, CreatedDate DESC 
		)
		FROM ProcessInstance where TargetObjectId =:reportId order by CreatedDate DESC
	  ];
	  
	  List<ProcessInstanceHistory> items = new List<ProcessInstanceHistory>();
	  for(ProcessInstance pro:pros){
		items.addAll(pro.StepsAndWorkitems);
	  }
	  
	  objs.put('approvalHistorys',items);
	  return objs;
	  }catch(DmlException e) {
	  Database.rollback(sp);
	  //生产环境bug修改 陈京武 20231105 Start
	  // if (e.getMessage().contains(',')) {
	  //   String exc = '' + e.getMessage();
	  //   Integer left = exc.indexOf(':') + 1;
	  //   Integer right = exc.lastIndexOf(':');
	  //   String str = exc.substring(left,right);
	  //   left = str.indexOf(',') +  1;
	  //   String newStr = str.substring(left);
	  //   objs.put('error',newStr);
	  //   return objs;
	  // }else {
	  //   objs.put('error',e.getMessage());
	  //   return objs;   
	  // }
	  objs.put('error',e.getDmlMessage(0));
	  return objs;
	  //生产环境bug修改 陈京武 20231105 End
	  }catch(Exception ex) {
	  objs.put('error',ex.getMessage());
	  return objs;
	  }
	}
	// +++++++++++++++++++++++++++++++++++++++++++++++++++++++
	@AuraEnabled
	public static LostBrand getNewLostBrand(Integer lineNo){
	  LostBrand lostBrand = null;
	  try {
	  //report.LostBrands.add(new LostBrand(report.LostBrands.size()));
	  lostBrand = new LostBrand(lineNo);
	  } catch (Exception e) {
	  System.debug(e.getMessage());
	  }
	  return lostBrand;
	}
	
	@AuraEnabled
	public static PCLLostProducts getNewLostProduct(Integer lineNo2){
	  PCLLostProducts pro = null;
	  try {
	  pro = new PCLLostProducts(lineNo2);
	  } catch (Exception e) {
	  System.debug(e.getMessage());
	  }
	  return pro;
	}
	
	// update tcm 20211125 添加型号时自动带出品牌 end
	// 页面的数据结构
	public class LostReport {
	  @AuraEnabled
	  public Lost_cancel_report__c lostReport { get; set; }
	  @AuraEnabled
	  public list<LostBrand> LostBrands { get; set; }
	  @AuraEnabled
	  public list<ProcessInstanceHistory> approvalHistorys { get; set; }
	  //chenjingwu 20231108 Start
	  @AuraEnabled
	  public Boolean isPartOfLost = false;
	  //chenjingwu 20231108 End
	  //chenjingwu 0116 start
	  @AuraEnabled
	  public Boolean isManger = false;
	  //chenjingwu 0116 end
	  public LostReport(){
	  lostReport = new Lost_cancel_report__c();
	  LostBrands = new list<LostBrand> {new LostBrand(0)};
	  approvalHistorys = new list<ProcessInstanceHistory>();
	  }
	  public LostReport(Lost_cancel_report__c lostReport){
	  this.lostReport = lostReport;
	  LostBrands = new list<LostBrand> {new LostBrand(0)};
	  approvalHistorys = new list<ProcessInstanceHistory>();
	  }
	  public LostReport(Lost_cancel_report__c lostReport,  list<LostBrand> LostBrands){
	  this.lostReport = lostReport;
	  this.LostBrands = LostBrands;
	  approvalHistorys = new list<ProcessInstanceHistory>();
	  }
	}
	
	public class LostBrand {
	  @AuraEnabled
	  public PCLLostBrand__c lostBrand;
	  @AuraEnabled
	  public Boolean isGuoChan;
	  @AuraEnabled
	  public Integer lineNo;
	  @AuraEnabled
	  public list<PCLLostProducts> LostProducts;
	  @AuraEnabled
	  public Integer ProductSize;
	  @AuraEnabled
	  public Boolean reasonFlag = false;
	  @AuraEnabled
	  public String brandTitle;
	  //chenjingwu 20230117 start
	  @AuraEnabled
	  public Boolean brandGongNengFlag;
	  //chenjingwu 20230117 end
	  //chenjingwu 20231107 Start
	  @AuraEnabled
	  public List<Map<String, String>> reasonOptions = new List<Map<String, String>>(); 
	  //chenjingwu 20231107 End
	  public LostBrand( integer lineNo ){
	  lostBrand = new PCLLostBrand__c();
	  this.lineNo = lineNo;
	  this.brandTitle = '失单品牌' + (lineNo + 1);
	  LostProducts = new list<PCLLostProducts> {new PCLLostProducts()};
	  ProductSize = 1;
	  lostBrand = new PCLLostBrand__c();
	  }
	  public LostBrand( integer lineNo, list<PCLLostProducts> LostProducts ){
	  lostBrand = new PCLLostBrand__c();
	  this.lineNo = lineNo;
	  this.brandTitle = '失单品牌' + (lineNo + 1);
	  this.LostProducts = LostProducts;
	  ProductSize = LostProducts.size();
	  }
	  public LostBrand( integer lineNo, list<PCLLostProducts> LostProducts,  PCLLostBrand__c lostBrand){
	  this.lostBrand = lostBrand;
	  this.lineNo = lineNo;
	  this.brandTitle = '失单品牌' + (lineNo + 1);
	  this.LostProducts = LostProducts;
	  ProductSize = LostProducts.size();
	  }
	}
	// add tcm 20211119 start
	public class PCLLostProducts {
	  @AuraEnabled
	  public Integer lineNo2;
	  @AuraEnabled
	  public PCLLostProduct__c LostProductss;
	  @AuraEnabled
	  public Boolean bool;
	  @AuraEnabled
	  public String productName;
	  @AuraEnabled
	  public Boolean isJinKou;
	  //chenjingwu 20231225 start
	  @AuraEnabled
	  public Boolean gongNengFlag;
	  //chenjingwu 20231225 end
	  @AuraEnabled
	  public List<Map<String, String>> productOptions = new List<Map<String, String>>();
	  public PCLLostProducts() {
	  this.lineNo2 = 0;
	  this.LostProductss=new PCLLostProduct__c();
	  }
	
	  public PCLLostProducts(Integer lineNo2) {
	  this.lineNo2 = lineNo2;
	  this.LostProductss=new PCLLostProduct__c();
	  }
	
	  public PCLLostProducts(Integer lineNo2,PCLLostProduct__c LostProductss) {
	  this.lineNo2 = lineNo2;
	  this.LostProductss=LostProductss;
	  if (LostProductss.LostProduct__c != null) {
		this.bool = true;
	  }
	  }
	}
	
	@AuraEnabled
	public static string searchProduct(String lostProduct){
	  Product2 prd = null;
	  try {
	  prd = [select Id
	  ,ProductClass__c
	  , ProductCategory__c
	  //chenjingwu 20231109 Start
	  ,isDomestic__c  
	  //chenjingwu 20231109 End
	  from Product2 where Id =:lostProduct];
	  } catch (Exception e) {
	  return e.getMessage();   
	  }
	  return JSON.serialize(prd);
	}
	// @AuraEnabled
	// public static Boolean searchAllProductIsGuoChan(String lostReport){
	//   LostReport report = (LostReport)JSON.deserialize(lostReport,LostReport.class);
	//   Map<String>
	//   List<Product2> proList = [select Id
	//               ,ProductClass__c
	//               , ProductCategory__c
	//               ,isDomestic__c from Product2 where Id in: recordIdList];
	//   Boolean flag = false;
	//   for (Product2 pro : proList) {
	//     if(pro.isDomestic__c == '国产'){
	//       flag
	//     }
	//   }
	// }
	
	// add tcm 20211118 end
	
	@AuraEnabled
	  public static String submitForApproval(String recordId, String comments,String action){
	  try {
	  List<ProcessInstanceWorkitem> workItems = [
		  SELECT Id, ProcessInstanceId 
		  FROM ProcessInstanceWorkitem 
		  WHERE ProcessInstance.TargetObjectId = :recordId 
	  ];
	  Approval.ProcessWorkitemRequest req = new Approval.ProcessWorkitemRequest();
	  req.setWorkitemId(workItems.get(0).Id);
	  req.setAction(action);
	  req.setComments(comments);
	  
		
	  Approval.ProcessResult result = Approval.process(req);
	  return null; 
	  } catch (Exception e) {
	  return e.getMessage();   
	  }
		
	  }
	
	@AuraEnabled
	  public static String reassignStep(String recordId, String newActorId ){
	  try {
	  List<ProcessInstanceWorkItem> workItemList = [SELECT ActorId FROM ProcessInstanceWorkitem WHERE ProcessInstance.TargetObjectId = : recordId];
		ApprovalHistoryUtil.reassignStep(workItemList, newActorId);
	  return null;
	  } catch (Exception e) {
	  return e.getMessage();
	  }
		
	  }
	

	  
	}