// 新维修合同更新现存实际报价金额
global class MCAssetUpdateEstimateCostBatch implements Database.Batchable<sObject>, Database.Stateful {
    // 设定运行的维修合同的ID
    public string TestID;

    // 设定运行的维修合同的list<ID>
    public list<string> TestIDList;
    
    // 设定运行的维修合同的记录类型 developerName
    public string recordTypeDevelopName1;
    
      // 设定运行的维修合同的记录类型 developerName
    public string recordTypeDevelopName2;

    // 报错的维修合同ID
    public String logstr = '';

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

    global Integer totalCount = 0; // 总件数
    global Integer failedCount = 0; // 失败件数

    global List<String> emailMessages = new List<String>();

    global MCAssetUpdateEstimateCostBatch() {
 
    }
 

 

    //  执行选定的维修合同
    global MCAssetUpdateEstimateCostBatch(string TestID ) {
        this.TestID = TestID;
    }
    
    //  执行选定的维修合同组
    global MCAssetUpdateEstimateCostBatch(string recordTypeDevelopName1, string recordTypeDevelopName2 ) {
        this.recordTypeDevelopName1 = recordTypeDevelopName1;
        this.recordTypeDevelopName2 = recordTypeDevelopName2;    
    }

    //  执行选定的维修合同组
    global MCAssetUpdateEstimateCostBatch(list<string> TestIDList ) {
        this.TestIDList = TestIDList;
        
    }

    global Database.QueryLocator start(Database.BatchableContext bc) {
        string query =
            ' select id ,  Contract_Amount__c , Estimation_Id__c, RecordType_DeveloperName__c, ' +
            ' Estimation_Id__r.Asset_Repair_Sum_Price__c, '+
            'Estimation_Id__r.NewEstimation_Amount__c ,Estimate_Trial_Money__c, '+ 
            'Estimation_Id__r.Asset_Sum_Price__c '+
            '  from Maintenance_Contract__c '
            + ' where RecordType_DeveloperName__c != \'VM_Contract\' ';
        if (string.isNotBlank(TestID) ) {
            query += ' and id =: TestID';
        } else if (TestIDList != null && TestIDList.size() > 0) {
            query += ' and id in: TestIDList';
        }  else  if (string.isNotBlank(recordTypeDevelopName1) ) {
            query += ' and RecordType_DeveloperName__c  = \'' + recordTypeDevelopName1 + '\' ';
        }
        system.debug('query:'+query);
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC,
                        list<Maintenance_Contract__c> MCList) {
        set<id> MCIDSet = new set<id>();
        Map<id,Maintenance_Contract__c> MCMap = new Map<id,Maintenance_Contract__c>();
        for (Maintenance_Contract__c tempMC : MCList) {
            mcIDSet.add(tempMC.id);
            MCMap.put(tempMC.id, tempMC);
        }
        list<Maintenance_Contract_Asset__c> UpdateMCAList = new list<Maintenance_Contract_Asset__c>();
        map<id,Maintenance_Contract_Asset_Estimate__c> UpdateMCAEMap = new map<id,Maintenance_Contract_Asset_Estimate__c>();
        list<Maintenance_Contract_Asset__c> MCAList = 
                    [select id, Estimate_List_Price_All__c, Estimate_Cost__c,
                        Maintenance_Contract_Asset_Estimate__c, 
                        Maintenance_Contract_Asset_Estimate__r.Estimate_Cost__c,
                        Maintenance_Contract__c
                        from Maintenance_Contract_Asset__c 
                        where Maintenance_Contract__c in: mcIDSet];
        
         for (Maintenance_Contract_Asset__c tempMCA : MCAList) {
             Maintenance_Contract__c tempMC = MCMap.get(tempMCA.Maintenance_Contract__c);
             decimal tempEC = tempMCA.Estimate_List_Price_All__c;
             decimal tempContactAmount = tempMC.Contract_Amount__c;
             decimal tempTotalListPrice = tempMC.Estimate_Trial_Money__c;
 //            if(tempMC.RecordType_DeveloperName__c.equals('NewMaintenance_Contract')){
  //               tempContactAmount = tempMC.Estimation_Id__r.NewEstimation_Amount__c;
   //          }
             if(tempMC.Estimation_Id__c != null &&  tempMC.Estimation_Id__r.Asset_Sum_Price__c != null
               &&  tempMC.Estimation_Id__r.Asset_Sum_Price__c != 0 ){
                 tempTotalListPrice = tempMC.Estimation_Id__r.Asset_Sum_Price__c;
                 
             }
            
             if( tempContactAmount != 0 && tempContactAmount!= null
               && tempMCA.Estimate_List_Price_All__c !=null && tempTotalListPrice!=null 
                && tempTotalListPrice!=0){
                 decimal repairAmount = tempMC.Estimation_Id__c == null || tempMC.Estimation_Id__r.Asset_Repair_Sum_Price__c ==null
                     ? 0.0 : tempMC.Estimation_Id__r.Asset_Repair_Sum_Price__c;
                  tempEC = ((tempMCA.Estimate_List_Price_All__c/tempTotalListPrice)*
                           ( tempContactAmount - repairAmount)).setScale(2);
             }
             
             if(tempMCA.Maintenance_Contract_Asset_Estimate__c != null && 
                     tempMCA.Maintenance_Contract_Asset_Estimate__r.Estimate_Cost__c != tempEC
               &&!UpdateMCAEMap.containskey(tempMCA.Maintenance_Contract_Asset_Estimate__c)){
                 Maintenance_Contract_Asset_Estimate__c tempMCAE = new Maintenance_Contract_Asset_Estimate__c();
                 tempMCAE.id = tempMCA.Maintenance_Contract_Asset_Estimate__c;
                 tempMCAE.Estimate_Cost__c = tempEC;
                 UpdateMCAEMap.put(tempMCAE.id,tempMCAE);   
             }
             if(tempMCA.Estimate_Cost__c != tempEC){
                 Maintenance_Contract_Asset__c newMCA = new Maintenance_Contract_Asset__c();
                 newMCA.id = tempMCA.id;
                 newMCA.Estimate_Cost__c = tempEC;
                 UpdateMCAList.add(newMCA);
             }
            
         }
        if( UpdateMCAList.size() > 0 ){
            Database.SaveResult[] saveResults = Database.update(UpdateMCAList, false);
            totalCount = + saveResults.size();
            for (Integer i = 0; i < saveResults.size(); i++) {
                if (!saveResults.get(i).isSuccess() || Test.isRunningTest()) {
                    logstr += '维修合同保有设备:' + UpdateMCAList.get(i).Id + ' ,';
                    errorstr += saveResults.get(i).getErrors() + '\n';
                    failedCount ++;
                }
            }
        }
        if( UpdateMCAEMap.size() > 0 ){
            Database.SaveResult[] saveResults = Database.update(UpdateMCAEMap.values(), false);
            totalCount = + saveResults.size();
            for (Integer i = 0; i < saveResults.size(); i++) {
                if (!saveResults.get(i).isSuccess()) {
                    logstr += '维修合同报价保有设备:' + UpdateMCAEMap.values().get(i).Id + ' ,';
                    errorstr += saveResults.get(i).getErrors() + '\n';
                    failedCount ++;
                }
            }
        }
        
    }
    global void finish(Database.BatchableContext BC) {
        BatchIF_Log__c batchIfLog = new BatchIF_Log__c();
        batchIfLog.Type__c = 'MCAssetUpdateEstimateCost';
        if (logstr.length() > 60000) {
            logstr = logstr.substring(0, 60000);
        }
        batchIfLog.Log__c = logstr;
        logstr += '\nBatchMCAssetUpdateEstimateCostEnd';
        if (errorstr.length() > 60000) {
            batchIfLog.ErrorLog__c = errorstr.substring(0, 60000);
        } else {
            batchIfLog.ErrorLog__c = errorstr.substring(0, errorstr.length());
        }
        insert batchIfLog;
        emailMessages.add('失败日志ID为：' + batchIfLog.Id);
        sendFieldEmail();
        
    }
    // 发送提醒邮件
    private void sendFieldEmail() {
        PretechBatchEmailUtil be = new PretechBatchEmailUtil();
        String[] toList = new String[] {UserInfo.getUserEmail()};
        String title = '更新维修合同保有设备报价金额失败';
        String[] ccList = new String[] {};
        if (System.Test.isRunningTest()) {
            be.successMail('', 1);
        }
        if (emailMessages.size() > 0 && failedCount > 0) {
            be.failedMail(toList, ccList, title,
                          String.join(this.emailMessages, '\n'),
                          totalCount, totalCount - failedCount, failedCount,'',false);
            if(!Test.isRunningTest())
                be.send();
        }
    }
    
}