/**************************************************************************************************
@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 = 'FY'+(nowDt.year()+1);
    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()-1,4,1);
            eTime = Date.newInstance(nowDt.year(),3,31);
        }else{
            sTime = Date.newInstance(nowDt.year()-2,4,1);
            eTime = Date.newInstance(nowDt.year()-1,3,31);
        }
        //修理表查询 修理单的金额
        query = 'select Id,Hospital__c from Repair__c where Agreed_Date__c >=:sTime and Agreed_Date__c <=:eTime and Discount_Price_formula__c !=null and Discount_Price_formula__c!=0 ';

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

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

        List<Id>scopeId = new List<Id>();
        List<Id>hosId = new List<Id>();
        for (Repair__c mcc : scope) {
            scopeId.add(mcc.Id);
            hosId.add(mcc.Hospital__c);
        }


        //汇总修理表中医院 修理金额
        List<AggregateResult> LastyearList = [
            select
            sum(Discount_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);
            // }
            Account_Service_Of_Target__c ast = new Account_Service_Of_Target__c();
            ast.Account_HP__c = mc.Hospital__c;
            ast.Annual_repair_amount__c = LastYearPriceSumMap.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); 
            }                
        }

        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;
    }
}