global class AssetWhereabouts implements Database.Batchable<sObject>,Database.Stateful {
    public String query;
    public BatchIF_Log__c iflog ;
    public Date toDay = Date.today();
    public List < String > assetIdList;
    global AssetWhereabouts() {
        this.query = query;
    }
    global AssetWhereabouts(List < String > assetIdList) {
        this.query = query;
        this.assetIdList = assetIdList;
    }
    global Database.QueryLocator start(Database.BatchableContext bc) {
        iflog  = new BatchIF_Log__c();
        iflog.Type__c = 'PushNotification';
        iflog.Log__c  = 'AssetWhereabouts start\n';
        iflog.ErrorLog__c = '';
        insert iflog;
        query = 'select id,Asset__r.AssetWhereabouts__c,Maintenance_Contract__r.status__c ,Asset__r.id,Maintenance_Contract__r.id,endDateGurantee_Text__c  '
                +' from Maintenance_Contract_Asset__c where Maintenance_Contract__r.RecordType_Name__c =\'多年保修合同\' and endDateGurantee_Text__c < :toDay and Asset__r.AssetWhereabouts__c!=\'服务合同\'';
        if (assetIdList != null && assetIdList.size() > 0) {
            query += ' and Asset__c in :assetIdList ';
        }
        query += '  order by CreatedDate ';
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, list<Maintenance_Contract_Asset__c> mcaList) {
        Map<String,Asset> assMap = new Map<String,Asset>();
        // 用作查询合同中的服务合同
        Set<String> assSet = new Set<String>();
        Set<String> fuwuSet = new Set<String>();
        // 用作查询一般维修
        Set<String> weixiuSet = new Set<String>();
        Map<String,Repair__c> mcMap = new Map<String,Repair__c>();
         for (Maintenance_Contract_Asset__c  mca: mcaList) {
            assSet.add(mca.Asset__r.id);
            weixiuSet.add(mca.Asset__r.id);
        }

        // 查询符合条件的修理
        List<Repair__c> reList  = [select id,Maintenance_Contract__r.id,Status1__c,Failure_Occurrence_Date__c,CreatedDate,Delivered_Product__c  
                                    from Repair__c 
                                    where Status1__c != '0.取消' and Status1__c != '0.删除' and Status2__c != '00.删除' and Status2__c != '00.取消'
                                   and Maintenance_Contract__c = null  and Delivered_Product__c in :weixiuSet order by CreatedDate ];
        for (Repair__c re: reList) {
             if ( mcMap.get(re.Delivered_Product__c)==null) {
                 mcMap.put(re.Delivered_Product__c,re);
            }
            // 取最近一期的修理记录
            if( mcMap.get(re.Delivered_Product__c)!=null && re.CreatedDate>mcMap.get(re.Delivered_Product__c).CreatedDate){
                mcMap.remove(re.Delivered_Product__c);
                mcMap.put(re.Delivered_Product__c,re);
            }
        }
       // 查询是否有合同中的服务合同
        list<Maintenance_Contract_Asset__c>   mcaList2 = [select Id,Asset__r.id from Maintenance_Contract_Asset__c 
                                                          where Maintenance_Contract__r.RecordType_Name__c ='服务合同' 
                                                          and Maintenance_Contract__r.status__c ='契約' and Asset__c in :assSet];
        for (Maintenance_Contract_Asset__c mca: mcaList2) {
                fuwuSet.add(mca.Asset__r.id);
        }                                                 


        for (Maintenance_Contract_Asset__c  mca: mcaList) {
                Asset ass =  new Asset();
                Date PassDay = mca.endDateGurantee_Text__c.addyears(1);
                Boolean isXiuli = false;
                // 判断修理是否是未来1年内
                if (mcMap.get(mca.Asset__r.id)!=null &&mcMap.get(mca.Asset__r.id).Failure_Occurrence_Date__c>mca.endDateGurantee_Text__c && mcMap.get(mca.Asset__r.id).Failure_Occurrence_Date__c < PassDay) {
                    isXiuli = true;
                }
                // 去向：服务合同   关联的执行中合同记录为【服务合同】状态为契约
            if (fuwuSet.contains(mca.Asset__r.id)) {
                ass.id = mca.Asset__r.id;
                ass.AssetWhereabouts__c = '服务合同';
                if (assMap.containsKey(ass.id)&&assMap.get(ass.id).AssetWhereabouts__c =='其他') {
                    assMap.remove(ass.id);
                    assMap.put(ass.id,ass);
                }else{
                    assMap.put(ass.id,ass);
                }
            }
            // 去向：一般维修
             else if(mca.Maintenance_Contract__r.status__c  != '契約' && isXiuli){
                    ass.id = mca.Asset__c;
                    ass.AssetWhereabouts__c = '一般维修';
                    if (assMap.containsKey(ass.id)&&assMap.get(ass.id).AssetWhereabouts__c =='其他') {
                        assMap.remove(ass.id);
                        assMap.put(ass.id,ass);
                     }else{
                        assMap.put(ass.id,ass);
                     }
            } else {
                // 去向：其他
                    ass.id = mca.Asset__c;
                    ass.AssetWhereabouts__c = '其他';
                    
                    if (!assMap.containsKey(ass.id)) {
                        assMap.put(ass.id,ass);
                    }
            }
        } 
        system.debug('更新数据='+assMap.values());
        if (assMap.values()!=null && assMap.values().size()!= 0) {
            update assMap.values();
        }  
    }

    global void finish(Database.BatchableContext BC) {

        iflog.Log__c += '\nAssetWhereabouts end';
        String tmp = iflog.ErrorLog__c;
        integer i=0;
        i++;
        if (tmp.length() >= 5000) {
            tmp = tmp.substring(0, 5000);
            tmp += ' ...have more lines...';
            iflog.ErrorLog__c = tmp;
        }
        update iflog;
    }
}