global class ConUpdateLastContractbatch implements Database.Batchable<sObject> {
	// 设定运行的维修合同的list<ID>
	public list<string> TestIDList;

	// 报错信息
	public String errorstr = '';

	global ConUpdateLastContractbatch() {
	}
	global ConUpdateLastContractbatch(List<string> TestIDList) {
		this.TestIDList = TestIDList;
	}

	global Database.QueryLocator start(Database.BatchableContext bc) {
		string query =
			' select id , previousTotalRepairAmount__c , currentTotalRepairAmount__c ,' +
			' previousTotalContractAmount__c , currentTotalContractAmountVM__c , currentTotalGuaranteePrice__c '+
			' , RecordType_DeveloperName__c ,Contract_Start_Date__c ' +  //tcm Contract_Start_Date__c
			'  from Maintenance_Contract__c '
			+ ' where ';
		if (TestIDList != null && TestIDList.size() > 0) {
			query += ' id in: TestIDList';
		}else {
			query += ' Status__c in (\'契約\',\'契約満了\') ';
		}
		return Database.getQueryLocator(query);
	}

	global void execute(Database.BatchableContext BC, list<Maintenance_Contract__c> scope) {
		List<String> mCidList = new List<String>();
		Map<String,String> IdMap=new Map<String,String>();
		for (Maintenance_Contract__c MC : scope) {
			mCidList.add(MC.Id);
			IdMap.put(MC.Id, MC.Id);
		}
		system.debug('scope等于'+scope);

		// 先取维修合同ID
		Map<String,Map<String,lastMContract> > lastMContractMap = new Map<String,Map<String,lastMContract> >();
		Map<String,Map<String,lastMContract> > lastMContractMap1 = new Map<String,Map<String,lastMContract> >();

		// 再取有上期合同的合同保有设备信息
		//tcm 20211130 start 更换Maintenance_Contract_No_F__c为Management_Code__c
		List<Maintenance_Contract_Asset__c> mCAList =
		[select Id,Maintenance_Contract__c,LastMContract__c,LastMContract__r.Contract_End_Date__c,
		 LastMContract__r.Management_Code__c,/*LastMContract__r.Maintenance_Contract_No_F__c,*/
		 Maintenance_Contract__r.Contract_Start_Date__c,LastMContract__r.RecordType_DeveloperName__c
		 from Maintenance_Contract_Asset__c
		 where Maintenance_Contract__r.Status__c in ('契約','契約満了')
		 and Maintenance_Contract__c in : mCidList
		 and LastMContract__c != null
		 order by Asset__c,Maintenance_Contract__r.Contract_End_Date__c];

		for (Maintenance_Contract_Asset__c mca : mCAList) {
			//判断 如果上一期维修合同为 多年保修合同 的话 则不放入map进行更新 LJPH-BUU3E3 update by rentx 2020-11-03 start
			// if (String.isNotBlank(mca.LastMContract__c) && mca.LastMContract__r.RecordType_DeveloperName__c!= 'VM_Contract'&&mca.LastMContract__r.Contract_End_Date__c!=null) {
			if (String.isNotBlank(mca.LastMContract__c) &&mca.LastMContract__r.Contract_End_Date__c!=null) {
				lastMContract lM = new lastMContract(mca.LastMContract__c,mca.LastMContract__r.Management_Code__c/*Maintenance_Contract_No_F__c*/,mca.LastMContract__r.Contract_End_Date__c,1);
				// 判断空白期
				system.debug('合同开始日等于：'+mca.Maintenance_Contract__r.Contract_Start_Date__c+'；合同结束日等于：'+mca.LastMContract__r.Contract_End_Date__c);
				if (mca.Maintenance_Contract__r.Contract_Start_Date__c.daysbetween(mca.LastMContract__r.Contract_End_Date__c) > -366 &&mca.Maintenance_Contract__r.Contract_Start_Date__c.daysbetween(mca.LastMContract__r.Contract_End_Date__c) < 366) {
					// 数量
					if (lastMContractMap.containsKey(mca.Maintenance_Contract__c)) {
						if (lastMContractMap.get(mca.Maintenance_Contract__c).containsKey(mca.LastMContract__c)) {
							lastMContractMap.get(mca.Maintenance_Contract__c).get(mca.LastMContract__c).count++;
						}else {
							lastMContractMap.get(mca.Maintenance_Contract__c).put(mca.LastMContract__c, lM);
						}
					}else{
						Map<String,lastMContract> lastMContracttemp = new Map<String,lastMContract>();
						lastMContracttemp.put(mca.LastMContract__c, lM);
						lastMContractMap.put(mca.Maintenance_Contract__c, lastMContracttemp);
					}
				} else {
					// 数量
					if (lastMContractMap1.containsKey(mca.Maintenance_Contract__c)) {
						if (lastMContractMap1.get(mca.Maintenance_Contract__c).containsKey(mca.LastMContract__c)) {
							lastMContractMap1.get(mca.Maintenance_Contract__c).get(mca.LastMContract__c).count++;
						}else {
							lastMContractMap1.get(mca.Maintenance_Contract__c).put(mca.LastMContract__c, lM);
						}
					}else{
						Map<String,lastMContract> lastMContracttemp1 = new Map<String,lastMContract>();
						lastMContracttemp1.put(mca.LastMContract__c, lM);
						lastMContractMap1.put(mca.Maintenance_Contract__c, lastMContracttemp1);
					}
				}
			}else {
				Map<String,lastMContract> lastMContracttemp2 = new Map<String,lastMContract>();
				lastMContractMap.put(mca.Maintenance_Contract__c, lastMContracttemp2);
			}
		}
		system.debug('lastMContractMap等于+'+lastMContractMap);
		system.debug('lastMContractMap1等于+'+lastMContractMap1);

		Map<String,List<lastMContract> > mapResult = new Map<String,List<lastMContract> >();

		for (String str : mCidList) {
			List<lastMContract> listResulttemp = new List<lastMContract>();
			List<lastMContract> listResulttemp1 = new List<lastMContract>();
			List<lastMContract> listResult = new List<lastMContract>();
			List<lastMContract> listResult1 = new List<lastMContract>();

			if (lastMContractMap.containsKey(str)) {
				// 空白期
				listResulttemp = lastMContractMap.get(str).values();
				listResulttemp.sort();
				for (Integer i = 0; i < listResulttemp.size(); i++) {
					if (listResulttemp.size() >= i+1) {
						listResult.add(listResulttemp[i]);
					}
				}
			}
			if (lastMContractMap1.containsKey(str)&&listResult.size()<=5) {
				// 非空白期
				listResulttemp1 = lastMContractMap1.get(str).values();
				listResulttemp1.sort();
				System.debug('listResulttemp1size等于'+listResulttemp1.size());
				for (Integer i = 0; i < listResulttemp1.size(); i++) {
					// if (listResulttemp1.size() >= i+1) {
						listResult1.add(listResulttemp1[i]);
					// 	system.debug('iiiiiiiiiiii'+i);
					// }else {
					// 	listResult1.add(new lastMContract(null, null, null, null));
					// }
				}
			}

			listResult.addAll(listResult1);
			system.debug('listResultsize1等于'+listResult.size());
			system.debug('listResultsList等于'+listResult);

			// 如果不足5个合同，自动添加剩余的合同为null
			if (listResult.size()<5) {
				Integer num=5-listResult.size();
				for (Integer i = 0; i < num; i++) {
					listResult.add(new lastMContract(null, null, null, null));
				}
				mapResult.put(str, listResult);
			}else {
				mapResult.put(str, listResult);
			}
			system.debug('listResultsizeend等于'+listResult.size());
		}
		system.debug('mapResult等于+'+mapResult);

		List<Maintenance_Contract__c> upMCList = new List<Maintenance_Contract__c>();
		// 五个合同赋值
		for (String str : mCidList) {
			if (mapResult.containsKey(str)) {
				Maintenance_Contract__c upMC = new Maintenance_Contract__c();
				upMC.Id = str;
				upMC.LastMContract1__c = mapResult.get(str)[0].contractId;
				upMC.LastMContract1_NO__c = mapResult.get(str)[0].contractNo;
				upMC.LastMContract1_ConCount__c = mapResult.get(str)[0].count;

				upMC.LastMContract2__c = mapResult.get(str)[1].contractId;
				upMC.LastMContract2_NO__c = mapResult.get(str)[1].contractNo;
				upMC.LastMContract2_ConCount__c = mapResult.get(str)[1].count;

				upMC.LastMContract3__c = mapResult.get(str)[2].contractId;
				upMC.LastMContract3_NO__c = mapResult.get(str)[2].contractNo;
				upMC.LastMContract3_ConCount__c = mapResult.get(str)[2].count;

				upMC.LastMContract4__c = mapResult.get(str)[3].contractId;
				upMC.LastMContract4_NO__c = mapResult.get(str)[3].contractNo;
				upMC.LastMContract4_ConCount__c = mapResult.get(str)[3].count;

				upMC.LastMContract5__c = mapResult.get(str)[4].contractId;
				upMC.LastMContract5_NO__c = mapResult.get(str)[4].contractNo;
				upMC.LastMContract5_ConCount__c = mapResult.get(str)[4].count;
				upMCList.add(upMC);
			}
			// else {
			// 	Maintenance_Contract__c upMC = new Maintenance_Contract__c();
			// 	upMC.Id = str;
			// 	upMC.LastMContract1__c = null;
			// 	upMC.LastMContract1_NO__c = null;
			// 	upMC.LastMContract1_ConCount__c =  null;

			// 	upMC.LastMContract2__c = null;
			// 	upMC.LastMContract2_NO__c = null;
			// 	upMC.LastMContract2_ConCount__c =  null;

			// 	upMC.LastMContract3__c = null;
			// 	upMC.LastMContract3_NO__c = null;
			// 	upMC.LastMContract3_ConCount__c =  null;

			// 	upMC.LastMContract4__c = null;
			// 	upMC.LastMContract4_NO__c = null;
			// 	upMC.LastMContract4_ConCount__c = null;

			// 	upMC.LastMContract5__c = null;
			// 	upMC.LastMContract5_NO__c = null;
			// 	upMC.LastMContract5_ConCount__c =  null;
			// 	upMCList.add(upMC);
			// }
		}
		system.debug('upMCList等于+'+upMCList);

		Database.SaveResult[] lsr = Database.update(upMCList, false);
		String errorMsg = '';
		for (Integer sIdx = 0; sIdx < lsr.size(); sIdx++) {
			Database.SaveResult sr = lsr[sIdx];
			if (!sr.isSuccess()) {
				Database.Error emsg = sr.getErrors()[0];
				errorstr += 'ERROR ' + upMCList[sIdx].get('Id') + ' 维修合同:' + emsg + '\n';
			}
		}
	}


	global void finish(Database.BatchableContext BC) {

		BatchIF_Log__c batchIfLog = new BatchIF_Log__c();
		batchIfLog.Type__c = 'MCAssetUpdate';
		batchIfLog.Log__c = '\nConUpdateLastContractbatchend';
		if (errorstr.length() > 60000) {
			batchIfLog.ErrorLog__c = errorstr.substring(0, 60000);
		} else {
			batchIfLog.ErrorLog__c = errorstr.substring(0, errorstr.length());
		}
		insert batchIfLog;

	}

	// 续签合同信息 class
	public class lastMContract implements Comparable {
		public Date endDate;
		public Integer count;
		public String contractId;
		public String contractNo;
		// tcm start
		public Boolean ayearcontract;
		// tcm end
		public lastMContract(String contractId,String contractNo,Date endDate, Integer count) {
			this.endDate = endDate;
			this.count = count;
			this.contractId = contractId;
			this.contractNo = contractNo;
		}
		// 排序
		// tcm start
		public Integer compareTo(Object compareTo) {
			lastMContract compareToesd = (lastMContract)compareTo;
			Integer returnValue = 0;
			// 判断数量
			if (count  > compareToesd.count) {
				returnValue = -1;
			} else if (count  < compareToesd.count) {
				returnValue = 1;
			} else {
				if (endDate  > compareToesd.endDate ) {
					returnValue = 1;
				} else {
					returnValue = -1;
				}
			}
			return returnValue;
		}
		// tcm end
	}

	
}