/**************************************************************************************************
@Author: Denny陈帮才
@Name: SumAnnualRepairAmountBatch
@CreateDate: 22/08/2022
@Description: 汇总用户年修理金额
@Version 1.0
*****************************************************************************************************/
global class SumAnnualRepairAmountBatch implements Database.Batchable<sObject>,Database.Stateful {
    public String query;
    public List < String > accountIdList;
    private BatchIF_Log__c iflog;
    public Date nowDt =Date.today();
    public String OCSM_Period_half;
    public String OCSM_Period;
    public Date sTime;
    public Date eTime;
    public String hospitalName;

    global SumAnnualRepairAmountBatch() {
        this.query = query;
    }

    global SumAnnualRepairAmountBatch(List <String> accountIdList) {
        this.query = query;
        this.accountIdList = accountIdList;
    }

    global Database.QueryLocator start(Database.BatchableContext bc) {
        system.debug('执行start');
        iflog = new BatchIF_Log__c();
        iflog.Type__c = 'PushNotification';
        iflog.Log__c  = 'SumAnnualRepairAmountBatch start\n';
        iflog.ErrorLog__c = '';
        insert iflog;
        //判断过去一年时间
        if(nowDt.month() >= 4){
            sTime = Date.newInstance(nowDt.year()-3,4,1);
            eTime = Date.newInstance(nowDt.year(),4,1);
        }else{
            sTime = Date.newInstance(nowDt.year()-4,4,1);
            eTime = Date.newInstance(nowDt.year()-1,4,1);
        }
        //修理表查询 修理单的金额
        // query = 'select Id,Hospital__c,PurchaseOrInstallationDate__c,Repair_List_Price_formula__c from Repair__c where Agreed_Date__c >=:sTime and Agreed_Date__c <:eTime 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.取消\'  ';
        query = 'select Id from Account where Id IN(select Hospital__c  from Repair__c where Agreed_Date__c >=:sTime and Agreed_Date__c <:eTime 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.取消\')  ';

        if (accountIdList != null && accountIdList.size() > 0) {
            query += ' AND Id IN :accountIdList ';
        }
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, list<Account> accounts) {
        System.debug(LoggingLevel.INFO, '*** excute start: ' );
        if (nowDt.month() >= 4 && nowDt.month() <= 9) {
            OCSM_Period_half = '1H';
        }else{
            OCSM_Period_half = '2H';
        }
        if(nowDt.month() >= 1 && nowDt.month() <= 3){
            OCSM_Period = 'FY'+(nowDt.year());
        }else{
            OCSM_Period = 'FY'+(nowDt.year()+1);
        }
        System.debug(LoggingLevel.INFO, '*** the OCSM_Period_half__c: ' + OCSM_Period_half);
        System.debug(LoggingLevel.INFO, '*** the OCSM_Period: ' + OCSM_Period);

        // List<Id>scopeId = new List<Id>();
        List<Id>hosId = new List<Id>();

        for (Account acco : accounts) {
            hosId.add(acco.Id);
        }

        List<Repair__c> scope = [SELECT Id,Hospital__c,PurchaseOrInstallationDate__c,Repair_List_Price_formula__c 
                                 FROM Repair__c where Hospital__c IN:hosId
                                 AND Agreed_Date__c >=:sTime AND Agreed_Date__c <:eTime 
                                 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.取消'];


        //汇总 修理原价 安装日期小于12个月的 算平均月 再*12
        Map<Id,Decimal> HosMoneys = new Map<Id,Decimal>();
        for (Repair__c mcc : scope) {
            // scopeId.add(mcc.Id);
            // hosId.add(mcc.Hospital__c);
            // Date purDate = mcc.PurchaseOrInstallationDate__c;
            // if(purDate!=null){
            //     Decimal bMonth = purDate.monthsBetween(eTime);
            //     Decimal hmoney = 0;
            //     if(bMonth < 0){
            //         bMonth *=-1;
            //     }
            //     //设备 安装日期至 Etime 不足三年的 按平均月计算再乘12
            //     if((bMonth < 12 * 3 ) && bMonth > 0){
            //     hmoney = (mcc.Repair_List_Price_formula__c / bMonth) *12;
            //     }else{
            //         hmoney = mcc.Repair_List_Price_formula__c;
            //     }
            //     if(HosMoneys.containsKey(mcc.Hospital__c)){
            //         HosMoneys.put(mcc.Hospital__c, HosMoneys.get(mcc.Hospital__c)+hmoney);
            //     }else{
            //     HosMoneys.put(mcc.Hospital__c, hmoney);
            //     }
            // }
            //2022/12/19 修改 不计算设备年龄 直接除以3
            if(mcc.Repair_List_Price_formula__c>0 && mcc.Repair_List_Price_formula__c!=null){
                Decimal hmoney = (mcc.Repair_List_Price_formula__c /3);

                if(HosMoneys.containsKey(mcc.Hospital__c)){
                    HosMoneys.put(mcc.Hospital__c, HosMoneys.get(mcc.Hospital__c)+hmoney);
                }else{
                HosMoneys.put(mcc.Hospital__c, hmoney);
                }
            }

           
        }


        //汇总修理表中医院 修理金额
        // List<AggregateResult> LastyearList = [
        //     select
        //     sum(Repair_List_Price_formula__c) SumPrice,
        //     Hospital__c
        //     from
        //     Repair__c
        //     where
        //     Id in:scopeId
        //     group by Hospital__c
        // ];  
        // //存医院 以及医院年修理金额
        // Map<Id,Decimal> LastYearPriceSumMap = new Map<Id,Decimal>();   
        // for (AggregateResult Rpc : LastyearList) {
        //     Id idf        = String.valueOf(Rpc.get('Hospital__c'));
        //     Decimal Defir = (Decimal)Rpc.get('SumPrice');

        //     LastYearPriceSumMap.put(idf, Defir);
        // } 
        
        //服务客户目标对象里 医院在scope里以及年份等于查询年份的
        List<Account_Service_Of_Target__c> asotList = [select Id,Account_HP__c 
                                                    from Account_Service_Of_Target__c 
                                                    where Account_HP__c in: hosId 
                                                    and OCSM_Period_half__c = :OCSM_Period_half
                                                    and OCSM_Period__c = :OCSM_Period];
        Map<Id,Account_Service_Of_Target__c> oldMap = new Map<Id,Account_Service_Of_Target__c>();
        for (Account_Service_Of_Target__c ast : asotList) {
            oldMap.put(ast.Account_HP__c,ast);
        }

        // Map<Id,Decimal>hospitalName = new Map<Id,Decimal>();
        List<Account_Service_Of_Target__c> hospital = new List<Account_Service_Of_Target__c>();
        for (Repair__c mc: scope) {
            // if(hospitalName.containsKey(mc.Hospital__c)){
            //     // hospitalName.get(mc.Hospital__c) += mc.Request_quotation_AmountF__c;
            //     hospitalName.put(mc.Hospital__c, hospitalName.get(mc.Hospital__c) + mc.Request_quotation_AmountF__c);
            // }else{
            //     hospitalName.put(mc.Hospital__c,mc.Request_quotation_AmountF__c);
            // }
            try{
                Account_Service_Of_Target__c ast = new Account_Service_Of_Target__c();
                ast.Account_HP__c = mc.Hospital__c;
                ast.Annual_repair_amount__c = HosMoneys.get(mc.Hospital__c);
                ast.OCSM_Period_half__c = OCSM_Period_half;
                ast.OCSM_Period__c = OCSM_Period;
                if(oldMap.containsKey(mc.Hospital__c)){
                    ast.Id = oldMap.get(mc.Hospital__c).Id;
                }
                if(!hospital.contains(ast)){
                    hospital.add(ast); 
                }      
            }catch(Exception e){
                System.debug(LoggingLevel.INFO, '*** mc.Id: ' + mc.Id);
                System.debug(LoggingLevel.INFO, '*** mc: ' + mc);
            }
                      
        }

        upsert hospital;

    }

    global void finish(Database.BatchableContext BC) {
        iflog.Log__c += '\nSumAnnualRepairAmountBatch 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;
    }
}