/*  分2种情况
    *1.需要更新历史数据，1）历史财年数据 2）财年初4月1号
    *2.不需要更新历史数据
*/
global class ETAPPActivityManageBatch implements Database.Batchable<sObject> {
    public String query;
    public String nyear;
    public String yearLastPeriod;
    public List<String> yearList = new list<String>();

    global ETAPPActivityManageBatch() {
        this.query = query;
        Date dateNow = Date.today();
        Integer month = dateNow.month();
        Integer day = dateNow.day();

        // if (String.isBlank(nyear)) {
        //     nyear = getYear();
        //     yearLastPeriod = getLastPeriodYear();
        //     yearList.add(nyear);
        //     yearList.add(yearLastPeriod);
        // }
        // 如果4月1号，取上财年数据更新
        if (month == 4 && day == 1) {
            nyear = getLastPeriodYear();
            yearLastPeriod = getLastPeriodYear(nyear);
            yearList.add(nyear);
            yearList.add(yearLastPeriod);
        }else{
            nyear = getYear();
            yearLastPeriod = getLastPeriodYear();
            yearList.add(nyear);
            yearList.add(yearLastPeriod);
        }


    }
    global ETAPPActivityManageBatch(String nyear) {
        this.query = query;
        this.nyear = nyear;
        yearLastPeriod = getLastPeriodYear(nyear);
        yearList.add(nyear);
        yearList.add(yearLastPeriod);
    }

    global Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator([select id, Category3__c, Category4__c, Hospital__c,
                                         ETAPP_key__c, Result__c
                                         from Product_Score_Table_History__c
                                         where OCSM_Period__c = :nyear
                                                 and RecordType.DeveloperName = 'TargetPDCA'
                                                         and Hospital__c != null
                                        ]);
    }

    global void execute(Database.BatchableContext BC, list<Product_Score_Table_History__c> scope) {
        // 获取需要查找的key
        Date dateNow = Date.today();
        Integer month = dateNow.month();
        Integer day = dateNow.day();
        List<String> etappkey = new List<String>();
        for (Product_Score_Table_History__c pst : scope) {
            etappkey.add(pst.ETAPP_key__c);
        }
        Map<String, Product_Score_Table_History__c> lastPeriodMap = new Map<String, Product_Score_Table_History__c>();
        Map<String, Product_Score_Table_History__c> agencyMap = new Map<String, Product_Score_Table_History__c>();
        List<Product_Score_Table_History__c> agencyList = [select id, OCSM_Period__c, Category3__c, Category4__c, Hospital__c, ETAPP_key__c
                from Product_Score_Table_History__c
                where OCSM_Period__c in :yearList
                and RecordType.DeveloperName in ('Agency','Company')
                                               and Hospital__c != null
                                               and ETAPP_key__c in :etappkey
                                               and Province_From_Consume__c = false
                                               and Qty__c > 0];
        for (Product_Score_Table_History__c pst : agencyList) {
            // String key = pst.Hospital__c + pst.Category3__c + pst.Category4__c;
            if (nyear.equals(pst.OCSM_Period__c) && !agencyMap.containsKey(pst.ETAPP_key__c)) {
                agencyMap.put(pst.ETAPP_key__c, pst);
            }
            if (yearLastPeriod.equals(pst.OCSM_Period__c) && !lastPeriodMap.containsKey(pst.ETAPP_key__c)) {

                lastPeriodMap.put(pst.ETAPP_key__c, pst);
            }
        }

        
        //Map<ID,Product_Score_Table_History__c> updateMap = new Map<ID,Product_Score_Table_History__c>();
        List<Product_Score_Table_History__c> updateList = new List<Product_Score_Table_History__c>();
        // 区分正常更新和 历史数据（包括4月1号）
        for (Product_Score_Table_History__c argetPDCA : scope) {
            // String key = argetPDCA.Hospital__c + argetPDCA.Category3__c + argetPDCA.Category4__c;     
            if (agencyMap.containsKey(argetPDCA.ETAPP_key__c)  && !lastPeriodMap.containsKey(argetPDCA.ETAPP_key__c) ) {
                if (!'使用'.equals(argetPDCA.Result__c)) {
                    argetPDCA.Result__c = '使用';
                    argetPDCA.Agency_Linkage__c = true;
                    updateList.add(argetPDCA);
                    // updateMap.put(argetPDCA.id,argetPDCA);
                }

            } else {
                if (nyear == getYear() && month != 4 && day != 1) {
                    argetPDCA.Result__c = null;
                    argetPDCA.Agency_Linkage__c = false;
                    updateList.add(argetPDCA);
                }else{
                    if (!'不使用'.equals(argetPDCA.Result__c)) {
                        argetPDCA.Result__c = '不使用';
                        argetPDCA.Agency_Linkage__c = true;
                        updateList.add(argetPDCA);

                    }
                }
                // if (!'不使用'.equals(argetPDCA.Result__c)) {
                    // argetPDCA.Result__c = null;
                    // argetPDCA.Agency_Linkage__c = false;
                    // updateList.add(argetPDCA);
                    // updateMap.put(argetPDCA.id,argetPDCA);

                // }
            }
        }

        if (updateList.size() > 0) {
            update updateList;
        }
        // if (updateMap.size() > 0) {
        //     update updateMap.values();
        // }


    }

    global void finish(Database.BatchableContext BC) {

    }

    public static string getYear() {
        Date dateNow = Date.today();
        Integer year = dateNow.year();
        Integer month = dateNow.month();
        if (month < 4) {
            year -= 1;
        }
        Integer tempiYear = year + 1;
        string currentPeriod = String.valueOf('FY' + tempiYear);
        return currentPeriod;
    }
    public static String getLastPeriodYear() {
        Date dateNow = Date.today();
        Integer year = dateNow.year();
        Integer month = dateNow.month();
        if (month < 4) {
            year -= 1;
        }
        Integer lastPeriodYear = year;
        string currentlastPeriodYear = String.valueOf('FY' + lastPeriodYear);
        return currentlastPeriodYear;
    }

    public static String getLastPeriodYear(String thisyear) {
        string lastPeriod;
        if (String.isNotBlank(thisyear) && thisyear.length() > 4) {
            Integer lastPeriodYear = Integer.valueOf(thisyear.substring(thisyear.length()-4,thisyear.length())) - 1;
            lastPeriod = String.valueOf('FY' + lastPeriodYear);
        }else{
            lastPeriod = getLastPeriodYear();
        }
        return lastPeriod;
    }
}