/**************************************************************************************************
@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;
    // 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.ServiceCategory__c=\'软性镜\' and Status !=\'廃棄\' and Status!=\'待报废\'';
        query = 'select Id from Account where Id IN( select Hospital__c from Asset where Status !=\'廃棄\' and Status!=\'待报废\' and OwnershipMachine_No__c!=null  and Product2.Maintenance_Price_Year__c>0 and Product2.Maintenance_Price_Year__c!=null and Asset_Owner__c =\'病院資産\')';
        // query = 'select Id from Account where Id IN( select Hospital__c from Asset where Product2.ServiceCategory__c=\'软性镜\' and Status !=\'廃棄\' and Status!=\'待报废\')';



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

    global void execute(Database.BatchableContext BC, list<Account> assList) {
        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);

        // 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);
        // }
        for (Account  acco : assList) {
            assetHosId.add(acco.Id);
        }

        //服务客户目标对象里 医院在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 Hospital__c IN: assetHosId
        //                                AND Product2.ServiceCategory__c='软性镜' 
        //                                AND Status !='廃棄' AND Status!='待报废' 
        //                                AND OwnershipMachine_No__c!=null 
        //                                AND Brand_Name__c='奥林巴斯' 
        //                                AND Maintenance_Price_Year__c>0 
        //                                AND Maintenance_Price_Year__c!=null  
        //                                AND Asset_OwnerNew__c ='医院资产'
        //                                group by Hospital__c];   
        Map<Id,Decimal> countMap1 = new Map<Id,Decimal>();
        Map<Id,Decimal> countMap2 = new Map<Id,Decimal>();
        Map<Id,Decimal> countMap3 = new Map<Id,Decimal>();
        List<String> HosIds = new List<String>();
        // for (AggregateResult ass : aggResult ) {
        //     Id  assId= (Id)ass.get('Hospital__c');
        //     Decimal Defir = (Decimal)ass.get('countalias');
        //     countMap.put(assId, Defir); 
        //     System.debug(LoggingLevel.INFO, '*** 医院Id: ' + assId);
        //     System.debug(LoggingLevel.INFO, '*** 保有设备数量: ' + Defir); 
        // }
        // Decimal rcount = new Decimal();
        for (Asset ass : [SELECT Hospital__c,Id,Product2.ServiceCategory__c FROM Asset WHERE Hospital__c IN: assetHosId
                                       // AND Product2.ServiceCategory__c='软性镜' 
                                       AND Status !='廃棄' AND Status!='待报废' 
                                       AND OwnershipMachine_No__c!=null 
                                       // AND Brand_Name__c='奥林巴斯' 
                                       AND Product2.Maintenance_Price_Year__c>0 
                                       AND Product2.Maintenance_Price_Year__c!=null  
                                       AND Asset_Owner__c ='病院資産'
                                       // AND AssetMark__c!='耗材'
                                       ]) {
            HosIds.add(ass.Hospital__c);
            System.debug(LoggingLevel.INFO, '*** ass.Product2.ServiceCategory__c: ' + ass.Product2.ServiceCategory__c);
            if(ass.Product2.ServiceCategory__c =='软性镜'){
                if(countMap1.containsKey(ass.Hospital__c)){
                    countMap1.put(ass.Hospital__c, countMap1.get(ass.Hospital__c)+1);
                }else{
                    countMap1.put(ass.Hospital__c, 1);
                }
            }else if(ass.Product2.ServiceCategory__c =='硬性镜'){
                if(countMap2.containsKey(ass.Hospital__c)){
                    countMap2.put(ass.Hospital__c, countMap2.get(ass.Hospital__c)+1);
                }else{
                    countMap2.put(ass.Hospital__c, 1);
                }
            }else if(ass.Product2.ServiceCategory__c =='周边'){
                if(countMap3.containsKey(ass.Hospital__c)){
                    countMap3.put(ass.Hospital__c, countMap3.get(ass.Hospital__c)+1);
                }else{
                    countMap3.put(ass.Hospital__c, 1);
                }
            }
            

            
        }

        List<Account_Service_Of_Target__c> asList = new List<Account_Service_Of_Target__c>();
        for (Id mapId : HosIds) {
            Account_Service_Of_Target__c asItem = new Account_Service_Of_Target__c();
            asItem.Account_HP__c = mapId;
            //保有设备数量（软性镜）
            if(countMap1.containsKey(mapId)){
                asItem.Equipment_Inventory_No__c = countMap1.get(mapId);
                System.debug(LoggingLevel.INFO, '*** asItem.Equipment_Inventory_No__c: ' + asItem.Equipment_Inventory_No__c);
            }
            //保有设备数量（硬性镜）
            if(countMap2.containsKey(mapId)){
                asItem.Equipment_Inventory_Rigid_No__c = countMap2.get(mapId);
                System.debug(LoggingLevel.INFO, '*** asItem硬性镜 数量: ' + asItem.Equipment_Inventory_No__c);

            }
            //保有设备数量（周边）
            if(countMap3.containsKey(mapId)){
                asItem.Equipment_Inventory_Correlation_No__c = countMap3.get(mapId);
                System.debug(LoggingLevel.INFO, '*** asItem.周边数量: ' + asItem.Equipment_Inventory_No__c);


            }
            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, '*** : in update 医院id' +asItem.Account_HP__c );
            // System.debug(LoggingLevel.INFO, '*** : in update 医院id' +asItem.Equipment_Inventory_No__c );

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

    }
}