// 22/03/2023 合同续签，Asset标志位变为false，以便生成新的报警提醒
global class HandleAlarm888AssetFlagBatch implements Database.Batchable<sObject> , Database.AllowsCallouts, Database.Stateful {
	public Date nowDate = Date.today();
	// List<Id> assetIdList = new List<Id>();
    global HandleAlarm888AssetFlagBatch() {
		// this.assetIdList = assetIdList;
    }
    //Database.QueryLocator
    global List<Asset> start(Database.BatchableContext bc) {
        //del SerMarGuranteeType__c 多年保修类型； CurrentContract__c  	最近一期维修合同 InstallDate,InstallDate__c,Extend_Gurantee_DateTo__c,
        List<Asset> assetList = [SELECT Id,InstallDate__c,Extend_Gurantee_DateTo__c,CurrentContract_Start_Date__c,CurrentContract_End_Date__c,Is_Add_888_Alarm__c,
                (SELECT Id,Asset_ID__c,Nth_Operating_Day__c FROM Alarm_888_Month__r ORDER BY Nth_Operating_Day__c DESC LIMIT 1) 
                FROM Asset WHERE Is_Add_888_Alarm__c = true];
                /*Where (MDM_Model_No__c = 'OER-AW' OR MDM_Model_No__c = 'OER-Smart') AND Is_Add_888_Alarm__c = false AND (InstallDate!= null AND InstallDate!= :installDate)
                          AND ((CurrentContract_End_Date__c >=: nowDate  AND CurrentContract_Start_Date__c <= :nowDate) OR (Extend_Gurantee_DateTo__c >= :nowDate AND InstallDate__c <= :nowDate ))*/
        return assetList;
    }

    global void execute(Database.BatchableContext BC,List<Asset> assetList) {
        System.debug(LoggingLevel.INFO, '*** assetList: ' + assetList);
        if (assetList.size() > 0) {
            for (Asset asset : assetList) {
            	if (asset.Alarm_888_Month__r.size() > 0 && asset.Alarm_888_Month__r[0] != null) {            	
	            	Date operatDate = asset.Alarm_888_Month__r[0].Nth_Operating_Day__c;
	            	Date contractStartDate = asset.CurrentContract_Start_Date__c > asset.InstallDate__c ? asset.CurrentContract_Start_Date__c : asset.InstallDate__c ;
	            	// Date contractEndDate = asset.CurrentContract_End_Date__c ;
	            	// Date serviceStartDate = asset.InstallDate__c ;
	            	Date serviceEndDate = asset.Extend_Gurantee_DateTo__c ;
	            	//最后操作日小余续签的合同开始日期并且多年保无效，需再生成888   
	                if (contractStartDate > operatDate){
	                	if (serviceEndDate == null) {
	                		asset.Is_Add_888_Alarm__c = false;
	                	}else if(serviceEndDate <= nowDate){
	                		asset.Is_Add_888_Alarm__c = false;
	                	}
	                }
                }
            }
            StaticParameter.EscapeVMCTrigger = true;
            update assetList;
            StaticParameter.EscapeVMCTrigger = false;
            System.debug(LoggingLevel.INFO, '*** assetList: ' + assetList);
        }
    }

    global void finish(Database.BatchableContext BC) {
        //生成预警对象
        Id execBTId = Database.executeBatch(new Create888AlarmBatch(),100);
    }
}