/*
* 2021-04-16  mzy  
* 每天凌晨跑batch查找 是否更新保有设备字段 为true的点检报告书，并更新保有设备，更新成功后把点检报告书的勾取消。
*/
global class UpdateInspectionReportAssetBatch implements Database.Batchable<sObject>,Database.stateful {
    Boolean IsNeedExecute = false;
    String tempReportId ='';
    List<Inspection_Report__c> updateReportList = new List<Inspection_Report__c>();

    global UpdateInspectionReportAssetBatch() {

    }

    global UpdateInspectionReportAssetBatch(String tempId) {
        this.tempReportId = tempId;
    }

    global UpdateInspectionReportAssetBatch(Boolean NeedExecute) {
        this.IsNeedExecute = NeedExecute;
    }


    global Database.QueryLocator start(Database.BatchableContext bc) {

        //查询 是否更新保有设备 为true的点检报告书
        String query = 'SELECT Id FROM Inspection_Report__c WHERE if_UpdateAsset__c = true ';
               //query += ' AND Name != null AND Name = null';
        if(String.isNotBlank(this.tempReportId)){
            query += ' AND Id = :tempReportId';
        }

        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, list<Inspection_Report__c> InspectionReportList) {


        //查询点检报告书下的点检明细中的保有设备(后面也需要将此id的报告书的勾取消掉)
        list<String> selectId = new list<String>();
        for(Inspection_Report__c i : InspectionReportList){
            selectId.add(i.Id);
        }

        // 点检报告书中所有的保有设备
        List<String> assIds = new List<String>();
        Map<String, String> assMap = new Map<String, String>();
        List<Inspection_Item__c> iis = [select id, AssetId__c from Inspection_Item__c where Inspection_ReportId__c in :selectId];


        for (Inspection_Item__c ii : iis) {
            if (ii.AssetId__c != null && assMap.containsKey(ii.AssetId__c) == false) {
                assIds.add(ii.AssetId__c);
                assMap.put(ii.AssetId__c, ii.AssetId__c);
            }
        }


        // 保有设备对应的所有点检报告明细
        List<Inspection_Item__c> iiList = [select id, AssetId__c, Inspection_ReportId__c, Inspection_Result__c, Inspection_Comment__c, Inspection_ReportId__r.Name, Inspection_ReportId__r.Inspection_Date__c,Inspection_ReportId__r.Reporter__c,Inspection_ReportId__r.Approved_date__c
                                             from Inspection_Item__c
                                            where AssetId__c = :assIds
                                            order by Inspection_ReportId__r.Approved_date__c desc];


        Map<String, Inspection_Item__c> iiMap = new Map<String, Inspection_Item__c>();
        for (Inspection_Item__c ii : iiList) {
            if (iiMap.containsKey(ii.AssetId__c) == false && ii.Inspection_ReportId__r.Approved_date__c != null) {
                iiMap.put(ii.AssetId__c, ii);
            }
        }


        List<Asset> needUpdAssetList = new List<Asset>();
        for (String assid : assIds) {
            Inspection_Item__c tmp = iiMap.get(assid) == null ? new Inspection_Item__c() : iiMap.get(assid);
            Asset ass = new Asset(
                Id = assid,
                Inspection_report_number__c = tmp.Inspection_ReportId__r.Name,
                Inspection_Report__c = tmp.Inspection_ReportId__c,
                Inspection_Comment__c = tmp.Inspection_Comment__c,
                Inspection_Result__c = tmp.Inspection_Result__c,
                Final_Examination_Date__c = tmp.Inspection_ReportId__r.Inspection_Date__c,
                Last_Inspection_staff__c = tmp.Inspection_ReportId__r.Reporter__c
            );
            needUpdAssetList.add(ass);
        }


        if (needUpdAssetList.size() > 0){
            update needUpdAssetList;

            //将更新后的点检报告书的 是否更新保有设备的勾  取消掉
            for(String i : selectId){
                Inspection_Report__c tempReprot = new Inspection_Report__c();
                tempReprot.Id = i;
                tempReprot.if_UpdateAsset__c = false;
                updateReportList.add(tempReprot);
            }

        } 

        
    }

    global void finish(Database.BatchableContext BC) {
      // 更新后 将点检报告书的 是否更新保有设备的勾  取消掉
      if(updateReportList.size()>0){
         update updateReportList;
      }

      //2021-04-21  mzy  add SFDCBatch合并 start
      if(!Test.isRunningTest() &&IsNeedExecute==true){
         //batch里调用下一个batch时，希望跟原有的Schedule里面传的条数保持一致
         Id execBTId = Database.executebatch(new AssetUpdateContractBatch(true),5);
     }
     //2021-04-21  mzy  add SFDCBatch合并 end

    }
    //2021-09-01   mzy  希望用点检Trigger 来调用一下Batch异步更新 保有设备的信息 完成更新  start
    @Future
    WebService static void updateAssetFun(List<String> InpIdList){

        List<Inspection_Report__c> IpsList = [SELECT Id,Status__c FROM Inspection_Report__c where Id IN :InpIdList];

        List<String> SQZ_List = new List<String>();
        if(IpsList.size()>0){
            for(Inspection_Report__c ir :IpsList){
                if('申请中'.equals(ir.status__c)){
                    SQZ_List.add(ir.Id);
                }
            }
        }

        // 点检报告书中所有的保有设备
        List<String> assIds = new List<String>();
        Map<String, String> assMap = new Map<String, String>();
        List<Inspection_Item__c> iis = [select id, AssetId__c,Inspection_ReportId__c,Inspection_ReportId__r.Inspection_Date__c,Inspection_ReportId__r.Name from Inspection_Item__c where Inspection_ReportId__c in :InpIdList];
        
        Set<String> assSet = new Set<String>();
        Map<String,Inspection_Item__c> assIiMap = new Map<String,Inspection_Item__c>();

        for (Inspection_Item__c ii : iis) {
            //批准
            if (ii.AssetId__c != null && assMap.containsKey(ii.AssetId__c) == false&&!SQZ_List.contains(ii.Inspection_ReportId__c)) {
                assIds.add(ii.AssetId__c);
                assMap.put(ii.AssetId__c, ii.AssetId__c);
            }

            //申请中
            if(SQZ_List.contains(ii.Inspection_ReportId__c)&&ii.AssetId__c!=null){
                assSet.add(ii.AssetId__c);
                assIiMap.put(ii.AssetId__c,ii);
            }
        }

        //申请中的需要将点检日赋值到设备上
        if(assSet.size()>0){
            List<Asset> needUpdAssetList_SQZ = new List<Asset>();
            for(String assId :assSet){
                Asset ass = new Asset();
                ass.Id = assId;
                ass.Final_Examination_Date__c = assIiMap.get(assId).Inspection_ReportId__r.Inspection_Date__c;
                ass.Inspection_report_number__c = assIiMap.get(assId).Inspection_ReportId__r.Name;
                needUpdAssetList_SQZ.add(ass);
            }

            update needUpdAssetList_SQZ;
        }
         
        if(assIds.size()==0){
            //没有批准了的点检报告书则不需要走下面的代码
            return;
        }

        // 保有设备对应的所有点检报告明细
        List<Inspection_Item__c> iiList = [select id, AssetId__c, Inspection_ReportId__c, Inspection_Result__c, Inspection_Comment__c, Inspection_ReportId__r.Name, Inspection_ReportId__r.Inspection_Date__c,Inspection_ReportId__r.Reporter__c,Inspection_ReportId__r.Approved_date__c
                                             from Inspection_Item__c
                                            where AssetId__c = :assIds
                                            order by Inspection_ReportId__r.Approved_date__c desc];


        Map<String, Inspection_Item__c> iiMap = new Map<String, Inspection_Item__c>();
        for (Inspection_Item__c ii : iiList) {
            if (iiMap.containsKey(ii.AssetId__c) == false && ii.Inspection_ReportId__r.Approved_date__c != null) {
                iiMap.put(ii.AssetId__c, ii);
            }
        }


        List<Asset> needUpdAssetList = new List<Asset>();
        for (String assid : assIds) {
            Inspection_Item__c tmp = iiMap.get(assid) == null ? new Inspection_Item__c() : iiMap.get(assid);
            Asset ass = new Asset(
                Id = assid,
                Inspection_report_number__c = tmp.Inspection_ReportId__r.Name,
                Inspection_Report__c = tmp.Inspection_ReportId__c,
                Inspection_Comment__c = tmp.Inspection_Comment__c,
                Inspection_Result__c = tmp.Inspection_Result__c,
                Final_Examination_Date__c = tmp.Inspection_ReportId__r.Inspection_Date__c,
                Last_Inspection_staff__c = tmp.Inspection_ReportId__r.Reporter__c
            );
            needUpdAssetList.add(ass);
        }


        if (needUpdAssetList.size() > 0){
            update needUpdAssetList;
        } 
    }
    //2021-09-01  mzy  希望用点检Trigger 来调用一下Batch异步更新 保有设备的信息 完成更新   end

}