// create by tcm 20211220 处理失单报告历史数据
// 2022-01-18 修改 从失单报告处理历史数据
global class LostCancelReportOppBatch implements Database.Batchable<sObject> {

	public List<String> IdList=new List<String> ();

	public Date start_date;

	public Date end_date;

	public Boolean update_all = true;

	global LostCancelReportOppBatch() {
	}

	// 通过询价Id查找
	global LostCancelReportOppBatch(List<string> IdList) {
		this.IdList = IdList;
	}

	// 通过日期查找
	global LostCancelReportOppBatch(String str_start, String str_end, Boolean if_upd_all) {
		this.start_date = String.isNotBlank(str_start) ? Date.parse(str_start) : null;
		this.end_date = String.isNotBlank(str_end) ? Date.parse(str_end) : null;
		this.update_all = if_upd_all != null ? if_upd_all : true;
	}

	global Database.QueryLocator start(Database.BatchableContext bc) {
		// string query ='select id from Opportunity ';
		// if (IdList.size() > 0) {
		// 	query += ' where Id in :IdList';
		// }
		// 2022-01-18 修改 从失单报告取值
		String query = 'SELECT Id FROM Lost_cancel_report__c WHERE Report_Status__c = \'批准\' AND LostType__c in (\'失单\', \'部分失单\') ';
		if (start_date != null) {
			query += ' AND Submit_Day__c >= :start_date';
		}
		if (end_date != null) {
			query += ' AND Submit_Day__c >= :start_date';
		}
		if (IdList != null && IdList.size() > 0) {
			query += ' AND Opportunity__c in :IdList';
		}
		if (!update_all) {
			query += ' AND Opportunity__r.PCLLostBrands__c != null';
		}
		return Database.getQueryLocator(query);
	}

	// global void execute(Database.BatchableContext BC, List<Opportunity> scope) {

	// 	List<String> oppIdList=new List<String>();
	// 	for (Opportunity opp : scope) {
	// 		oppIdList.add(opp.Id);
	// 	}

	// 	List<PCLLostProduct__c> pclLpList=[select id,Quantity__c, LostProduct__r.Name, LostProductMannual__c, PCLLostBrand__r.Lost_By_Company__c, PCLLostBrand__r.Lost_reason_main__c, PCLLostBrand__r.Lost_Reason_Sub__c, PCLLostBrand__r.Lost_By_Company_Mannual__c, PCLLostBrand__r.Agency__r.Name, PCLLostBrand__r.AgencyMannual__c, PCLLostBrand__r.Lost_cancel_report__r.LostType__c, PCLLostBrand__r.Lost_cancel_report__r.LostTotalAmount__c, PCLLostBrand__r.Lost_cancel_report__r.of_lost_system_processor__c,PCLLostBrand__r.Lost_cancel_report__r.Opportunity__c from PCLLostProduct__c where PCLLostBrand__r.Lost_cancel_report__r.Report_Status__c = '批准' and PCLLostBrand__r.Lost_cancel_report__r.Opportunity__c in : oppIdList and LostProduct__c!=null];

	// 	List<Opportunity> oppList=new List<Opportunity>();
	// 	for (String oppId : oppIdList) {

	// 		Opportunity opp=new Opportunity();
	// 		opp.Id=Id.valueOf(oppId); opp.PCLLostBrands__c=''; opp.Agencies__c=''; opp.Lost_Reason_Sub__c='';opp.of_lost_system_processor__c=0;    //Id ,品牌,经销商,原因次
	// 		Integer i=0;
	// 		List<String> ppList=new List<String>(); //品牌List
	// 		List<String> jxsList=new List<String>(); //经销商List


	// 		for (PCLLostProduct__c lp : pclLpList) {
	// 			if (oppId==lp.PCLLostBrand__r.Lost_cancel_report__r.Opportunity__c) {
	// 				if (i==0) {
	// 					opp.LostTypeText__c=lp.PCLLostBrand__r.Lost_cancel_report__r.LostType__c;  //失单类型
	// 					opp.LostPrices__c=lp.PCLLostBrand__r.Lost_cancel_report__r.LostTotalAmount__c; //失单金额
	// 					// opp.of_lost_system_processor__c=lp.PCLLostBrand__r.Lost_cancel_report__r.of_lost_system_processor__c; //失单主机台数(总)
	// 					opp.Lost_reason_main__c=lp.PCLLostBrand__r.Lost_reason_main__c; //失单理由（主）
	// 				}
	// 				opp.of_lost_system_processor__c+=lp.Quantity__c; 	//失单主机台数（累加）
	// 				if (lp.PCLLostBrand__r.Lost_Reason_Sub__c!=null) {
	// 					opp.Lost_Reason_Sub__c=lp.PCLLostBrand__r.Lost_Reason_Sub__c;   //失单理由（次）
	// 				}

	// 				// 失单产品123 start
	// 				if (opp.CompetitorProduct1__c==null) {
	// 					opp.CompetitorProduct1__c=lp.LostProduct__r.Name;
	// 				}else if (opp.CompetitorProduct2__c==null) {
	// 					opp.CompetitorProduct2__c=lp.LostProduct__r.Name;
	// 				}else if (opp.CompetitorProduct3__c==null) {
	// 					opp.CompetitorProduct3__c=lp.LostProduct__r.Name;
	// 				}
	// 				// 失单产品123 end

	// 				//失单品牌 start
	// 				if (!ppList.contains(lp.PCLLostBrand__r.Lost_By_Company__c)) {
	// 					ppList.add(lp.PCLLostBrand__r.Lost_By_Company__c);
	// 					if (ppList.size()==1) {
	// 						if (lp.PCLLostBrand__r.Lost_By_Company__c=='其他') {
	// 							opp.PCLLostBrands__c+=lp.PCLLostBrand__r.Lost_By_Company_Mannual__c;
	// 						}else {
	// 							opp.PCLLostBrands__c+=lp.PCLLostBrand__r.Lost_By_Company__c;
	// 						}
	// 					}else {
	// 						if (lp.PCLLostBrand__r.Lost_By_Company__c=='其他') {
	// 							opp.PCLLostBrands__c+=','+lp.PCLLostBrand__r.Lost_By_Company_Mannual__c;
	// 						}else {
	// 							opp.PCLLostBrands__c+=','+lp.PCLLostBrand__r.Lost_By_Company__c;
	// 						}
	// 					}
	// 				}
	// 				//失单品牌 end

	// 				//经销商 start
	// 				if (!jxsList.contains(lp.PCLLostBrand__r.Agency__r.Name)) {
	// 					jxsList.add(lp.PCLLostBrand__r.Agency__r.Name);
	// 					if (jxsList.size()==1) {
	// 						if (lp.PCLLostBrand__r.AgencyMannual__c==null) {
	// 							opp.Agencies__c+=lp.PCLLostBrand__r.Agency__r.Name;
	// 						}else {
	// 							opp.Agencies__c+=lp.PCLLostBrand__r.AgencyMannual__c;
	// 						}
	// 					}else {
	// 						if (lp.PCLLostBrand__r.AgencyMannual__c==null) {
	// 							opp.Agencies__c+='，'+lp.PCLLostBrand__r.Agency__r.Name;
	// 						}else {
	// 							opp.Agencies__c+='，'+lp.PCLLostBrand__r.AgencyMannual__c;
	// 						}
	// 					}
	// 				}
	// 				//经销商 end
	// 				i++;
	// 			}
	// 		}
	// 		oppList.add(opp);
	// 		system.debug('opp等于'+opp);
	// 	}
	// 	system.debug('oppList等于'+oppList);
	// 	update oppList;
	// }

	// 2022-01-18 修改 从失单报告取值
	global void execute(Database.BatchableContext BC, List<Lost_cancel_report__c> scope) {

		List<String> reportIdList=new List<String>();
		for (Lost_cancel_report__c report : scope) {
			reportIdList.add(report.Id);
		}

		List<PCLLostProduct__c> pclLpList=[select 
											id,                                                                  // 失单型号id
											Quantity__c,                                                         // 失单数量
											LostProductName__c,                                                  // 失单对手型号
											LostProductMannual__c,                                               // 失单对手型号（手动）
											PCLLostBrand__r.Lost_By_Company__c,                                  // 失单品牌
											PCLLostBrand__r.Lost_reason_main__c,                                 // 失单原因（主）
											PCLLostBrand__r.Lost_Reason_Sub__c,                                  // 失单原因（次）
											PCLLostBrand__r.Lost_By_Company_Mannual__c,                          // 失单品牌（手动）
											PCLLostBrand__r.Agency__r.Name,                                      // 中标经销商
											PCLLostBrand__r.AgencyMannual__c,                                    // 中标经销商（手动）
											PCLLostBrand__r.Lost_cancel_report__r.LostType__c,                   // 失单类型
											PCLLostBrand__r.Lost_cancel_report__r.LostTotalAmount__c,            // 失单总金额
											PCLLostBrand__r.Lost_cancel_report__r.TotalAmountLost__c,  			// 失单总金额（不含税）  //20230215 lt DB202302247719
											PCLLostBrand__r.Lost_cancel_report__r.of_lost_system_processor__c,   // 失单主机台数
											PCLLostBrand__r.Lost_cancel_report__r.Opportunity__c 
										from 
											PCLLostProduct__c 
										where 
										PCLLostBrand__r.Lost_cancel_report__c in :reportIdList];
		
		// 初始化保存参数
		Map<String, Opportunity> opp_map = new Map<String, Opportunity>();
		Map<String, String> prod_map = new Map<String, String>();
		Map<String, String> agency_map = new Map<String, String>();

		// 循环整理数据
		for (PCLLostProduct__c lost : pclLpList) {
			// 判断是否可用数据
			// if (String.isBlank(lost.LostProductName__c) && String.isBlank(lost.LostProductMannual__c)) {
			// 	continue;
			// }
			// 询价id
			String opp_id = lost.PCLLostBrand__r.Lost_cancel_report__r.Opportunity__c;
			// 询价
			Opportunity opp = opp_map.get(opp_id);
			if (opp == null) {
				opp = new Opportunity();
				opp.Id = opp_id;
				opp.of_lost_system_processor__c = 0;
				opp_map.put(opp_id, opp);
			}
			// 赋值
			opp.LostTypeText__c = lost.PCLLostBrand__r.Lost_cancel_report__r.LostType__c;       // 失单类型
			//opp.LostPrices__c = lost.PCLLostBrand__r.Lost_cancel_report__r.LostTotalAmount__c;  // 失单金额 //20230215 lt DB202302247719 注释
			opp.LostPrices__c = lost.PCLLostBrand__r.Lost_cancel_report__r.TotalAmountLost__c;  // 失单金额  //20230215 lt DB202302247719
			opp.Lost_reason_main__c = lost.PCLLostBrand__r.Lost_reason_main__c;                 // 失单原因（主）
			opp.Lost_Reason_Sub__c = lost.PCLLostBrand__r.Lost_Reason_Sub__c;                   // 失单理由（次）
			opp.of_lost_system_processor__c += lost.Quantity__c; 	                            // 失单主机台数（累加）

			// 失单产品123 start
			if (opp.CompetitorProduct1__c == null) {
				opp.CompetitorProduct1__c = lost_product_name(lost.LostProductName__c, lost.LostProductMannual__c);
			}else if (opp.CompetitorProduct2__c == null) {
				opp.CompetitorProduct2__c = lost_product_name(lost.LostProductName__c, lost.LostProductMannual__c);
			}else if (opp.CompetitorProduct3__c == null) {
				opp.CompetitorProduct3__c = lost_product_name(lost.LostProductName__c, lost.LostProductMannual__c);
			}
			// 失单产品123 end

			// 失单品牌
			opp.PCLLostBrands__c = lost_brand_name(opp.PCLLostBrands__c, lost.PCLLostBrand__r.Lost_By_Company__c, lost.PCLLostBrand__r.Lost_By_Company_Mannual__c);

			// 中标经销商
			opp.Agencies__c = lost_agency_name(opp.Agencies__c, lost.PCLLostBrand__r.Agency__r.Name, lost.PCLLostBrand__r.AgencyMannual__c);

		}
		System.debug(opp_map);
		update opp_map.values();
	}

	// 失单对手型号
	private String lost_product_name(String lost_product, String lost_product_mannual) {
		if (String.isBlank(lost_product) && String.isNotBlank(lost_product_mannual)) {
			return lost_product_mannual;
		}
		return lost_product;
	}

	// 失单品牌
	private String lost_brand_name(String lost_brand_in_opp, String lost_brand, String lost_brand_mannual) {
		// 初始化参数
		String plus = '';
		// 判断	
		// SWAG-CCC6F6 2022-04-22 ssm start
		// 询价上都只显示选项列表的值，不需要手动的值
		// if ('其他'.equals(lost_brand) && String.isNotBlank(lost_brand_mannual)) {
		// 	plus = lost_brand_mannual;
		// } else {
		// 	plus = lost_brand;
		// }
		plus = lost_brand;
		// SWAG-CCC6F6 2022-04-22 ssm end
		// 初始化返回值
		if (String.isBlank(lost_brand_in_opp)) {
			lost_brand_in_opp = '';
		}
		// 拼接
		if (String.isNotBlank(plus) && !lost_brand_in_opp.contains(plus)) {
			// 增加分隔标识
			if (String.isNotBlank(lost_brand_in_opp)) {
				lost_brand_in_opp += ',';
			}
			lost_brand_in_opp += plus;
		}
		return lost_brand_in_opp;
	}

	// 中标经销商
	private String lost_agency_name(String lost_agency_in_opp, String lost_agency, String lost_agency_mannual) {
		// 初始化参数
		String plus = '';
		// 判断	
		// SWAG-CCC6F6 2022-04-22 ssm start
		// 询价上都只显示选项列表的值，不需要手动的值
		// if ('对手经销商'.equals(lost_agency) && String.isNotBlank(lost_agency_mannual)) {
		// 	plus = lost_agency_mannual;
		// } else {
		// 	plus = lost_agency;
		// }
		plus = lost_agency;
		// SWAG-CCC6F6 2022-04-22 ssm end
		// 初始化返回值
		if (String.isBlank(lost_agency_in_opp)) {
			lost_agency_in_opp = '';
		}
		// 拼接
		if (String.isNotBlank(plus) && !lost_agency_in_opp.contains(plus)) {
			// 增加分隔标识
			if (String.isNotBlank(lost_agency_in_opp)) {
				lost_agency_in_opp += ',';
			}
			lost_agency_in_opp += plus;
		}
		return lost_agency_in_opp;
	}

	global void finish(Database.BatchableContext BC) {

	}
}


// List<String> IdList=new List<String>{'0061m000003fUz6'};
// Database.executeBatch(new LostCancelReportOppBatch(IdList));

// Database.executeBatch(new LostCancelReportOppBatch());