//Database.executeBatch(new LastRepairUpdateBatch(),10);
global class LastRepairUpdateBatch  implements Database.Batchable<SObject> , Database.Stateful {
    private BatchIF_Log__c iflog;
    public String query;
    public String RepairId;// 修理ID
    global LastRepairUpdateBatch() {
        this.query = query;
    }
    global LastRepairUpdateBatch(String RepairId) {
        this.query = query;
        this.RepairId = RepairId;
    }
    global Database.QueryLocator start(Database.BatchableContext bc) {
        iflog = new BatchIF_Log__c();
        iflog.Type__c = 'LastRepairUpdateBatch';
        iflog.Log__c  = '';
        iflog.Log2__c = '';
        insert iflog;
        //  query = 'select id,name,LastRepairText__c,LastRepair__c,Repair_Inspection_Date__c  from Repair__c where LastRepairText__c != null and LastRepair__c = null and  Cycle_between_failure__c != 0 and Repair_Inspection_Date__c != null';
        query = 'select id,name,SAPRepairNo__c,LastRepairText__c,LastRepair__c,Repair_Inspection_Date__c,Hospital__c,Product_Unique_Value__c,Difference_in_repair_intervals__c  from Repair__c where LastRepairText__c != null and LastRepair__c = null and Repair_Inspection_Date__c != null '; 
        if (RepairId!= null && RepairId != '') {
            query += ' and id = :RepairId';
        }
        query += '  order by Hospital__c,Product_Unique_Value__c  asc';
        System.debug('执行结果：'+Database.getQueryLocator(query));
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, list<Repair__c> RepairList) {
        List<String> LastRepairTextList = new List<String>(); // 储存上次修理文本
        iflog.Log__c += '处理数量：'+ RepairList.size()+'\r\n';
        for (Repair__c rp : RepairList) {
            if (Test.isRunningTest()) {
                LastRepairTextList.add(rp.SAPRepairNo__c);
            }else {
                LastRepairTextList.add(rp.LastRepairText__c);
            }     
        }
        Map<Object, Object> mapName = new Map<Object, Object>();
        try {
            Map<String,Repair__c> mp = LastRepairText(LastRepairTextList);
            
            if (!mp.isEmpty()) {
                for (Repair__c rp : RepairList) {
                    iflog.Log__c  += rp.name +'====>'+rp.LastRepairText__c+'\n';
                    rp.LastRepair__c = mp.get(rp.LastRepairText__c).id;
                    if (mp.get(rp.LastRepairText__c).Cycle_between_failure__c != null && mp.get(rp.LastRepairText__c).Repair_Inspection_Date__c != null) { // 判断上一次修理的cbf是否为空
                      rp.Difference_in_repair_intervals__c = calculateDaysBetween(mp.get(rp.LastRepairText__c).Repair_Inspection_Date__c,rp.Repair_Inspection_Date__c);
                    }else if(mp.get(rp.LastRepairText__c).Repair_Inspection_Date__c != null){
                        Decimal Difference_in_repair_intervals =  mp.get(rp.LastRepairText__c).Difference_in_repair_intervals__c == null ? 0 :mp.get(rp.LastRepairText__c).Difference_in_repair_intervals__c;
                      rp.Difference_in_repair_intervals__c = calculateDaysBetween(mp.get(rp.LastRepairText__c).Repair_Inspection_Date__c,rp.Repair_Inspection_Date__c) +Difference_in_repair_intervals;
                    }else {
                        iflog.Log2__c += rp.name+'==>'+mp.get(rp.LastRepairText__c).id+'\n';
                    }
                  }
                  Database.SaveResult[] saveTenderResults = Database.update(RepairList, false);
                  for (Integer save = 0; save < saveTenderResults.size(); save++) {
                     Database.SaveResult sr = saveTenderResults[save];
                     if (!sr.isSuccess()) {
                        Database.Error emsg = sr.getErrors()[0];
                         iflog.ErrorLog__c += 'ERROR  ' + saveTenderResults[save].id + 'SS_oli:' + emsg + '\n';
                     }
                  }
            }
        } catch (Exception e) {
            iflog.ErrorLog__c += e.getMessage();
        }
        update iflog;
    }
    global void finish(Database.BatchableContext BC) {
       
    }

    public static Map<String,Repair__c>  LastRepairText(List<String> LastRepairText){
        Map<String, Repair__c> mapName = new Map<String, Repair__c>();
        List<Repair__c> rpList = null;
        if (!Test.isRunningTest()) {
            rpList = [select id,name,Repair_Inspection_Date__c,Cycle_between_failure__c,Difference_in_repair_intervals__c from Repair__c where name in:LastRepairText];
        }else {
            rpList = [select id,name,Repair_Inspection_Date__c,Cycle_between_failure__c,Difference_in_repair_intervals__c from Repair__c where SAPRepairNo__c in:LastRepairText];
        }
        for (Repair__c rp : rpList) {
            mapName.put(rp.name,rp);
        }
        return mapName;
    }
    public static Integer calculateDaysBetween(Date startDate, Date endDate) {
        // 使用Date类的daysBetween方法计算天数差异
        Integer days = startDate.daysBetween(endDate);
  
        return Math.abs(days); // 如果你希望天数始终为正数，可以使用Math.abs方法
    }
}