public with sharing class SetProductTargetController {
    // 当前期
    public String currentPeriod { get; private set; }
    public String currentPeriodOld;//20210225 WLIG-BV8CHF ljh add 财年
    // 上年度按钮制御
    public boolean previousRendered { get; private set; }
    // 下年度按钮制御
    public boolean nextRendered { get; private set; }
    // 数据集
    public List<DataBean> dataBeans { get; set; }
    // 金额分类
    public List<String> opportunity_category { get; private set; }
    // 是否是过去年度
    public Boolean isPast { get; private set; }
    // 年度変化時セーブかどうか
    public Boolean saveFlg { get; set; }
    // 本部の選択値
    public String salesDpt { get; set; }
    // 目标区分
    public String target_category { get; set; }
    // 製品プルダウン用
    public Opportunity opp { get; set; }
    public Integer titleSize { get; set; } 
        
    public SetProductTargetController() {
           //Apexpages.currentPage().getHeaders().put('X-UA-Compatible', 'IE=8');
    }

    
    
    // 本部プルダウン
    public static List<SelectOption> salesDptOpts { get; private set; }
    static {
        salesDptOpts = new List<SelectOption>();
        salesDptOpts.add(new SelectOption('0.无','--无--'));
        salesDptOpts.add(new SelectOption('1.华北','1.华北'));
        salesDptOpts.add(new SelectOption('2.东北','2.东北'));
        salesDptOpts.add(new SelectOption('3.西北','3.西北'));
        salesDptOpts.add(new SelectOption('4.西南','4.西南'));
        salesDptOpts.add(new SelectOption('5.华东','5.华东'));
        salesDptOpts.add(new SelectOption('6.华南','6.华南'));
        //CHAN-BDQBLX  20210204 ljh update start
        /*salesDptOpts.add(new SelectOption('7.能量-1.华北','7.能量-1.华北'));
        salesDptOpts.add(new SelectOption('7.能量-2.东北','7.能量-2.东北'));
        salesDptOpts.add(new SelectOption('7.能量-3.西北','7.能量-3.西北'));
        salesDptOpts.add(new SelectOption('7.能量-4.西南','7.能量-4.西南'));
        salesDptOpts.add(new SelectOption('7.能量-5.华东','7.能量-5.华东'));
        salesDptOpts.add(new SelectOption('7.能量-6.华南','7.能量-6.华南'));*/
        //CHAN-BDQBLX  20210204 ljh update end
    }
    // 重点目标分类
    public static List<SelectOption> targetOpts { get; private set; }
    static {
        targetOpts = new List<SelectOption>();
        targetOpts.add(new SelectOption('重点产品目标(数量)','重点产品目标(数量)'));
        targetOpts.add(new SelectOption('重点产品目标(金额)','重点产品目标(金额)'));
    }
    
    //  现在年度
    private Integer currentYear;
    //  当前年度
    private Integer iYear;

    public User loginUser { get; set; }          // 登陆用户
    private RecordType rt;           // 目标的数据类型
    private Map<String, List<Double>> proportion;    // 比重
    
    private List<String> provinces;
    private Map<String,List<String>> salesDptMap;  //本部-省对应关系
    private Map<String,String> provinceMap;        //省-本部对应关系

    private boolean isEng;
    
    //更新用条件
    //private String old_target_category;
    //private String old_important_Key_product_category;
    
    // 既存目标数据
    private Map<String, Opportunity> oppsMap;
    private Map<String, AggregateResult> oliMap;
    //2020/07/08 中间表寄存数据 by ld
    private Map<String,Key_Product_Goals__c> Key_Product_GoalsMap;
    public Key_Product_Goals__c[] Existed_Key_Product_Goals;
    // 金额分类 xiongyl
   // private static String[] amountCategory = new String[] {'GI','ET','BF','GS','URO','GYN','ENT','OTH'};
    public static List<String> amountCategory { get; private set; }
    public static List<ImportantProductCategory__c> pcList { get; private set; }
    public static Map<String, boolean> isCntMap = new Map<String, boolean>();
    public static Map<String,String> NkeyMap= new Map<String,String>();//20210204 CHAN-BDQBLX  ljh add
    static {
        amountCategory = new List<String>();
        pcList = [select depName__c,importantProductGoaIName__c,commodityCode__c,commodityName__c,if_Quantity__c,sort__c from ImportantProductCategory__c order by sort__c];
        for (ImportantProductCategory__c pc : pcList) {
            isCntMap.put(pc.importantProductGoaIName__c + '_' + pc.depName__c, pc.if_Quantity__c);
            if (pc.depName__c != null) {
                amountCategory.add(pc.commodityName__c + '(' + pc.depName__c + ')' + (pc.if_Quantity__c ? '' : '金额'));
                NkeyMap.put(pc.commodityName__c + '(' + pc.depName__c + ')' + (pc.if_Quantity__c ? '' : '金额'),pc.importantProductGoaIName__c + '_' + pc.depName__c);//CHAN-BDQBLX  20210204 ljh add
            }else {
                amountCategory.add(pc.commodityName__c + (pc.if_Quantity__c ? '' : '金额'));
                NkeyMap.put(pc.commodityName__c + (pc.if_Quantity__c ? '' : '金额'),pc.importantProductGoaIName__c + '_' + pc.depName__c);//CHAN-BDQBLX  20210204 ljh add
            }
        }
    }
    
    // 重点製品API名マップ
    public static Map<String, String> impProductApiMap = new Map<String, String> {
        '重点产品01' => 'Important_product1__c',
        '重点产品02' => 'Important_product2__c',
        '重点产品03' => 'Important_product3__c',
        '重点产品04' => 'Important_product4__c',
        '重点产品05' => 'Important_product5__c',
        '重点产品06' => 'Important_product6__c',
        '重点产品07' => 'Important_product7__c',
        '重点产品08' => 'Important_product8__c',
        '重点产品09' => 'Important_product9__c',
        '重点产品10' => 'Important_product10__c',
        '重点产品11' => 'Important_product11__c',
        '重点产品12' => 'Important_product12__c',
        '重点产品13' => 'Important_product13__c',
        '重点产品14' => 'Important_product14__c',
        '重点产品15' => 'Important_product15__c',
        '重点产品16' => 'Important_product16__c',
        '重点产品17' => 'Important_product17__c',
        '重点产品18' => 'Important_product18__c',
        '重点产品19' => 'Important_product19__c',
        '重点产品20' => 'Important_product20__c',
        '重点产品21' => 'Important_product21__c',
        '重点产品22' => 'Important_product22__c',
        '重点产品23' => 'Important_product23__c',
        '重点产品24' => 'Important_product24__c',
        '重点产品25' => 'Important_product25__c',
        '重点产品26' => 'Important_product26__c',
        '重点产品27' => 'Important_product27__c',
        '重点产品28' => 'Important_product28__c',
        '重点产品29' => 'Important_product29__c',
        '重点产品30' => 'Important_product30__c',
        '重点产品31' => 'Important_product31__c'
    };
    public static List<SelectOption> impProductOptions { get; private set; }
    static {
        impProductOptions = new List<SelectOption>();
        impProductOptions.add(new SelectOption('重点产品01', Product2.Important_product1__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品02', Product2.Important_product2__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品03', Product2.Important_product3__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品04', Product2.Important_product4__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品05', Product2.Important_product5__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品06', Product2.Important_product6__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品07', Product2.Important_product7__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品08', Product2.Important_product8__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品09', Product2.Important_product9__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品10', Product2.Important_product10__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品11', Product2.Important_product11__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品12', Product2.Important_product12__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品13', Product2.Important_product13__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品14', Product2.Important_product14__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品15', Product2.Important_product15__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品16', Product2.Important_product16__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品17', Product2.Important_product17__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品18', Product2.Important_product18__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品19', Product2.Important_product19__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品20', Product2.Important_product20__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品21', Product2.Important_product21__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品22', Product2.Important_product22__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品23', Product2.Important_product23__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品24', Product2.Important_product24__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品25', Product2.Important_product25__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品26', Product2.Important_product26__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品27', Product2.Important_product27__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品28', Product2.Important_product28__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品29', Product2.Important_product29__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品30', Product2.Important_product30__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品31', Product2.Important_product31__c.getDescribe().getlabel()));
    }
    //CHAN-BDQBLX  20210204 ljh start
    private List<Key_Product_Goals__c> upsertKPGList;
    private Map<String, Key_Product_Goals__c> Key_Product_GoalsMap1;
    public string csvAsString {get; set;}
    public String[] csvFileLines {get; set;}
    private static List<String> titlepage = new List<String>{'销售本部', '省', '担当'};
    public Integer detailCountLimit{get;private set;}
    //CHAN-BDQBLX  20210204 ljh end
    // 画面初始化
    public Pagereference init() {
        // 现在时间
        Date dateNow = Date.today();
        Integer year = dateNow.year();
        Integer month = dateNow.month();
        //CHAN-BDQBLX  20210204 LJH start
        Key_Product_GoalsMap1 = new Map<String, Key_Product_Goals__c>();
        upsertKPGList = new List<Key_Product_Goals__c>();
        detailCountLimit = 10000;
        //CHAN-BDQBLX  20210204 LJH end
        if (month < 4) {
            year -= 1;
        }
        // 初始化
        opp = new Opportunity();
        // xiongyl 修改后初始化的时候取得的是22种产品对应的数据
        //opp.Important_Key_product_category__c = '重点产品01';
        
        currentYear = year;
        iYear = year;
        isPast = false;
        // 20200304 开放管理员权限 Start
        //if (month == 3) isPast = true;
        if (month == 3 && UserInfo.getProfileId() != System.Label.ProfileId_SystemAdmin) isPast = true;
        // 20200304 开放管理员权限 End
        //20210225 ljh WLIG-BV8CHF update  财年 start
        //currentPeriod = String.valueOf(iYear - 1867 + 'P');
        currentPeriodOld = String.valueOf(iYear - 1867 + 'P');
        Integer tempiYear = iYear+1;
        currentPeriod = String.valueOf('FY'+tempiYear);
        //20210225 ljh WLIG-BV8CHF update  财年 end
        previousRendered = true;
        nextRendered = true;
        saveFlg = false;
        target_category = '省重点产品目标';
        titleSize = pcList.size();
        
        //old_target_category = target_category;
        //old_important_Key_product_category = opp.Important_Key_product_category__c;
        
        // 金额分类
        opportunity_category = amountCategory;
        // 每月比重
        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);

            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);
        }
        // 当前用户信息
        if (loginUser == null) {
            loginUser = [Select Id, Salesdepartment__c, ProfileId From User where Id = :Userinfo.getUserId()];
        }
        
        getsalesDptMap();
        //salesDpt = '0.无';
        salesDpt = '1.华北';
        provinces = new List<String>();
        provinces = salesDptMap.get(salesDpt);

        isEng = false;
        
        // 目标的数据类型
        if (rt == null) {
            rt = [select Id from RecordType where SobjectType = 'Opportunity' and IsActive = true and DeveloperName = 'Target'];
        }
        // 数据赋值
        setBean(iYear);

        return null;
    }
    
    //SWAG-BB48QB 判断当前时间是否是4月15日之后 start
    private boolean checkCurrentDate(){
        boolean dateResult = true;
        Date today = Date.today();
        Date date415 = Date.newInstance(today.year(), 4, 
            Integer.valueOf(System.Label.SetPersonalTarget_buffer_day));

        if(iYear >= currentYear -1 && today <= date415 )
            dateResult = false;
        return dateResult;
    }
    //SWAG-BB48QB 判断当前时间是否是4月15日之后 end
    
    // 点击上年度
    public void previous() {
        if (saveFlg) {
            this.saveLogic();
        }
        
        iYear -= 1;
        //20210225 ljh WLIG-BV8CHF update  财年 start
        //currentPeriod = String.valueOf(iYear - 1867 + 'P');
        currentPeriodOld = String.valueOf(iYear - 1867 + 'P');
        Integer tempiYear = iYear+1;
        currentPeriod = String.valueOf('FY'+tempiYear);
        //20210225 ljh WLIG-BV8CHF update  财年 end
        // 是否是过去数据
        isPast = false;
         //SWAG-BB48QB 判断当前时间是否是4月15日之后 start
        if (iYear < currentYear && checkCurrentDate()) {
            isPast = true;
        }

        // else if (iYear == currentYear) {
        //    if (Date.today().month() == 3) {
        //        isPast = true;
        //    }
        //}
         //SWAG-BB48QB 判断当前时间是否是4月15日之后 end
        previousRendered = true;
        nextRendered = true;
        // 数据赋值
        setBean(iYear);
    }
    
    // 点击下年度
    public void next() {
        if (saveFlg) {
            this.saveLogic();
        }
        
        iYear += 1;
        //20210225 ljh WLIG-BV8CHF update  财年 start
        //currentPeriod = String.valueOf(iYear - 1867 + 'P');
        currentPeriodOld = String.valueOf(iYear - 1867 + 'P');
        Integer tempiYear = iYear+1;
        currentPeriod = String.valueOf('FY'+tempiYear);
        //20210225 ljh WLIG-BV8CHF update  财年 end
        // 是否是过去数据
        isPast = false;
         //SWAG-BB48QB 判断当前时间是否是4月15日之后 start
        if (iYear < currentYear && checkCurrentDate()) {
            isPast = true;
        }  
        //else if (iYear == currentYear) {
        //    if (Date.today().month() == 3) {
        //        isPast = true;
        //    }
        //}
         //SWAG-BB48QB 判断当前时间是否是4月15日之后 end
        previousRendered = true;
        nextRendered = true;
        // 只显示到现在时间的下一年数据
        if (iYear > currentYear) {
            nextRendered = false;
        }
        // 数据赋值
        setBean(iYear);
    }
    
    // 本部プルダウン変更時の処理
    public void searchByDpt() {
        if (saveFlg) {
            this.saveLogic();
        }
        //CHAN-BDQBLX  20210220 ljh update start
        /*Map<String, String> engMap = new Map<String, String>();
        engMap.put('7.能量-1.华北','7.能量-1.华北');
        engMap.put('7.能量-2.东北','7.能量-2.东北');
        engMap.put('7.能量-3.西北','7.能量-3.西北');
        engMap.put('7.能量-4.西南','7.能量-4.西南');
        engMap.put('7.能量-5.华东','7.能量-5.华东');
        engMap.put('7.能量-6.华南','7.能量-6.华南');
        if (engMap.containsKey(salesDpt)) {
            isEng = true;
        } else {
            isEng = false;
        }*/
        //CHAN-BDQBLX  20210220 ljh update end
        provinces = new List<String>();
        provinces = salesDptMap.get(salesDpt);
        opp.SAP_Province__c = null;
        //CHAN-BDQBLX  20210207 ljh update start
        //if (salesDpt != '0.无') {
            // 数据赋值
            setBean(iYear);
        //}
        //CHAN-BDQBLX  20210207 ljh update end
    }
    
    // 省プルダウン変更時の処理
    public void searchByProvince() {
        if (saveFlg) {
            this.saveLogic();
        }

        provinces = new List<String>();
        salesDpt = '0.无';
        if (opp.SAP_Province__c == null) {
            provinces = salesDptMap.get(salesDpt);
        } else {
            provinces.add(opp.SAP_Province__c);
        }

        isEng = false;

        // 数据赋值
        setBean(iYear);
    }
    
    // 重点目標分類変更時の処理
    public void searchByCategory() {
        if (saveFlg) {
            this.saveLogic();
        }
        //old_target_category = target_category;
        // 数据赋值
        setBean(iYear);
    }
    
    // 重点製品変更時の処理
    public void searchByImpKey() {
        if (saveFlg) {
            this.saveLogic();
        }
        //old_important_Key_product_category = opp.Important_Key_product_category__c;
        // 数据赋值
        setBean(iYear);
    }
    //CHAN-BDQBLX  20210204 ljh start 导入出方法 start
    //导出方法
    public Pagereference exportBycsv() {
        setBean(iYear);
        return page.SetProductTargetcvs;                 
    }
    //导入方法
    public PageReference importCSVFile() {
        try {
            String csvData = ApexPages.currentPage().getParameters().get('csvData');
            // 将内容转换成为中文
            if(!Test.isRunningTest()){
                //csvAsString = bitToString(csvFileBody, 'gb2312');
                csvAsString = csvData;
            }            
            // 拆成每一行
            csvFileLines = csvAsString.split('\n');
            Boolean ValFlag = false;
            String exportByVal = '';
            ApexPages.Message successMsg = new ApexPages.Message(ApexPages.severity.INFO, '');
            // 需要根据情况来解析,查看表头是否一致
            if(opportunity_category !=null && opportunity_category.size()>0){
                titlepage.addAll(opportunity_category);
            }
            String target_Source1 = 'SalesTarget';
            String salesDpt1;
            if (csvFileLines.size() > 0) {
                string[] titlecsv = csvFileLines[0].trim().split(',');
                System.debug('==titlepage=='+titlepage);
                System.debug('==titlecsv=='+titlecsv);
                if(titlecsv[0].split(':').size()>=2){
                    if (titlecsv[0].split(':')[1].contains('能量')) {
                        target_Source1 = 'EngTarget';
                    }
                    /**
                    salesDpt = titlecsv[0].split(':')[1];
                    if(titlecsv[0].split(':').size()==3){
                        opp.SAP_Province__c = titlecsv[0].split(':')[2];
                    }else{
                        opp.SAP_Province__c = null;
                    }
                    **/
                    titlecsv[0] = titlecsv[0].split(':')[0];                    
                }                
                for (integer j = 0; j < titlecsv.size(); j++) {
                    if (!titlepage.contains(titlecsv[j])) {
                        system.debug('表头不一致得列===' + titlecsv[j]);
                        ValFlag = true;
                        exportByVal = '表头不一致，请严格按照导出模板填写';
                        break;
                    }
                }
            }
            if (ValFlag) {
                successMsg = new ApexPages.Message(ApexPages.severity.INFO, exportByVal);
                ApexPages.addMessage(successMsg);
            } else {
                List<String> UserInfoList = new List<String>();
                Map<String, List<String>> szMap = new Map<String, List<String>>();
                Set<String> sfs = new Set<String>();//省份
                for (Integer i = 1; i < csvFileLines.size(); i++) {
                    string[] csvRecordData = csvFileLines[i].split(',');
                    if (csvRecordData.size() > 0) {
                        String bu = csvRecordData[0].replace(' ', '');
                        String sf = csvRecordData[1].replace(' ', '');
                        String dandang = csvRecordData[2].replace(' ', '');
                        if(String.isNotBlank(dandang)){
                            UserInfoList.add(dandang);//根据 担当查user     
                        }
                        szMap.put(bu+'_'+ sf + '_'+dandang, csvRecordData);
                        sfs.add(sf);//把省份放进去 
                    }
                }
                if (null != sfs && sfs.size() > 0) {
                    this.getKey_Product_Goals(sfs);//根据省份年份，获取当前系统中已经存在得数据 放到map中 
                }
                List<User> userList  = new List<User>();
                if (null != UserInfoList && UserInfoList.size() > 0) {
                    userList = this.getUserList(UserInfoList);//返回用户得一些信息
                }
                Map<String, User> userMap = new Map<String, User>();
                for (User userl : userList) {
                    userMap.put(userl.Alias, userl);
                }                
                upsertKPGList = new List<Key_Product_Goals__c>();//初始化，解决重复导入数据 id重复得问题
                for (String key : szMap.keySet()) {
                    //取用户的Id
                    String userid = '';
                    String key_shengfen=key.split('_')[1];//省份
                    String key_dandang= '';
                    if(key.split('_').size()>=3){
                         key_dandang=key.split('_')[2];//把担当取出来
                    }
                    if (userMap.containskey(key_dandang)) {
                        userid = userMap.get(key_dandang).Id;
                    } else {
                        System.debug('==key==='+key);
                        //用户不存在要提醒
                        continue;
                    }
                    System.debug('==userid:'+userid);
                    //String key = dataBean.Opportunity.SAP_Province__c + '_' + target_category + '_' +
                                // pc.importantProductGoaIName__c + '_' + pc.depName__c + '_' + target_Source;
                   //--------
                    List<String> csvRecordData = szMap.get(key);
                    Key_Product_Goals__c upsertKPG = new Key_Product_Goals__c();
                    Integer tI = amountCategory.size()+3;//数字3取决于导入的cvs重点产品前的个数
                    System.debug('amountCategory.size():'+amountCategory.size());
                    for(Integer i = 3;i<tI;i++){
                        Integer  Num_Of_OPD;
                        if(String.isNotBlank(csvRecordData[i])){
                            if(i==(tI-1)){
                                Num_Of_OPD = Integer.valueOf(csvRecordData[i].trim());
                            }else{
                                Num_Of_OPD = Integer.valueOf(csvRecordData[i]);
                            }
                        }

                        String nkey = csvRecordData[1] + '_' + target_category + '_' +NkeyMap.get(amountCategory[i-3])+'_'+target_Source1;
                        DataSplicing(Num_Of_OPD,nkey,target_Source1,csvRecordData,Key_Product_GoalsMap1,userid);
                    }
                }
                if(null!=upsertKPGList && upsertKPGList.size()>0){
                    upsert upsertKPGList;
                }
                /**
                provinces = new List<String>();
                if (salesDpt != null && opp.SAP_Province__c != null && salesDpt == '0.无' && opp.SAP_Province__c != '0.无') {
                    provinces.add(opp.SAP_Province__c);
                } else {
                    provinces = salesDptMap.get(salesDpt);
                }
                **/
                // 数据赋值
                setBean(iYear);
                successMsg = new ApexPages.Message(ApexPages.severity.INFO, '导入成功');
                ApexPages.addMessage(successMsg);
            }
        } catch (Exception e) {
             ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.severity.ERROR, e.getMessage());
             ApexPages.addMessage(errorMessage);
        }
        return null;
    }
    // 最终得数据处理，
    private void DataSplicing(Integer NumOfOPD, String key,String target_Source,List<String> csvRecordData, Map<String, Key_Product_Goals__c> nmpMap,String userId) {//去进行最终数据得插入，更新或删除操作
        Key_Product_Goals__c upsertKPG = new Key_Product_Goals__c();
        Key_Product_Goals__c Key_Product_Goals = Key_Product_GoalsMap.get(key);  
        if (nmpMap.containskey(key)) {
            upsertKPG = nmpMap.get(key);
            if (NumOfOPD > 0) {
                if(NumOfOPD != upsertKPG.Num_Of_OPD__c){
                    upsertKPG.Num_Of_OPD__c = NumOfOPD;
                    upsertKPG.Owner_System__c = userId;
                    upsertKPG.Is_Processing__c = true;
                    upsertKPGList.add(upsertKPG);
                    //更新
                }
                
            } else {
                //不用删除了，允许 数据是空的存在
                upsertKPG.Num_Of_OPD__c = null;
                upsertKPG.Is_Processing__c = true;
                upsertKPG.Owner_System__c = userId;
                upsertKPGList.add(upsertKPG);
            }
        } else {
            if (NumOfOPD > 0) {
                upsertKPG.Num_Of_OPD__c = NumOfOPD;
                upsertKPG.key__c = key;
                upsertKPG.Owner_System__c = userId;
                upsertKPG.SAP_Province__c = csvRecordData[1];
                upsertKPG.Department__c = csvRecordData[0];
                upsertKPG.iYear__c = iYear;
                upsertKPG.Is_Processing__c = true;
                upsertKPG.Target_Source__c = target_Source;
                upsertKPGList.add(upsertKPG);
            } else {
                //允许 数据是空的存在
                upsertKPG.Num_Of_OPD__c = null;
                upsertKPG.key__c = key;
                upsertKPG.Owner_System__c = userId;
                upsertKPG.SAP_Province__c = csvRecordData[1];
                upsertKPG.Department__c = csvRecordData[0];
                upsertKPG.iYear__c = iYear;
                upsertKPG.Is_Processing__c = true;
                upsertKPG.Target_Source__c = target_Source;
                upsertKPGList.add(upsertKPG);
            }
        }
    }
    private void getKey_Product_Goals(Set<String> sfs) {//根据省份年份，获取当前系统中已经存在得数据
        Key_Product_GoalsMap1 = new Map<String, Key_Product_Goals__c>();

        list<Key_Product_Goals__c> Existed_Key_Product_Goals = [select key__c, Num_Of_OPD__c, Owner_System__c,
                                      Is_Processing__c, iYear__c from Key_Product_Goals__c where iYear__c = : iYear and SAP_Province__c in :sfs];
        for (Key_Product_Goals__c Key_Product_Goals : Existed_Key_Product_Goals ) {
            if (String.isBlank(Key_Product_Goals.key__c)) {
                continue;
            }
            Key_Product_GoalsMap1.put(Key_Product_Goals.key__c, Key_Product_Goals);
        }
    }
    private List<User> getUserList(List<String> UserInfoList) {
        String soql = 'select Id,Alias from User where IsActive = true'
                      + ' and (Alias IN :UserInfoList'+' OR Id IN :UserInfoList '
                      +') order by Salesdepartment__c, Province__c';
        System.debug('==soql==' + soql);
        return Database.query(soql);
    }
    //CHAN-BDQBLX  20210204 ljh start 导入出方法 end
    // 点击保存按钮
    public Pagereference saveBtn() {
        boolean rs = saveLogic();
        setBean(iYear);
        if (rs) {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, '保存成功'));
        }
        return null;
    }
    
    // 点击返回按钮
    public Pagereference backBtn() {
        // HOMEに戻る
        PageReference ref = new Pagereference('/home/home.jsp');
        ref.setRedirect(true);
        return ref;
    }

    // 2020/07/08 从中间表获取既有数据
    private boolean getKey_Product_Goalsmap() {
        Key_Product_GoalsMap = new Map<String,Key_Product_Goals__c>();
        System.debug('allen=iYear==>>'+iYear);
        Existed_Key_Product_Goals = [select id, key__c,Num_Of_OPD__c,Department__c,SAP_Province__c,Owner_System__c,iYear__c
                                                                FROM Key_Product_Goals__c where iYear__c = : iYear ];
        
        if (Existed_Key_Product_Goals.size() <= 0) {
            return false;
        }

        // 将所数据存入map中
        for ( Key_Product_Goals__c Key_Product_Goal : Existed_Key_Product_Goals ){
            if (String.isBlank(Key_Product_Goal.key__c)) {
                continue;
            }
            Key_Product_GoalsMap.put(Key_Product_Goal.key__c,Key_Product_Goal);
        }

        return true;
    }
    
    //获取本部-省对应关系
    private void getsalesDptMap() {
        salesDptMap = new Map<String,List<String>>();
        
        List<String> provinceList = new List<String>();
        provinceList.add('北京市');
        provinceList.add('天津市');
        provinceList.add('河南省');
        provinceList.add('河北省');
        provinceList.add('山西省');
        provinceList.add('内蒙古');
        provinceList.add('山东省');
        provinceList.add('陕西省');
        provinceList.add('青海省');
        provinceList.add('宁夏自治区');
        provinceList.add('甘肃省');
        provinceList.add('新疆自治区');
        provinceList.add('辽宁省');
        provinceList.add('黑龙江省');
        provinceList.add('吉林省');
        provinceList.add('上海市');
        provinceList.add('江苏省');
        provinceList.add('浙江省');
        provinceList.add('福建省');
        provinceList.add('安徽省');
        provinceList.add('江西省');
        provinceList.add('广东省');
        provinceList.add('广西自治区');
        provinceList.add('海南省');
        provinceList.add('四川省');
        provinceList.add('重庆市');
        provinceList.add('云南省');
        provinceList.add('贵州省');
        provinceList.add('西藏自治区');
        provinceList.add('湖北省');
        provinceList.add('湖南省');
        provinceList.add('深圳市');
        provinceList.add('大连市');
        provinceList.add('青岛市');
        salesDptMap.put('0.无',provinceList);
        
        provinceList = new List<String>();
        provinceList.add('北京市');
        provinceList.add('天津市');
        provinceList.add('河北省');
        provinceList.add('内蒙古');
        provinceList.add('山东省');
        provinceList.add('青岛市');
        salesDptMap.put('1.华北',provinceList);
        
        provinceList = new List<String>();
        provinceList.add('辽宁省');
        provinceList.add('黑龙江省');
        provinceList.add('吉林省');
        provinceList.add('大连市');
        salesDptMap.put('2.东北',provinceList);
        
        provinceList = new List<String>();
        provinceList.add('河南省');
        provinceList.add('山西省');
        provinceList.add('陕西省');
        provinceList.add('青海省');
        provinceList.add('宁夏自治区');
        provinceList.add('甘肃省');
        provinceList.add('新疆自治区');
        salesDptMap.put('3.西北',provinceList);
        
        provinceList = new List<String>();
        provinceList.add('上海市');
        provinceList.add('江苏省');
        provinceList.add('浙江省');
        provinceList.add('福建省');
        provinceList.add('安徽省');
        provinceList.add('江西省');
        salesDptMap.put('5.华东',provinceList);
        
        provinceList = new List<String>();
        provinceList.add('广东省');
        provinceList.add('广西自治区');
        provinceList.add('海南省');
        provinceList.add('湖北省');
        provinceList.add('湖南省');
        provinceList.add('深圳市');
        salesDptMap.put('6.华南',provinceList);
        
        provinceList = new List<String>();
        provinceList.add('四川省');
        provinceList.add('重庆市');
        provinceList.add('云南省');
        provinceList.add('贵州省');
        provinceList.add('西藏自治区');
        salesDptMap.put('4.西南',provinceList);
        //CHAN-BDQBLX  20210204 ljh update start
        /*provinceList = new List<String>();
        provinceList.add('北京市');
        provinceList.add('天津市');
        provinceList.add('河北省');
        provinceList.add('山东省');
        provinceList.add('河南省');
        salesDptMap.put('7.能量-1.华北',provinceList);

        provinceList = new List<String>();
        provinceList.add('黑龙江省');
        provinceList.add('吉林省');
        provinceList.add('辽宁省');
        provinceList.add('大连市');
        provinceList.add('内蒙古');
        salesDptMap.put('7.能量-2.东北',provinceList);

        provinceList = new List<String>();
        provinceList.add('山西省');
        provinceList.add('陕西省');
        provinceList.add('青海省');
        provinceList.add('宁夏自治区');
        provinceList.add('新疆自治区');
        provinceList.add('甘肃省');
        salesDptMap.put('7.能量-3.西北',provinceList);

        provinceList = new List<String>();
        provinceList.add('四川省');
        provinceList.add('重庆市');
        provinceList.add('云南省');
        provinceList.add('贵州省');
        provinceList.add('西藏自治区');
        salesDptMap.put('7.能量-4.西南',provinceList);

        provinceList = new List<String>();
        provinceList.add('上海市');
        provinceList.add('江苏省');
        provinceList.add('江西省');
        provinceList.add('安徽省');
        provinceList.add('浙江省');
        provinceList.add('福建省');
        salesDptMap.put('7.能量-5.华东',provinceList);

        provinceList = new List<String>();
        provinceList.add('广东省');
        provinceList.add('深圳市');
        provinceList.add('海南省');
        provinceList.add('广西自治区');
        provinceList.add('湖北省');
        provinceList.add('湖南省');
        salesDptMap.put('7.能量-6.华南',provinceList);*/
        //CHAN-BDQBLX  20210204 ljh update end
        provinceMap = new Map<string,string>();
        
        provinceMap.put('北京市','1.华北');
        provinceMap.put('天津市','1.华北');
        provinceMap.put('河北省','1.华北');
        provinceMap.put('内蒙古','1.华北');
        provinceMap.put('山东省','1.华北');
        provinceMap.put('青岛市','1.华北');
        
        provinceMap.put('辽宁省','2.东北');
        provinceMap.put('黑龙江省','2.东北');
        provinceMap.put('吉林省','2.东北');
        provinceMap.put('大连市','2.东北');
        
        provinceMap.put('河南省','3.西北');
        provinceMap.put('山西省','3.西北');
        provinceMap.put('陕西省','3.西北');
        provinceMap.put('青海省','3.西北');
        provinceMap.put('宁夏自治区','3.西北');
        provinceMap.put('甘肃省','3.西北');
        provinceMap.put('新疆自治区','3.西北');
        
        provinceMap.put('上海市','5.华东');
        provinceMap.put('江苏省','5.华东');
        provinceMap.put('浙江省','5.华东');
        provinceMap.put('福建省','5.华东');
        provinceMap.put('安徽省','5.华东');
        provinceMap.put('江西省','5.华东');
        
        provinceMap.put('广东省','6.华南');
        provinceMap.put('广西自治区','6.华南');
        provinceMap.put('海南省','6.华南');
        provinceMap.put('湖北省','6.华南');
        provinceMap.put('湖南省','6.华南');
        provinceMap.put('深圳市','6.华南');
        
        provinceMap.put('四川省','4.西南');
        provinceMap.put('重庆市','4.西南');
        provinceMap.put('云南省','4.西南');
        provinceMap.put('贵州省','4.西南');
        provinceMap.put('西藏自治区','4.西南');
    }
    
    // 数据赋值
    private void setBean(Integer year) {
        String target_Source = 'SalesTarget';
        if (isEng == true) {
            target_Source = 'EngTarget';
        }
        System.debug('allen===target_category==>'+target_category);
        System.debug('allen===rt.Id==>'+rt.Id);
        System.debug('allen===currentPeriodOld==>'+currentPeriodOld);
        System.debug('allen===provinces==>'+provinces);
        System.debug('allen===target_Source==>'+target_Source);


        // 取得当前年度目标数据
        Opportunity[] opportunitys = [select
                        Id, OwnerId, Proportion__c, Opportunity_Category__c, CloseDate,
                        Target_category__c, Important_Key_product_category__c,
                        SAP_Province__c, Owner_System__c,Owner_System__r.Name, Target_Source__c
                 from Opportunity
                where Target_category__c = :target_category
                  // xionyl去掉重点产品名称的查询条件
                 // and Important_Key_product_category__c = :opp.Important_Key_product_category__c
                  and RecordTypeId = :rt.Id
                  //20210225 ljh WLIG-BV8CHF update  财年 start
                  //and OCM_Target_period__c = :currentPeriod
                  and OCM_Target_period__c = :currentPeriodOld
                  //20210225 ljh WLIG-BV8CHF update  财年 end
                  and SAP_Province__c in :provinces
                  and Target_Source__c = :target_Source];
        // 当前年度没有数据时，显示信息
        if (opportunitys.size() <= 0 && isPast && iYear < currentYear) {
            ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.INFO, '没有上年度的数据。');
            ApexPages.addMessage(msg);
            previousRendered = false;
            iYear += 1;
            //20210225 ljh WLIG-BV8CHF update  财年 start
            //currentPeriod = String.valueOf(iYear - 1867 + 'P');
            currentPeriodOld = String.valueOf(iYear - 1867 + 'P');
            Integer tempiYear = iYear+1;
            currentPeriod = String.valueOf('FY'+tempiYear);
            //20210225 ljh WLIG-BV8CHF update  财年 end
            isPast = false;
            if (iYear < currentYear) {
                isPast = true;
            } else if (iYear == currentYear) {
                if (Date.today().month() == 3) {
                    isPast = true;
                }
            }
            // 今表示しているデータを再取得
            setBean(iYear);
            return;
        }
        oppsMap = new Map<String, Opportunity>();
        for (Opportunity opp : opportunitys) {
            if (opp.OwnerId != null && opp.CloseDate != null){
                String key = opp.SAP_Province__c + '_' + opp.Target_category__c + '_' + opp.Important_Key_product_category__c
                           + '_' + opp.Opportunity_Category__c + '_' + String.valueOf(opp.CloseDate);
                oppsMap.put(key, opp);
            }
        }

        // 2020/07/08 读取中间寄存表 by ld
        getKey_Product_Goalsmap();
        
        AggregateResult[] opportunityLineItems = [select OpportunityId,SUM(NumberOfObjective__c) sum_n,SUM(Objective__c) sum_o from OpportunityLineItem where OpportunityId in :opportunitys group by OpportunityId];
        oliMap = new Map<String, AggregateResult>();
        for (AggregateResult oli : opportunityLineItems) {
            oliMap.put((String) oli.get('OpportunityId'), oli);
        }
        
        List<String> UserId = new List<String>();//CHAN-BDQBLX 20210205 ljh add
        //建立数据集
        dataBeans = new List<DataBean>();
        for (String pro : provinces) {
            DataBean dataBean = new DataBean(provinceMap.get(pro), pro, oppsMap, iYear, target_category, oliMap, pcList);
            System.debug('allen===>pcList'+pcList.size());
            System.debug('allen===>dataBean'+dataBean);
            Integer i=0;
            // 2020/07/10 与既有中间表数据进行对比 by ld start
            for (Integer j = 0; j < pcList.size(); j++) {
                ImportantProductCategory__c pc = pcList[j];
                String key = dataBean.Opportunity.SAP_Province__c + '_' + target_category + '_' +
                                 pc.importantProductGoaIName__c + '_' + pc.depName__c + '_' + target_Source;
                // String key = dataBean.opportunity.SAP_Province__c + '_' + amountCategory[j];
                System.debug('allen===>pcList.importantProductGoaIName__c'+pc.importantProductGoaIName__c);
                System.debug('allen===>pcList.depName__c'+pc.depName__c);

                System.debug('allen===key==>'+key);
                System.debug('allen===Key_Product_GoalsMap==>'+Key_Product_GoalsMap);

                if (Key_Product_GoalsMap.containsKey(key)){
                    i++;
                    System.debug('allen===key==>1'+key);
                    System.debug('allen===Key_Product_GoalsMap==>2'+Key_Product_GoalsMap);
                    Key_Product_Goals__c Key_Product_Goal = Key_Product_GoalsMap.get(key);
                    System.debug('allen===Key_Product_Goal==>2'+Key_Product_Goal);

                    dataBean.opportunity.Owner_System__c = Key_Product_Goal.Owner_System__c;
                    dataBean.amount[j].Num_Of_OPD__c = Key_Product_Goal.Num_Of_OPD__c;
                    //CHAN-BDQBLX  20210204 ljh start 
                    UserId.add(Key_Product_Goal.Owner_System__c);
                    //CHAN-BDQBLX  20210204 ljh end
                }
            }
            // 2020/07/10 与既有中间表数据进行对比 by ld end
            System.debug('allen===>>>i'+i);
            System.debug('allen==放入=dataBeans==dataBean>1'+dataBean);

            dataBeans.add(dataBean);
        }
        //CHAN-BDQBLX  20210204 ljh start
        List<User> userList  = new List<User>();
        Map<String,String> userIdAMap  = new Map<String,String>();
        System.debug('allen===>UserId'+UserId);
        if (null != UserId && UserId.size() > 0) {
            userList = this.getUserList(UserId);//返回用户得一些信息
        }
        for(User u:userList){
            userIdAMap.put(u.Id,u.Alias);
        }
        System.debug('allen===>userIdAMap'+userIdAMap);
        System.debug('allen===>dataBeans'+dataBeans);
        
        for(dataBean db:dataBeans){
            //System.debug('==='+db);
            System.debug('allen===>db.opportunity.Owner_System__c'+db.opportunity.Owner_System__c);

            if(userIdAMap.containsKey(db.opportunity.Owner_System__c)){
                db.ownername = userIdAMap.get(db.opportunity.Owner_System__c);
            }
        }
        //CHAN-BDQBLX  20210204 ljh end
    }
    
    // 是否删除整行数据
    private boolean isDelete(DataBean db) {
        if (db.opportunity.Owner_System__c == null) {
            for (Integer i = 0; i < 12; i++) {
                Integer y = iYear;
                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 sTagetDay = syear + '-' + smonth + '-01';
                Date tagetDay = Date.valueOf(sTagetDay);
                // 按金额分类顺序处理
                for (Integer j = 0; j < pcList.size(); j++) {
                    ImportantProductCategory__c pc = pcList[j];
                    // 数据检索Key
                    String key = db.opportunity.SAP_Province__c + '_' + target_category + '_' + opp.Important_Key_product_category__c + '_' + pc.depName__c + '_' + sTagetDay;
                    if (oppsMap.containskey(key)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
    
    // 実際の保存ロジック
    /*private boolean saveLogic() {
        List<Opportunity> insertList = new List<Opportunity>();
        List<Opportunity> updateList = new List<Opportunity>();
        List<Opportunity> deleteList = new List<Opportunity>();

        List<Key_Product_Goals__c> InsertKey_Product_Goals = new list<Key_Product_Goals__c>();
        List<Key_Product_Goals__c> UpdateKey_Product_Goals = new list<Key_Product_Goals__c>();

        String target_Source = 'SalesTarget';
        if (isEng == true) {
            target_Source = 'EngTarget';
        }

        Savepoint sp = Database.setSavepoint();
        try {
            Map<String, Decimal> oppAmount = new Map<String, Decimal>();
            Map<String,String> saveAmountCategoryMap = new Map<String,String>();

            System.debug(dataBeans+'6666');
            
            for (Integer d = 0; d < dataBeans.size(); d++) {
                DataBean db = dataBeans[d];
                System.debug(db+'7777');
                // 寄存数据比例值是否变化
                Boolean proportionChanged = false;
                for (Integer i = 0; i < 12; i++) {
                    Integer y = iYear;
                    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';
                    
                    // 按金额分类顺序处理
                    for (ImportantProductCategory__c pc : pcList){
                        // 数据检索Key
                        String key = db.opportunity.SAP_Province__c + '_' + target_category + '_' + pc.importantProductGoaIName__c + '_' + pc.depName__c + '_' + sTargetDay;
                        
                        Opportunity opp = new Opportunity();
                        // 每月数据赋值                       
                        if (oppsMap.containskey(key)) {
                            opp = oppsMap.get(key);
                            String depName = (pc.depName__c == null || pc.depName__c == '') ? 'GI' : pc.depName__c;
                            if (opp.Proportion__c != proportion.get(depName)[i]) {
                                proportionChanged = true;
                                break;
                             }
                        }
                    }
                    if (proportionChanged) {
                        break;
                    }
                }
                if (db.isChanged == '0' && !proportionChanged) {
                    continue;
                }
                User u = new User();
                if (db.opportunity.Owner_System__c == null) {
                    if (isDelete(db) == false) {
                        continue;
                    }
                }
                // 一年分成12条数据
                for (Integer i = 0; i < 12; i++) {
                    Integer y = iYear;
                    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 sTagetDay = syear + '-' + smonth + '-01';
                    Date tagetDay = Date.valueOf(sTagetDay);
                    // 按金额分类顺序处理
                    for (Integer j = 0; j < pcList.size(); j++){
                        ImportantProductCategory__c pc = pcList[j];
                        // 数据检索Key
                        String key = db.opportunity.SAP_Province__c + '_' + target_category + '_' + pc.importantProductGoaIName__c + '_' + pc.depName__c + '_' + sTagetDay;
                        
                        Opportunity newopp = new Opportunity();
                        // 每月数据赋值                        
                        if (oppsMap.containskey(key)) {
                            newopp = oppsMap.get(key);
                            if (db.opportunity.Owner_System__c == null || db.amount[j].Num_Of_OPD__c == null || db.amount[j].Num_Of_OPD__c == 0) {
                                deleteList.add(newopp);
                                continue;
                            }
                            newopp.OwnerId = db.opportunity.Owner_System__c;
                            newopp.Owner_System__c = db.opportunity.Owner_System__c;
                            String depName = (pc.depName__c == null || pc.depName__c == '') ? 'GI' : pc.depName__c;
                            newopp.Proportion__c = proportion.get(depName)[i];
                            newopp.Num_Of_OPD__c = db.amount[j].Num_Of_OPD__c;
                            oppAmount.put(newopp.Id, db.amount[j].Num_Of_OPD__c);
                            updateList.add(newopp);

                            if (!saveAmountCategoryMap.containskey(pc.importantProductGoaIName__c + '_' + pc.depName__c)) {
                                saveAmountCategoryMap.put(pc.importantProductGoaIName__c + '_' + pc.depName__c, pc.importantProductGoaIName__c + '_' + pc.depName__c);
                            }
                        } else {
                            if (db.amount[j].Num_Of_OPD__c == null || db.amount[j].Num_Of_OPD__c == 0) {
                                continue;
                            }
                            newopp.Name = db.opportunity.SAP_Province__c + ' ' + pc.importantProductGoaIName__c;
                            
                            newopp.StageName = '目標';
                            newopp.OwnerId = db.opportunity.Owner_System__c;
                            // トリガをスルーのため、ここでやります
                            newopp.Owner_System__c = db.opportunity.Owner_System__c;
                            
                            newopp.Opportunity_Category__c = pc.depName__c;
                            String depName = (pc.depName__c == null || pc.depName__c == '') ? 'GI' : pc.depName__c;
                            newopp.Proportion__c = proportion.get(depName)[i];
                            newopp.CloseDate = tagetDay;
                            newopp.Num_Of_OPD__c = db.amount[j].Num_Of_OPD__c;
                            newopp.Target_category__c = target_category;
                            newopp.Important_Key_product_category__c = pc.importantProductGoaIName__c;
                            newopp.SAP_Province__c = db.opportunity.SAP_Province__c;
                            newopp.RecordTypeId = rt.Id;
                            newopp.OCM_Target_period__c = currentPeriod;
                            newopp.Target_Source__c = target_Source;
                            
                            insertList.add(newopp);
                            
                            if (!saveAmountCategoryMap.containskey(pc.importantProductGoaIName__c + '_' + pc.depName__c)) {
                                saveAmountCategoryMap.put(pc.importantProductGoaIName__c + '_' + pc.depName__c, pc.importantProductGoaIName__c + '_' + pc.depName__c);
                            }
                        }
                    }
                }
                // 数据库限制小于10000条
                if (insertList.size() + updateList.size() + deleteList.size() >= 4000) {
                    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, '操作数据量过大，截止至' + db.opportunity.SAP_Province__c + '的数据操作完成，之后的数据请再次输入并保存。'));
                    break;
                }
            }
            // トリガをスルー
            StaticParameter.EscapeOpportunityBefUpdTrigger = true;
            StaticParameter.EscapeOpportunityHpDeptUpdTrigger = true;
            StaticParameter.EscapeSyncOpportunityTrigger = true;
            StaticParameter.EscapeNFM001Trigger = true;
            StaticParameter.EscapeNFM001AgencyContractTrigger = true;
            StaticParameter.EscapeNFM007Trigger = true;
    
            // 更新数据库
            if (insertList.size() > 0) {
                insert insertList;
                
                Map<String,PricebookEntry> pricebookEntryMap = new Map<String,PricebookEntry>();
                // 製品を検索
                for (ImportantProductCategory__c pc : pcList){
                    String dep = pc.depName__c;
                    Map<String, String> impmap = getImpProductMap(dep);
                    String soql = 'select Id from PricebookEntry' + 
                                  ' where IsActive = true ' + 
                                  '   and Product2.' + impProductApiMap.get(pc.importantProductGoaIName__c) + ' = true';
                    if (dep != null && dep.length() > 0) {
                          soql += '   and Product2.' + impmap.get(pc.importantProductGoaIName__c) + ' = true';
                    }
                          soql += '   and CurrencyIsoCode = \'CNY\' limit 1';
                    System.debug(soql);
                    
                    List<PricebookEntry> pbes = Database.query(soql);
                    if (pbes.size() < 1) {
                        Database.rollback(sp);
                        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '在产品（价格表）里找不到' + pc.importantProductGoaIName__c + '-' + dep));
                        return false;
                    }
                    
                    pricebookEntryMap.put(pc.importantProductGoaIName__c + '_' + pc.depName__c, pbes[0]);  
                }
                // 商談新規後、商談商品作成
                List<OpportunityLineItem> oli = new List<OpportunityLineItem>();
                for (Opportunity insOpp : [select Id, Amount,Num_Of_OPD__c,Important_Key_product_category__c,Opportunity_Category__c,Objective__c from Opportunity where Id in :insertList]) {
                    oli.add(new OpportunityLineItem(
                        OpportunityId = insOpp.Id,
                        PricebookEntryId = pricebookEntryMap.get(insOpp.Important_Key_product_category__c + '_' + insOpp.Opportunity_Category__c).Id,
                        Quantity = isCntMap.get(insOpp.Important_Key_product_category__c + '_' + insOpp.Opportunity_Category__c) == false ? 1 : insOpp.Num_Of_OPD__c,
                        UnitPrice = isCntMap.get(insOpp.Important_Key_product_category__c + '_' + insOpp.Opportunity_Category__c) == false ? insOpp.Num_Of_OPD__c : 0
                    ));
                }
                insert oli;
            }
            
            if (updateList.size() > 0) {
                update updateList;
                
                List<OpportunityLineItem> oli = new List<OpportunityLineItem>();
                for (OpportunityLineItem updOli : [select Id, OpportunityId, Opportunity.Important_Key_product_category__c, Opportunity.Opportunity_Category__c from OpportunityLineItem where OpportunityId in : updateList]) {
                    updOli.UnitPrice = isCntMap.get(updOli.Opportunity.Important_Key_product_category__c + '_' + updOli.Opportunity.Opportunity_Category__c) == false ? oppAmount.get(updOli.OpportunityId) : 0;
                    updOli.Quantity = isCntMap.get(updOli.Opportunity.Important_Key_product_category__c + '_' + updOli.Opportunity.Opportunity_Category__c) == false ? 1 : oppAmount.get(updOli.OpportunityId);
                    oli.add(updOli);
                }
                update oli;
            }
            
            if (deleteList.size() > 0) delete deleteList;
            
            return true;
            
        } catch (Exception e) {
            Database.rollback(sp);
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, e.getMessage() + '|' + e.getLineNumber()));
            return false;
        }
    }*/

    public Pagereference UpdateBtn() {
        system.debug('=====UpdateBtn-1');
        boolean rs = saveLogic();
        setBean(iYear);
        Database.executeBatch(new SetProductTargetBatch(), 10);
        if (rs) {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, '反映到目标成功'));
        }
        return null;
    }

    private Boolean saveLogic() {
        List<Opportunity> insertList = new List<Opportunity>();
        List<Opportunity> updateList = new List<Opportunity>();
        List<Opportunity> deleteList = new List<Opportunity>();
        Savepoint sp = Database.setSavepoint();
        try {
            List<Key_Product_Goals__c> InsertKey_Product_Goals = new list<Key_Product_Goals__c>();
            List<Key_Product_Goals__c> UpdateKey_Product_Goals = new list<Key_Product_Goals__c>();
            // 只处理当前本部数据
            
            String target_Source = 'SalesTarget';
            if (isEng == true) {
                target_Source = 'EngTarget';
            }
            System.debug('allen===save==>>');
            for (Integer d = 0; d < dataBeans.size(); d++){
                DataBean db = dataBeans[d];
                system.debug('db+++++++ ' + db);
                if(String.isBlank(db.Opportunity.Owner_System__c))continue;
                for (Integer j = 0; j < amountCategory.size(); j++) {
                    ImportantProductCategory__c pc = pcList[j];
                        // 数据检索Key
                    String key = db.Opportunity.SAP_Province__c + '_' + target_category + '_' +
                                 pc.importantProductGoaIName__c + '_' + pc.depName__c + '_' + target_Source;
                    //     // String key = db.Opportunity.SAP_Province__c + '_' + amountCategory[j];
                    // if(String.isNotBlank(db.Opportunity.Owner_System__c)){
                    if(Key_Product_GoalsMap.containsKey(key)) {
                        //临时表已经有了
                        Key_Product_Goals__c Key_Product_Goal = Key_Product_GoalsMap.get(key);
                        if(Key_Product_Goal.Num_Of_OPD__c == db.amount[j].Num_Of_OPD__c) {
                            continue;
                        }else {
                            Key_Product_Goal.Num_Of_OPD__c = db.amount[j].Num_Of_OPD__c;
                            Key_Product_Goal.Department__c = db.department;
                            Key_Product_Goal.SAP_Province__c = db.Opportunity.SAP_Province__c;
                            Key_Product_Goal.Owner_System__c = db.Opportunity.Owner_System__c;
                            Key_Product_Goal.iYear__c = iYear;
                            Key_Product_Goal.Is_Processing__c = true;
                            Key_Product_Goal.Target_Source__c = target_Source;
                            UpdateKey_Product_Goals.add(Key_Product_Goal);
                        }
                    }else {
                        if (db.amount[j].Num_Of_OPD__c == null || db.amount[j].Num_Of_OPD__c == 0) {
                            continue;
                        }
                        Key_Product_Goals__c Key_Product_Goal = new Key_Product_Goals__c();
                        Key_Product_Goal.key__c = key;
                        Key_Product_Goal.Num_Of_OPD__c = db.amount[j].Num_Of_OPD__c;
                        Key_Product_Goal.Department__c = db.department;
                        Key_Product_Goal.SAP_Province__c = db.Opportunity.SAP_Province__c;
                        Key_Product_Goal.Owner_System__c = db.Opportunity.Owner_System__c;
                        Key_Product_Goal.iYear__c = iYear;
                        Key_Product_Goal.Is_Processing__c = true;
                        Key_Product_Goal.Target_Source__c = target_Source;
                        InsertKey_Product_Goals.add(Key_Product_Goal);
                    }

                    // }else {
                    //     if(Key_Product_GoalsMap.containsKey(key)) {
                    //         //临时表已经有了
                    //         Key_Product_Goals__c Key_Product_Goal = Key_Product_GoalsMap.get(key);
                    //         if(Key_Product_Goal.Num_Of_OPD__c == db.amount[j].Num_Of_OPD__c) {
                    //             continue;
                    //         }else {  
                    //             Key_Product_Goal.Num_Of_OPD__c = 0;
                    //             Key_Product_Goal.Department__c = db.department;
                    //             Key_Product_Goal.SAP_Province__c = db.Opportunity.SAP_Province__c;
                    //             Key_Product_Goal.Owner_System__c = db.Opportunity.Owner_System__c;
                    //             Key_Product_Goal.iYear__c = iYear;
                    //             Key_Product_Goal.Is_Processing__c = true;
                    //             UpdateKey_Product_Goals.add(Key_Product_Goal);
                    //         }
                    //     }
                    //     continue;
                    // }
                }
            }

            if(InsertKey_Product_Goals.size() > 0) {
                insert InsertKey_Product_Goals;
            }
            if(UpdateKey_Product_Goals.size() > 0) {
                update UpdateKey_Product_Goals;
            }
            return true;
        } catch (Exception e) {
            system.debug('=====saveLogic-e' + e.getMessage());
            Database.rollback(sp);
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, e.getLineNumber() + ':' + e.getMessage()));
            return false;
        }
    }
    
    private Map<String, String> getImpProductMap(String ac) {
        Map<String, String> impmap = new Map<String, String> {
            '重点产品01' => 'Important_Rroduct_1' + ac +'__c',
            '重点产品02' => 'Important_Rroduct_2' + ac +'__c',
            '重点产品03' => 'Important_Rroduct_3' + ac +'__c',
            '重点产品04' => 'Important_Rroduct_4' + ac +'__c',
            '重点产品05' => 'Important_Rroduct_5' + ac +'__c',
            '重点产品06' => 'Important_Rroduct_6' + ac +'__c',
            '重点产品07' => 'Important_Rroduct_7' + ac +'__c',
            '重点产品08' => 'Important_Rroduct_8' + ac +'__c',
            '重点产品09' => 'Important_Rroduct_9' + ac +'__c',
            '重点产品10' => 'Important_Rroduct_10' + ac +'__c',
            '重点产品11' => 'Important_Rroduct_11' + ac +'__c',
            '重点产品12' => 'Important_Rroduct_12' + ac +'__c',
            '重点产品13' => 'Important_Rroduct_13' + ac +'__c',
            '重点产品14' => 'Important_Rroduct_14' + ac +'__c',
            '重点产品15' => 'Important_Rroduct_15' + ac +'__c',
            '重点产品16' => 'Important_Rroduct_16' + ac +'__c',
            '重点产品17' => 'Important_Rroduct_17' + ac +'__c',
            '重点产品18' => 'Important_Rroduct_18' + ac +'__c',
            '重点产品19' => 'Important_Rroduct_19' + ac +'__c',
            '重点产品20' => 'Important_Rroduct_20' + ac +'__c',
            '重点产品21' => 'Important_Rroduct_21' + ac +'__c',
            '重点产品22' => 'Important_Rroduct_22' + ac +'__c',
            '重点产品23' => 'Important_Rroduct_23' + ac +'__c',
            '重点产品24' => 'Important_Rroduct_24' + ac +'__c',
            '重点产品25' => 'Important_Rroduct_25' + ac +'__c',
            '重点产品26' => 'Important_Rroduct_26' + ac +'__c',
            '重点产品27' => 'Important_Rroduct_27' + ac +'__c',
            '重点产品28' => 'Important_Rroduct_28' + ac +'__c',
            '重点产品29' => 'Important_Rroduct_29' + ac +'__c',
            '重点产品30' => 'Important_Rroduct_30' + ac +'__c',
            '重点产品31' => 'Important_Rroduct_31' + ac +'__c'
        };
        return impmap;
    }
    
    // 数据类
    class DataBean {
        // 担当者信息
        public Opportunity opportunity { get; set; }
        // 总金额，画面用
        public Opportunity[] amount { get; set; }
        // 本部表示用
        public String department { get; private set; }
        // 是否变化 0：无 1：有
        public String isChanged { get; set; }
        //CHAN-BDQBLX  20210204 ljh start  导出用name
        public String ownername { get; private set; }
        //CHAN-BDQBLX  20210204 ljh end
        // 构造方法
        DataBean(String salesDpt, String province, Map<String, Opportunity> oppMap, Integer iYear, String category, Map<String, AggregateResult> oliMap, List<ImportantProductCategory__c> pcList2) {
            this.opportunity = new Opportunity();
            this.amount = new List<Opportunity>();
            this.opportunity.SAP_Province__c = province;
            this.department = salesDpt;
            this.isChanged = '0';

            // 按金额分类，查找数据，并设值
            //List<ImportantProductCategory__c> pcList2 = [select depName__c,importantProductGoaIName__c,commodityCode__c,commodityName__c,if_Quantity__c,sort__c from ImportantProductCategory__c order by sort__c];
            System.debug('allen==------'+pcList2);

            System.debug('allen==?'+pcList2.size());
            for (Integer i = 0; i < pcList2.size(); i++) {
                ImportantProductCategory__c pc = pcList2[i];  
                Opportunity a = new Opportunity();
                a.Opportunity_Category__c = pc.depName__c;
                Decimal amountSum = 0.0;
                for (Integer j = 0; j < 12; j++) {
                    Integer y = iYear;
                    Integer m = 4 + j;
                    if (m > 12) {
                        y += 1;
                        m -= 12;
                    }
                    String strY = String.valueOf(y);
                    String strM = String.valueOf(m);
                    if (strM.length() < 2) {
                        strM = '0' + strM;
                    }
                    String key = this.opportunity.SAP_Province__c + '_' + category + '_' + pc.importantProductGoaIName__c + '_' + pc.depName__c + '_' + strY + '-' + strM + '-01';
                    if (oppMap.containskey(key)) {
                        if (oppMap.get(key).Owner_System__c != null) {
                            this.opportunity.Owner_System__c = oppMap.get(key).Owner_System__c;
                        }
                        //a.Amount = oppMap.get(key).Amount;
                        if (isCntMap.get(pc.importantProductGoaIName__c + '_' + pc.depName__c) == false) {
                            amountSum += oliMap.get(oppMap.get(key).Id).get('sum_o') == null ? 0 : (Decimal) oliMap.get(oppMap.get(key).Id).get('sum_o');
                        } else {
                            amountSum += oliMap.get(oppMap.get(key).Id).get('sum_n') == null ? 0 : (Decimal) oliMap.get(oppMap.get(key).Id).get('sum_n');
                        }
                    }
                }
                
                if (amountSum > 0) {
                    if (category == '重点产品目标(金额)') {
                        amountSum = amountSum.setScale(2);
                        a.Amount = amountSum;
                    } else {
                        amountSum = amountSum.round();
                        a.Num_Of_OPD__c = amountSum;
                    }
                }  
                  
                this.amount.add(a);
            }
        }
    }
}