/**************************************************************************************************
@Author: Denny陈帮才
@Name: SumEquipmentInventoryBatch
@CreateDate: 22/08/2022
@Description: 汇总医院为目标有效保有设备量(软性镜)
@Version 1.0
*****************************************************************************************************/
global class SumEquipmentInventoryBatch implements Database.Batchable<sObject>,Database.Stateful {
    public String query;
    public Date nowDt =Date.today();
    private BatchIF_Log__c iflog;
    public String OCSM_Period_half;
    public String OCSM_Period = 'FY'+(nowDt.year()+1);
    // public Date sTime;
    // public Date eTime;
    public List < String > accountIdList;

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

    global SumEquipmentInventoryBatch(List < String > accountIdList) {
        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  = 'SumEquipmentInventoryBatch 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 Asset where Product2.Service_Category3__c=\'软性镜\' and Status =\'使用中\' and Asset_Year__c >=:sTime and Asset_Year__c <=:eTime';
        query = 'select Id, Hospital__c from Asset where Product2.Service_Category3__c=\'软性镜\' and Status !=\'廃棄\' and Status!=\'待报废\'  ';

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

    global void execute(Database.BatchableContext BC, list<Asset> assList) {
        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> assetId = new List<Id>();
        List<Id> assetHosId = new List<Id>();
        for (Asset ast : assList) {
            assetId.add(ast.Id);
            assetHosId.add(ast.Hospital__c);
        }
        //服务客户目标对象里 医院在scope里以及年份等于查询年份的
        List<Account_Service_Of_Target__c> asotList = [select Id,Account_HP__c 
                                                    from Account_Service_Of_Target__c 
                                                    where Account_HP__c in: assetHosId 
                                                    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);
        }

        //汇总
        AggregateResult[] aggResult = [SELECT Hospital__c,COUNT(Id)countalias
                                       FROM Asset WHERE Id IN: assetId 
                                       group by Hospital__c];   
        Map<Id,Decimal> countMap = new Map<Id,Decimal>();
        for (AggregateResult ass : aggResult ) {
            Id  assId= (Id)ass.get('Hospital__c');
            Decimal Defir = (Decimal)ass.get('countalias');
            countMap.put(assId, Defir);  
        }
        List<Account_Service_Of_Target__c> asList = new List<Account_Service_Of_Target__c>();
        for (Id mapId : countMap.keySet()) {
            Account_Service_Of_Target__c asItem = new Account_Service_Of_Target__c();
            asItem.Account_HP__c = mapId;
            //保有设备数量（软性镜）
            asItem.Equipment_Inventory_No__c = countMap.get(mapId);
            asItem.OCSM_Period_half__c = OCSM_Period_half;
            asItem.OCSM_Period__c = OCSM_Period;

            if(oldMap.containsKey(asItem.Account_HP__c)){
                asItem.Id = oldMap.get(asItem.Account_HP__c).Id;
            }
            if(!asList.contains(asItem)){
                asList.add(asItem);
            }
        }
        System.debug(LoggingLevel.INFO, '*** asList: ' + asList);
        upsert asList;
    }

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

    }
}