global class UpdateURFContactBatch implements Database.Batchable<sObject> {
    public String query;
    public String conId;

    global UpdateURFContactBatch() {
        this.query = query;
    }
    global UpdateURFContactBatch(String conId) {
        this.query = query;
        this.conId = conId;
    }

    global Database.QueryLocator start(Database.BatchableContext bc) {
        query = 'select Id,Maintenance_Contract__c,Series_AllCount__c from Maintenance_Contract_Asset__c where ';
        query += ' Maintenance_Contract__r.Status__c = \'契約\' and  Maintenance_Contract__r.URF_Contract__c = true ';
        if (conId != null && conId != '') {
            query += ' and Maintenance_Contract__c = :conId ';
        }
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, list<Maintenance_Contract_Asset__c> scope) {
        Map<String,Maintenance_Contract__c> MCMap = new Map<String,Maintenance_Contract__c>();
        for (Maintenance_Contract_Asset__c mca : scope) {
            if (MCMap.containsKey(mca.Maintenance_Contract__c) && mca.Series_AllCount__c) {
                MCMap.remove(mca.Maintenance_Contract__c);
            }else if (!MCMap.containsKey(mca.Maintenance_Contract__c) && mca.Series_AllCount__c == false) {
                Maintenance_Contract__c mc = new Maintenance_Contract__c();
                mc.Id = mca.Maintenance_Contract__c;
                mc.Status__c = '契約満了';
                mc.URFContact_EndDate__c = Date.today();
                MCMap.put(mca.Maintenance_Contract__c, mc);
            }
        }

        if (MCMap.size() > 0) {
            update MCMap.values();
        }
    }

    global void finish(Database.BatchableContext BC) {

    }
}