/* 用于更新目前所有维修合同续签的上期合同
1) 为避免错误，按保有设备为基础查询维修合同保有设备；
2) 按维修合同保有设备与合同结束日排序查询
3) 检索出上一期维修合同所有的维修合同保有设备；
*/
global class AssetUpdateLastContractbatch implements Database.Batchable<sObject> {
    // 设定运行的保有设备ID
    public String TestID;
    // 设定运行的保有设备的list<ID>
    public list<string> TestIDList;

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

    Boolean IsNeedExecute = false; // 2021-03-08  mzy  WLIG-BYHD79  SFDC环境batch合并调查  是否符合执行条件


    global AssetUpdateLastContractbatch() {
    }
    global AssetUpdateLastContractbatch(List<String> TestIDList) {
        this.TestIDList = TestIDList;
    }
    // 2021-03-08  mzy  WLIG-BYHD79  SFDC环境batch合并调查  start
    global AssetUpdateLastContractbatch(Boolean NeedExecute) {
        this.IsNeedExecute = NeedExecute;
    }
    // 2021-03-08  mzy  WLIG-BYHD79  SFDC环境batch合并调查  end

    global Database.QueryLocator start(Database.BatchableContext bc) {
        // List<String> assetList = new List<String>();
        // List<AggregateResult> mCA = [select count(Id), Asset__c from Maintenance_Contract_Asset__c Group by Asset__c ];
        // for (AggregateResult ar : mCA) {
        //     assetList.add(String.valueOf(ar.get('Asset__c')));
        // }
        if (TestIDList != null && TestIDList.size() > 0) {
            return Database.getQueryLocator([select id from asset where Id in : TestIDList]);
        }else{
            // 20221117 ljh DB202211258553 start
            // return Database.getQueryLocator([select id from asset]);
            return Database.getQueryLocator([select id from asset where IsCompetitorProduct = false AND ( AssetMark__c != '耗材' OR Product2.Family != 'ET')]);
            // 20221117 ljh DB202211258553 end
            // return Database.getQueryLocator([select id from asset where Id in : assetList]);
        }
    }

    global void execute(Database.BatchableContext BC, list<asset> scope) {
        List<String> assetslist = new List<String>();
        for (asset ass : scope) {
            assetslist.add(ass.Id);
        }
        List<Maintenance_Contract_Asset__c> mCAList = 
                                [select Id,Maintenance_Contract__c,Asset__c,Maintenance_Contract__r.Contract_End_Date__c,LastMContract__c
                                    from Maintenance_Contract_Asset__c 
                                    where Maintenance_Contract__r.Status__c in ('契約','契約満了')
                                    and Asset__c in : assetslist 
                                    // 2020/10/30 songxiaoqi  start
                                     // and Maintenance_Contract__r.RecordType_DeveloperName__c !='VM_Contract'
                                     //2020/ 10/30 songxiaoqi  end
                                    order by Asset__c,Maintenance_Contract__r.Contract_End_Date__c];

        //add by rentx 2020-11-09 start
        List<Maintenance_Contract_Asset__c> updatelist = new List<Maintenance_Contract_Asset__c>();
        //add by rentx 2020-11-09 end
        for (Integer i = 0; i < mCAList.size(); i++) {
            if (i== 0) {
                
            }else{                
                // if (mCAList[i].Asset__c == mCAList[i-1].Asset__c) {
                if ((mCAList[i].Asset__c == mCAList[i-1].Asset__c) && (mCAList[i].LastMContract__c != mCAList[i-1].Maintenance_Contract__c)) {
                    mCAList[i].LastMContract__c = mCAList[i-1].Maintenance_Contract__c;
                    //add by rentx 2020-11-09 start
                    updatelist.add(mCAList[i]);
                    //add by rentx 2020-11-09 end
                }
            }
        }

        //update by rentx 2020-11-09 start
        // Database.SaveResult[] lsr = Database.update(mCAList, false);
        Database.SaveResult[] lsr = Database.update(updatelist, false);
        //update by rentx 2020-11-09 end

        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 ' + mCAList[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 = '\nAssetUpdateLastContractEnd';
        if (errorstr.length() > 60000) {
            batchIfLog.ErrorLog__c = errorstr.substring(0, 60000);
        } else {
            batchIfLog.ErrorLog__c = errorstr.substring(0, errorstr.length());
        }
        insert batchIfLog;

        //2021-03-03  mzy  WLIG-BYHD79  SFDC环境batch合并调查  start
        if(!Test.isRunningTest() &&IsNeedExecute==true){
          //batch里调用下一个batch时，希望跟原有的Schedule里面传的条数保持一致
           Id execBTId = Database.executebatch(new TargetCustomerAssignmentBatch(true),1);
        }
        //2021-03-03  mzy  WLIG-BYHD79  SFDC环境batch合并调查 end

    }

}