public with sharing class SetProvinceTargetBatch implements Database.Batchable<sObject>{
    String query;
    private String target_category;  // 省目标
    // 比重
    private Map<String, List<Double>> proportion;
    private Map<String, Opportunity> oppMap;
    //  现在年度
    private Integer currentYear;
    //  当前年度
    private Integer iYear;
    // 是否是过去年度
    public Boolean isPast { get; private set; }
    private RecordType rt;           // 目标的数据类型
    // 当前期
    public String currentPeriod { get; private set; }
   /**
     * 构造器,初始化
     */
    public SetProvinceTargetBatch(){
    }

    /**
     * 开始方法
     */
    public Database.QueryLocator start(Database.BatchableContext BC) {
        // 查询中间表,获取当前 年 的信息  key__c 剪切, 第二数据是数字字段名
        query = 'select Id,key__c,Target_Source__c,SAP_Province__c,iYear__c,Owner_System__c,Department__c,Amount__c from Provincial_Goal_Setting_Input__c where Is_Processing__c = true';
        return Database.getQueryLocator(query);
    }

    /**
     * 执行方法,添加保存
     */

    public void execute(Database.BatchableContext BC, List<Provincial_Goal_Setting_Input__c> Provincial_Goal_Setting_Inputs) { 
        init(Provincial_Goal_Setting_Inputs);
        List<Opportunity> saveList = new List<Opportunity>();
        List<Opportunity> deleteList = new List<Opportunity>();
        for (Provincial_Goal_Setting_Input__c Provincial_Goal_Setting_Input : Provincial_Goal_Setting_Inputs){
            string key = Provincial_Goal_Setting_Input.key__c;
            list<string> sp_ac_iy = key.split('_');
            if(sp_ac_iy.size() < 2){
                return;
            }
            Provincial_Goal_Setting_Input.Is_Processing__c = false;
            string SAP_Province = sp_ac_iy[0];
            string amountC = sp_ac_iy[1];
            for (Integer i = 0; i < 12; i++) {
                Integer y = Integer.valueOf(Provincial_Goal_Setting_Input.iYear__c);
                Integer m = 4 + i;
                if (m > 12) {
                    y += 1;
                    m -= 12;
                }
                String syear = String.valueOf(y);
                String smonth = String.valueOf(m);
                if (m < 10) {
                    smonth = '0' + smonth;
                }
                String sTargetDay = syear + '-' + smonth + '-01';
                Date targetDay = Date.valueOf(sTargetDay);
                String tem_key = key + '_' + sTargetDay;
                // 按金额分类顺序处理
                    // 每月数据赋值
                Opportunity opp = new Opportunity();
                if (oppMap.containskey(tem_key)) {
                    opp = oppMap.get(tem_key);
                    if (Provincial_Goal_Setting_Input.Amount__c == null || Provincial_Goal_Setting_Input.Amount__c == 0) {
                        deleteList.add(opp);
                        continue;
                    }
                    //Update 20160531 Start/
                    opp.OwnerId = Provincial_Goal_Setting_Input.Owner_System__c;
                    opp.Owner_System__c = Provincial_Goal_Setting_Input.Owner_System__c;
                    //Update 20160531 End/
                    if(proportion.get(amountC)!=null){
                        opp.Proportion__c = proportion.get(amountC)[i];
                    }
                    opp.Amount = Provincial_Goal_Setting_Input.Amount__c;
                } else {
                    if (Provincial_Goal_Setting_Input.Amount__c == null || Provincial_Goal_Setting_Input.Amount__c == 0) {
                        continue;
                    }
                    opp.Name = Provincial_Goal_Setting_Input.SAP_Province__c + ' 省目标';
                    opp.StageName = '目標';
                    //Update 20160531 Start/
                    opp.OwnerId = Provincial_Goal_Setting_Input.Owner_System__c;
                    //トリガをスルーのため、ここでやります
                    opp.Owner_System__c = Provincial_Goal_Setting_Input.Owner_System__c;
                    //Update 20160531 End/
                    opp.Opportunity_Category__c = amountC;
                    if(proportion.get(amountC)!=null){
                        opp.Proportion__c = proportion.get(amountC)[i];
                    }
                    opp.CloseDate = targetDay;
                    opp.Amount = Provincial_Goal_Setting_Input.Amount__c;
                    opp.Target_category__c = target_category;
                    opp.SAP_Province__c = Provincial_Goal_Setting_Input.SAP_Province__c;
                    opp.RecordTypeId = rt.Id;
                    opp.Target_Source__c = 'SetProvinceTarget';
                    //20210225 ljh WLIG-BV8CHF update  财年 start
                    //opp.OCM_Target_period__c = currentPeriod;
                    opp.OCM_Target_period__c = String.valueOf(integer.valueOf(Provincial_Goal_Setting_Input.iYear__c) - 1867 + 'P');
                   //20210225 ljh WLIG-BV8CHF update  财年 end
                }
                // 加入保存列表
                saveList.add(opp);
               
            }
        }
        StaticParameter.EscapeOpportunityBefUpdTrigger = true;
        StaticParameter.EscapeOpportunityHpDeptUpdTrigger = true;
        StaticParameter.EscapeNFM007Trigger = true;

        // 更新数据库
        if (saveList.size() > 0) upsert saveList;
        if (deleteList.size() > 0) delete deleteList;

        upsert Provincial_Goal_Setting_Inputs;
    }

    /**
     * 完成方法
     */
    public void finish(Database.BatchableContext BC) {
      
    }
    private void init(List<Provincial_Goal_Setting_Input__c> Provincial_Goal_Setting_Inputs){
         // 所有本年度属于省目标的目标
         if (target_category == null) {
            target_category = '省目标';
        }
        // 每月比重
        if (proportion == null) {
            proportion = new Map<String, List<Double>>();
            String strObjectiveProportionGI = System.Label.ObjectiveProportionGI;
            List<String> objectiveProportionGI = strObjectiveProportionGI.split(',');
            List<Double> doubleGI = new List<Double>();
            for (String strGI : objectiveProportionGI) {
                doubleGI.add(Double.valueOf(strGI));
            }
            proportion.put('GI', doubleGI);

            String strObjectiveProportionET = System.Label.ObjectiveProportionET;
            List<String> objectiveProportionET = strObjectiveProportionET.split(',');
            List<Double> doubleET = new List<Double>();
            for (String strET : objectiveProportionET) {
                doubleET.add(Double.valueOf(strET));
            }
            proportion.put('ET', doubleET);

            String strObjectiveProportionBF = System.Label.ObjectiveProportionBF;
            List<String> objectiveProportionBF = strObjectiveProportionBF.split(',');
            List<Double> doubleBF = new List<Double>();
            for (String strBF : objectiveProportionBF) {
                doubleBF.add(Double.valueOf(strBF));
            }
            proportion.put('BF', doubleBF);

            String strObjectiveProportionGS = System.Label.ObjectiveProportionGS;
            List<String> objectiveProportionGS = strObjectiveProportionGS.split(',');
            List<Double> doubleGS = new List<Double>();
            for (String strGS : objectiveProportionGS) {
                doubleGS.add(Double.valueOf(strGS));
            }
            proportion.put('GS', doubleGS);

            String strObjectiveProportionURO = System.Label.ObjectiveProportionURO;
            List<String> objectiveProportionURO = strObjectiveProportionURO.split(',');
            List<Double> doubleURO = new List<Double>();
            for (String strURO : objectiveProportionURO) {
                doubleURO.add(Double.valueOf(strURO));
            }
            proportion.put('URO', doubleURO);

            String strObjectiveProportionGYN = System.Label.ObjectiveProportionGYN;
            List<String> objectiveProportionGYN = strObjectiveProportionGYN.split(',');
            List<Double> doubleGYN = new List<Double>();
            for (String strGYN : objectiveProportionGYN) {
                doubleGYN.add(Double.valueOf(strGYN));
            }
            proportion.put('GYN', doubleGYN);

            String strObjectiveProportionENT = System.Label.ObjectiveProportionENT;
            List<String> objectiveProportionENT = strObjectiveProportionENT.split(',');
            List<Double> doubleENT = new List<Double>();
            for (String strENT : objectiveProportionENT) {
                doubleENT.add(Double.valueOf(strENT));
            }
            proportion.put('ENT', doubleENT);

            String strObjectiveProportionOTH = System.Label.ObjectiveProportionOTH;
            List<String> objectiveProportionOTH = strObjectiveProportionOTH.split(',');
            List<Double> doubleOTH = new List<Double>();
            for (String strOTH : objectiveProportionOTH) {
                doubleOTH.add(Double.valueOf(strOTH));
            }
            proportion.put('OTH', doubleOTH);

            //DB202305277681 fy 20230517 start

            // String strObjectiveProportionENG = System.Label.ObjectiveProportionENG;
            // List<String> objectiveProportionENG = strObjectiveProportionENG.split(',');
            // List<Double> doubleENG = new List<Double>();
            // for (String strENG : objectiveProportionENG) {
            //     doubleENG.add(Double.valueOf(strENG));
            // }
            // proportion.put('ENG', doubleENG);
            // proportion.put('_ENG', doubleENG);
            String strObjectiveProportionENG1 = System.Label.ObjectiveProportionENG;
            List<String> objectiveProportionENG1 = strObjectiveProportionENG1.split(',');
            List<Double> doubleENG1 = new List<Double>();
            for (String strENG1 : objectiveProportionENG1) {
                doubleENG1.add(Double.valueOf(strENG1));
            }
            proportion.put('ENG1', doubleENG1);
            proportion.put('_ENG1', doubleENG1);

            String strObjectiveProportionENG2 = System.Label.ObjectiveProportionENG;
            List<String> objectiveProportionENG2 = strObjectiveProportionENG2.split(',');
            List<Double> doubleENG2 = new List<Double>();
            for (String strENG2 : objectiveProportionENG2) {
                doubleENG2.add(Double.valueOf(strENG2));
            }
            proportion.put('ENG2', doubleENG2);
            proportion.put('_ENG2', doubleENG2);
            
            //DB202305277681 fy 20230517 end
        }
        //初始化既存目标数据
        oppMap = new Map<String, Opportunity>();
        // 目标的数据类型
        if (rt == null) {
            rt = [select Id from RecordType where SobjectType = 'Opportunity' and IsActive = true and DeveloperName = 'Target'];
        }
        // 现在时间
        Date dateNow = Date.today();
        Integer year = dateNow.year();
        Integer month = dateNow.month();
        if (month < 3) {
            year -= 1;
        }
        // 初始化
        currentYear = year;
        iYear = year;
        isPast = false;
        if (month == 3) isPast = true;
        
        //WLIG-BZVDB4 20210414  ljh update start
        //currentPeriod = String.valueOf(iYear - 1867 + 'P');
        list<string> currentPeriods = new list<string>();
        currentPeriod = String.valueOf(iYear - 1867 + 'P');
        currentPeriods.add(currentPeriod);
        currentPeriod = String.valueOf(iYear + 1 - 1867 + 'P');
        currentPeriods.add(currentPeriod);
        currentPeriod = String.valueOf(iYear - 1 - 1867 + 'P');
        currentPeriods.add(currentPeriod);
        // 获取 存储用户 用于搜索所对应询价
        list<String> OwnerSP = new list<String>();
        for (Provincial_Goal_Setting_Input__c Provincial_Goal_Setting_Input : Provincial_Goal_Setting_Inputs) {
            string key = Provincial_Goal_Setting_Input.key__c;
            list<string> sp_ac_iy = key.split('_');
            if (sp_ac_iy.size() < 2) {
                return;
            }
            Provincial_Goal_Setting_Input.Is_Processing__c = false;
            string SAP_Province = sp_ac_iy[0];
            OwnerSP.add(SAP_Province);
        }     
         //获取既存Opportunity
         Opportunity[] opportunitys = [select
                        Id, OwnerId, Opportunity_Category__c, Proportion__c, CloseDate,
                        Amount, Objective__c, Target_category__c,
                        SAP_Province__c, RecordTypeId, OCM_Target_period__c, Owner_System__c,Owner_System__r.Name
                 from Opportunity
                where Target_category__c = :target_category
                  and RecordTypeId = :rt.Id
                  and Target_Source__c = 'SetProvinceTarget'
                  and OCM_Target_period__c = :currentPeriods
                  and SAP_Province__c in :OwnerSP];
        if(opportunitys.size() <= 0)
            return;
        for (Opportunity opp : opportunitys) {
            if (opp.SAP_Province__c != null && opp.CloseDate !=null){
                //数据检索key
                String key = opp.SAP_Province__c + '_' + opp.Opportunity_Category__c+'_'+String.valueOf(opp.CloseDate);
                oppMap.put(key, opp);
            }
        }
        system.debug('oppMap++++'+oppMap);
    }
}