/**************************************************************************************************
@Author: Denny陈帮才
@Name: EquipmentRepairBatch
@CreateDate: 22/08/2022
@Description: 过去三年维修实绩
@Version 1.0
*****************************************************************************************************/
global class EquipmentRepairBatch implements Database.Batchable<sObject>,Database.Stateful {
    public String query;
    public List < String > accountIdList;
    private BatchIF_Log__c iflog;
    public Date td = Date.today();  //如2022.10.15
    public String OCSM_Period_half;
    public String OCSM_Period;
    public Date eTime=td.toStartOfMonth(); //如 2022.10.1
    public Date sTime=eTime.addYears(-3);  // 2019.10.1
    public Date egdTime = Date.newInstance(td.year()+1,3,31);


    global EquipmentRepairBatch() {
        this.query = query;
        // OCSM_Period = 'FY'+(td.year()+1);
    }

    global EquipmentRepairBatch(List <String> accountIdList) {
        this.query = query;
        this.accountIdList = accountIdList;
        // OCSM_Period = 'FY'+(td.year()+1);
    }

    global Database.QueryLocator start(Database.BatchableContext bc) {
        system.debug('执行start');
        iflog = new BatchIF_Log__c();
        iflog.Type__c = 'PushNotification';
        iflog.Log__c  = 'EquipmentRepairBatch start\n';
        iflog.ErrorLog__c = '';
        insert iflog;
        if (td.month() >= 4 && td.month() <= 9) {
            OCSM_Period_half = '1H';
        }else{
            OCSM_Period_half = '2H';
        }

        if(td.month() >= 1 && td.month() <= 3){
            OCSM_Period = 'FY'+(td.year());
        }else{
            OCSM_Period = 'FY'+(td.year()+1);
        }

       
        //2022/12/28 修改筛选条件 同步kpi设备
        query ='SELECT Maintenance_Contract__c,Asset__c,Maintenance_Contract__r.Hospital__c FROM Maintenance_Contract_Asset__c WHERE Maintenance_Contract__r.RecordType.Name  =\'多年保修合同\' ';
       
        
        System.debug(LoggingLevel.INFO, '*** query: ' + query);
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, list<Maintenance_Contract_Asset__c> resultList) {
        
        system.debug('*** 执行execute');
        System.debug(LoggingLevel.INFO, '*** 查询IF_Coverage_Target_Asset_F__c=1的保有设备Id JSON resultList: ' + JSON.Serialize(resultList));

        //查询是否有维修合同 类型 分别统计维修金额
        //保有设备 1.有无维修合同（字段）2.

       // List<Id> mids = new List<Id>();
       Set<Id> mids = new Set<Id>();

        //医院Id
        List<Id> assetHos = new List<Id>();
        List<Asset> AssetUpdate = new List<Asset>();
        Map<Id,Id> assetMcaIdall = new Map<Id,Id>();
        Map<Id,Id> assetMcaId = new Map<Id,Id>();
                //查询维修合同记录类型是服务合同以及服务类型的 维修合同Id 更新字段（是否有签约历史）
        for (Maintenance_Contract_Asset__c mcas : resultList) {
            assetMcaId.put(mcas.Asset__c, mcas.Maintenance_Contract__c);
            if (!mids.contains(mcas.Asset__c)) {
                AssetUpdate.add(new Asset(Id=mcas.Asset__c));               
            }
            mids.add(mcas.Asset__c);
            assetHos.add(mcas.Maintenance_Contract__r.Hospital__c);
           
        }

        //查询服务目标客户
        Map<String,Account_Service_Of_Target__c> targetMap = new Map<String,Account_Service_Of_Target__c>();
        for(Account_Service_Of_Target__c asotList:[SELECT Id ,Account_HP__c,OCSM_Period_half__c,Three_Years_Repair_Cost_Soft_Mirror__c,Three_Years_Repair_Cost_Text__c,Three_Years_Repair_Cost_Surrounding_Area__c,Three_Years_Repair_Cost_Hard_Mirror__c 
                                                FROM Account_Service_Of_Target__c 
                                                WHERE OCSM_Period_half__c = :OCSM_Period_half 
                                                AND OCSM_Period__c = :OCSM_Period
                                                AND Account_HP__c IN:assetHos]){
            targetMap.put(asotList.Account_HP__c,asotList);
        }


        //存客户服务目标对象 医院Id 后续判断 有则给Id赋值。
        // Map<Id,Account_Service_Of_Target__c> hospMap = new Map<Id,Account_Service_Of_Target__c>();
        // for (Account_Service_Of_Target__c ast : asotList) {
        //     hospMap.put(ast.Account_HP__c,ast);
        // }

        //最后upsert客户服务目标对象 list目标
        List<Account_Service_Of_Target__c> asslist = new List<Account_Service_Of_Target__c>();
        //保有设备为单位 过去三年维修实绩
        Map<Id,Decimal> ThreeYearPriceSumMap = new Map<Id,Decimal>();

        //过去三年维修实际 2022/10/13 修改 为当前时间的上一个月最后一天 往前推三年 
        for(Repair__c rp :[SELECT Hospital__c,PurchaseOrInstallationDate__c,Repair_List_Price_formula__c,Delivered_Product__c 
                           FROM Repair__c WHERE Delivered_Product__c in:mids
                           AND Repair_List_Price_formula__c !=null 
                           AND Repair_List_Price_formula__c!=0 
                           AND Status1__c!='0.删除' 
                           AND Status1__c!='0.取消' 
                           AND Status2__c!='00.删除' 
                           AND Status2__c!='00.取消'
                           AND Agreed_Date__c >=:sTime 
                           AND Agreed_Date__c <:eTime 
                           ]){
            Date purDate = rp.PurchaseOrInstallationDate__c;
            if(purDate!=null){
                Decimal bDay = purDate.daysBetween(eTime);
                Decimal hmoney = 0;
                if(bDay < 0){
                    bDay *=-1;
                }
                //设备年龄不足三年的 按平均每天计算 再乘 365 再乘 3
                if((bDay < 365*3) && bDay>0){
                    hmoney = (rp.Repair_List_Price_formula__c / bDay) *365*3;
                }else{
                    hmoney = rp.Repair_List_Price_formula__c / 3;
                }
                if(ThreeYearPriceSumMap.containsKey(rp.Delivered_Product__c)){
                    ThreeYearPriceSumMap.put(rp.Delivered_Product__c, ThreeYearPriceSumMap.get(rp.Delivered_Product__c)+hmoney);
                }else{
                    ThreeYearPriceSumMap.put(rp.Delivered_Product__c, hmoney);
                }

            }
            
        }
        


        //以医院为对象存储医院所有保有设备List
        // Map<Id,List<Asset>> aMapLists =  new Map<Id,List<Asset>>(); 
         
        // for (Asset assertItem : resultList) {
        for (Asset assertItem : AssetUpdate) {


            //更新字段：执行中的合同 
            // if(assetMcaIdall.containsKey(assertItem.Id)){
            //     assertItem.Maintenance_Contract__c = assetMcaId.get(assertItem.Id);
            // }
            //更新字段:是否有签约历史
            if(assetMcaId.containsKey(assertItem.Id)){
                assertItem.Is_Has_Contract_History__c = '1';
            }else{
                assertItem.Is_Has_Contract_History__c = '0';
            }
            if(ThreeYearPriceSumMap.containsKey(assertItem.Id)){
                assertItem.Three_Years_Repair_Cost_Text__c = ThreeYearPriceSumMap.get(assertItem.Id); 
                assertItem.IF_Maintenance_Equipment__c = 'Y';          
                 
            }
           

        }
        update AssetUpdate;
        System.debug(LoggingLevel.INFO, '*** updated AssetUpdate: ' + AssetUpdate);
     


    }

    global void finish(Database.BatchableContext BC) {
        iflog.Log__c += '\nEquipmentRepairBatch end';
        String tmp = iflog.ErrorLog__c;
        if (tmp.length() > 65000) {
            tmp = tmp.substring(0, 65000);
            tmp += ' ...have more lines...';
            iflog.ErrorLog__c = tmp;
        }
        update iflog;

    }

   

}