public with sharing class SetPersonalProductTargetController {
    // 当前期
    public String currentPeriod { get; private set; }
    public String currentPeriodOld;//20210225  ljh WLIG-BV8CHF 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 User loginUser { get; set; }
    // checkAll値保持用
    public Boolean checkAll { get; set; }
    // 製品担当の選択値
    public String productUser { get; set; }
    public Integer titleSize { get; set; }

    // 製品担当 プルダウン
    public static List<SelectOption> productUserOptions { get; private set; }

    static {
        productUserOptions = new List<SelectOption>();
        productUserOptions.add(new SelectOption('产品担当', '产品担当'));
        productUserOptions.add(new SelectOption('产品担当以外', '产品担当以外'));
    }

    // 目标区分
    public String target_category { get; set; }
    // 製品プルダウン用
    public Opportunity opp { get; set; }

    public SetPersonalProductTargetController() {

    }

    // ユーザ数
    public Integer getUserSize() {
        return users.size();
    }
    // 本部プルダウン
    public static List<SelectOption> salesDptOpts { get; private set; }
    static {
        salesDptOpts = new List<SelectOption>();
        salesDptOpts.add(new SelectOption('', '--无--'));
        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.华南'));
        salesDptOpts.add(new SelectOption('7.能量', '7.能量'));
    }



    // 重点目标分类
    public static List<SelectOption> targetOpts { get; private set; }
    static {
        targetOpts = new List<SelectOption>();
        targetOpts.add(new SelectOption('重点产品目标(数量)', '重点产品目标(数量)'));
        targetOpts.add(new SelectOption('重点产品目标(金额)', '重点产品目标(金额)'));
    }

    // 职种
    public static List<SelectOption> userJobCategorys { get; private set; }
    static {
        userJobCategorys = new List<SelectOption>();
        userJobCategorys.add(new SelectOption('', '--无--'));
        userJobCategorys.add(new SelectOption('销售推广', '销售推广'));
        userJobCategorys.add(new SelectOption('销售市场', '销售市场'));
    }

    //  现在年度
    private Integer currentYear;
    //  当前年度
    private Integer iYear;
    private RecordType rt;           // 目标的数据类型
    private User[] users;            // 担当人员
    private Map<String, List<Double>> proportion;     // 比重
    private String adminDpt = null;

    private List<String> provinces;
    private Map<String, List<String>> salesDptMap; //本部-省对应关系
    private Map<String, String> provinceMap;       //省-本部对应关系

    //更新用条件
    //private String old_target_category;
    //private String old_important_Key_product_category;

    //2018年7月5日 SWAG-AZHBH7 中间表既存数据 by 张玉山
    private Map<String, Num_Major_Product__c> Num_Major_ProductMap;

    // 既存目标数据
    private Map<String, Opportunity> oppsMap;
    private Map<Id, OpportunityLineItem> oliMap;


    // 金额分类
    // private static String[] amountCategory = new String[20] {'GI','ET','BF','GS','URO','GYN','ENT','OTH'};

    // xiongyl--start
    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 ljh add
    // public static List<DataBeanForSort> dataBeanForSortList { get; private set; }
    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);//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);//20210204 ljh add
            }
            // DataBeanForSort titles = new DataBeanForSort(pc);
            //dataBeanForSortList.add(titles);
        }
        // dataBeanForSortList.sort();
    }



    // xiongyl--end
    // 重点製品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  20210129 ljh start
    private List<Num_Major_Product__c> upsertNMPList;
    private Map<String, Num_Major_Product__c> Num_Major_ProductMap1;
    public Boolean isFlg { get; set; }//判断走哪个查询方法
    public Boolean isFlg1 { get; set; }
    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  20210129 ljh end
    // 画面初始化
    public Pagereference init() {
        // 现在时间
        Date dateNow = Date.today();
        Integer year = dateNow.year();
        Integer month = dateNow.month();
        //CHAN-BDQBLX  20210204 LJH start
        Num_Major_ProductMap1 = new Map<String, Num_Major_Product__c>();
        upsertNMPList = new List<Num_Major_Product__c>();
        detailCountLimit = 10000;
        //CHAN-BDQBLX  20210204 LJH end
        if (month < 4) {
            year -= 1;
        }
        // 初始化
        opp = new Opportunity();
        //xiongyl
        //opp.Important_Key_product_category__c = '重点产品01';
        titleSize = pcList.size();
        currentYear = year;
        iYear = year;
        isPast = false;
        //        if (month == 3) isPast = true;
        //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 = '担当重点产品目标';

        //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);
        }
        // 職位
        checkAll = true;

        // 当前用户信息
        if (loginUser == null) {
            loginUser = [Select Id, Salesdepartment__c, Province__c, ProfileId, Job_Category__c, Sales_Speciality__c From User where Id = :Userinfo.getUserId()];
            loginUser.Job_Category__c = null;
            loginUser.Sales_Speciality__c = null;
        }
        adminDpt = loginUser.Salesdepartment__c;
        if (String.isBlank(adminDpt)
                && (loginUser.ProfileId == System.Label.ProfileId_SystemAdmin
                    || loginUser.ProfileId == System.Label.ProfileId_103
                   )
           ) {
            adminDpt = '5.华东';
        }

        getsalesDptMap();
        provinces = new List<String>();
        provinces = salesDptMap.get(adminDpt);

        users = this.getUserList(false, false, true);
        isFlg1=true;//CHAN-BDQBLX  20210129 ljh add
        // 目标的数据类型
        if (rt == null) {
            rt = [select Id from RecordType where SobjectType = 'Opportunity' and IsActive = true and DeveloperName = 'Target'];
        }
        // 数据赋值
        setBean(iYear);
        // 保存成功のメッセージ
        String s = System.currentPageReference().getParameters().get('s');
        if (s == '1') {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, '保存成功。'));
        }
        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()) {
            //SWAG-BB48QB 判断当前时间是否是4月15日之后 end
            isPast = true;
        }// else if (iYear == currentYear) {
        //            if (Date.today().month() == 3) {
        //                isPast = true;
        //            }
        //        }
        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()) {
            //SWAG-BB48QB 判断当前时间是否是4月15日之后 end
            isPast = true;
        }//  else if (iYear == currentYear) {
        //            if (Date.today().month() == 3) {
        //                isPast = true;
        //            }
        //        }
        previousRendered = true;
        nextRendered = true;
        // 只显示到现在时间的下一年数据
        if (iYear > currentYear) {
            nextRendered = false;
        }
        // 数据赋值
        setBean(iYear);
    }

    // 本部プルダウン変更時の処理
    public void searchByDpt() {
        if (saveFlg) {
            this.saveLogic();
        }

        provinces = new List<String>();
        provinces = salesDptMap.get(salesDpt);
        opp.SAP_Province__c = null;
        //CHAN-BDQBLX  20210129 ljh start
        isFlg = true;
        isFlg1=false;
        //CHAN-BDQBLX  20210129 ljh end
        users = this.getUserList(true, false, false);
        // 数据赋值
        setBean(iYear);
    }

    // 省プルダウン変更時の処理
    public void searchByProvince() {
        if (saveFlg) {
            this.saveLogic();
        }

        provinces = new List<String>();
        if (opp.SAP_Province__c == null) {
            if (salesDpt != null) {
                provinces = salesDptMap.get(salesDpt);
            } else {
                provinces = salesDptMap.get(adminDpt);
            }
        } else {
            provinces.add(opp.SAP_Province__c);
            salesDpt = null;
        }
         //CHAN-BDQBLX  20210129 ljh start
        isFlg = false;
        isFlg1= false;
        //CHAN-BDQBLX  20210129 ljh end
        users = this.getUserList(false, true, false);
        // 数据赋值
        setBean(iYear);
    }

    // 重点製品変更時の処理
    public void searchByImpKey() {
        if (saveFlg) {
            this.saveLogic();
        }
        //old_important_Key_product_category = opp.Important_Key_product_category__c;
        users = this.getUserList(false, false, false);
        isFlg1=false;//CHAN-BDQBLX  20210129 ljh add
        // 数据赋值
        setBean(iYear);
    }

    // SearchFilter変更時の処理
    public void searchByFilter() {
        if (saveFlg) {
            this.saveLogic();
        }
        users = this.getUserList(false, false, false);
        isFlg1=false;//CHAN-BDQBLX  20210129 ljh add 
        // 数据赋值
        setBean(iYear);
    }
    //CHAN-BDQBLX  20210129 ljh start 导入出方法 start
    public Pagereference exportBycsv() {
        system.debug('isFlg==' + isFlg);
        boolflag(isFlg1,isFlg);//判断执行哪个查询得方法
        return page.SetPersonalProductTargetcvs;
    }
    //导入方法
    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);
            }
            if (csvFileLines.size() > 0) {
                string[] titlecsv = csvFileLines[0].trim().split(',');
                System.debug('==titlepage=='+titlepage);
                System.debug('==titlecsv=='+titlecsv);
                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>();//省份
                Set<String> bus = new Set<String>();//本部
                Set<String> zws = new Set<String>();//职位
                Set<String> yydds = new Set<String>();//医院担当
                Set<String> zzs = 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[3].replace(' ', '');
                        String zw = csvRecordData[4].replace(' ', '');
                        UserInfoList.add(bu + sf + dandang + zw);
                        szMap.put(bu + sf + dandang + zw, csvRecordData);
                        sfs.add(sf);//把省份放进去
                        bus.add(bu);//本部
                        zws.add(zw);//职位
                    }
                }
                if (null != sfs && sfs.size() > 0) {
                    this.getNum_Major_Product(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) {
                    yydds.add(userl.Sales_Speciality__c);//医院担当
                    zzs.add(userl.Job_Category__c);//职种
                    userMap.put(userl.UserInfos__c, userl);

                }                
                upsertNMPList = new List<Num_Major_Product__c>();//初始化，解决重复导入数据 id重复得问题
                for (String key : szMap.keySet()) {
                    //取用户的Id
                    String userid = '';
                    User userinfors=new User();
                    if (userMap.containskey(key)) {
                        userid = userMap.get(key).Id;
                        userinfors = userMap.get(key);
                    } else {
                        //用户不存在要提醒
                        continue;
                    }
                    //string key = ('' + db.user.Id).substring(0, 15) + '_' + target_category + '_' +
                    // pc.importantProductGoaIName__c + '_' + pc.depName__c;
                   //--------
                    List<String> csvRecordData = szMap.get(key);
                    Num_Major_Product__c upsertNMP = new Num_Major_Product__c();
                    Integer tI = amountCategory.size()+7;//数字7取决于导入的cvs重点产品前的个数
                    for(Integer i = 7;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 = ('' + userid).substring(0, 15) + '_' + target_category + '_' +NkeyMap.get(amountCategory[i-7]);
                        DataSplicing(Num_Of_OPD,nkey,Num_Major_ProductMap1,userinfors);
                    }
                }
                if(null!=upsertNMPList && upsertNMPList.size()>0){
                    upsert upsertNMPList;
                }
                boolflag(isFlg1,isFlg);
                    
                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, Map<String, Num_Major_Product__c> nmpMap,User userinfors ) {//去进行最终数据得插入，更新或删除操作
        Num_Major_Product__c upsertNMP = new Num_Major_Product__c();
        Num_Major_Product__c Num_Major_Product = Num_Major_ProductMap.get(key);   
        if (nmpMap.containskey(key)) {
            upsertNMP = nmpMap.get(key);
            if (NumOfOPD > 0) {
                if(NumOfOPD != upsertNMP.Num_Of_OPD__c){
                    upsertNMP.Num_Of_OPD__c = NumOfOPD;
                    upsertNMP.Is_Processing__c = true;
                    upsertNMPList.add(upsertNMP);
                    //更新
                }
                
            } else {
                //不用删除了，允许 数据是空的存在
                upsertNMP.Num_Of_OPD__c = null;
                upsertNMP.Is_Processing__c = true;
                upsertNMPList.add(upsertNMP);
            }
        } else {
            if (NumOfOPD > 0) {
                upsertNMP.Num_Of_OPD__c = NumOfOPD;
                upsertNMP.key__c = key;
                upsertNMP.user_Alias__c = userinfors.Alias;
                upsertNMP.SAP_Province__c = userinfors.Province__c;
                upsertNMP.iYear__c = iYear;
                upsertNMP.Is_Processing__c = true;
                upsertNMPList.add(upsertNMP);
            } else {
                //允许 数据是空的存在
                upsertNMP.Num_Of_OPD__c = null;
                upsertNMP.key__c = key;
                upsertNMP.user_Alias__c = userinfors.Alias;
                upsertNMP.SAP_Province__c = userinfors.Province__c;
                upsertNMP.iYear__c = iYear;
                upsertNMP.Is_Processing__c = true;
                upsertNMPList.add(upsertNMP);
            }
        }
    }
    private void getNum_Major_Product(Set<String> sfs) {//根据省份年份，获取当前系统中已经存在得数据
        Num_Major_ProductMap1 = new Map<String, Num_Major_Product__c>();

        list<Num_Major_Product__c> Existed_Num_Major_Products = [select key__c, Num_Of_OPD__c, user_Alias__c,
                                      Is_Processing__c, iYear__c from Num_Major_Product__c where iYear__c = : iYear and SAP_Province__c in :sfs];
        for (Num_Major_Product__c Num_Major_Product : Existed_Num_Major_Products ) {
            if (String.isBlank(Num_Major_Product.key__c)) {
                continue;
            }
            Num_Major_ProductMap1.put(Num_Major_Product.key__c, Num_Major_Product);
        }
    }
    private List<User> getUserList(List<String> UserInfoList) {//根据上传文件中得本部，省份，担当，职位 得到了user 信息
        String soql = 'select Id, UserInfos__c, Salesdepartment__c, Province__c, Alias, Product_specialist_incharge_product__c, Use_Start_Date__c,'
                      + ' ProfileId, Profile.Name, UserRoleId, UserRole.Name, Sales_Speciality__c, HR_Post__c,Job_Category__c,'
                      // + ' Responsible_for_Products_Concurrently__c, Product_specialist_incharge_dept__c'
                      + ' Responsible_for_Products_Concurrently__c'
                      + ' from User where IsActive = true and Test_staff__c = false and UserType = \'Standard\' '
                      + ' and Salesdepartment__c <> \'7.能量\' '
                      + ' and UserInfos__c IN :UserInfoList order by Salesdepartment__c, Province__c';
        System.debug('==soql==' + soql);
        return Database.query(soql);
    }
    //CHAN-BDQBLX  20210129 ljh start 导入出方法 end
    // 点击保存按钮
    public Pagereference saveBtn() {
        system.debug('=====saveBtn-1');
        boolean rs = saveLogic();
        setBean(iYear);
        if (rs) {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, '保存成功'));
        }
        return null;
    }

    // 2018年7月6日，SWAG-AZHBH7 点击更新按钮 by 张玉山
    public Pagereference UpdateBtn() {
        system.debug('=====UpdateBtn-1');
        boolean rs = saveLogic();
        setBean(iYear);
        Database.executeBatch(new SetPersonalProductTargetBatch(), 10);
        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;
    }

    //获取本部-省对应关系
    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);

        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 boolflag(Boolean isFlg1, Boolean isFlg) {//判断走哪个查询方法，进行导出数据
        if(isFlg1!=null && isFlg1){
            system.debug('初始化');
            users = this.getUserList(false, false, true);
        }else if (isFlg != null && isFlg) {
            system.debug('进1');
            users = this.getUserList(true, false, false);
        } else if ( isFlg != null && !isFlg) {
            system.debug('进2');
            users = this.getUserList(false, true, false);
        } else {
            system.debug('进3');
            users = this.getUserList(false, false, false);
        }
        // 数据赋值
        setBean(iYear);
    }
    // 2018年7月6日 SWAG-AZHBH7 从中间表获取既有数据，并以key__c为key存入map中 by 张玉山
    // key__c = db.user.Id + '_' + target_category + '_' + pc.importantProductGoaIName__c +'_' + pc.depName__c;
    private boolean getNum_Major_Productmap() {
        Num_Major_ProductMap = new Map<String, Num_Major_Product__c>();
        if (getUserSize() == 0) {
            return false;
        }

        list<Num_Major_Product__c> Existed_Num_Major_Products = [select key__c, Num_Of_OPD__c, user_Alias__c, SAP_Province__c,
                                   Is_Processing__c, iYear__c from Num_Major_Product__c where iYear__c = : iYear ];
        system.debug('Existed_Num_Major_Products' + Existed_Num_Major_Products);
        if (Existed_Num_Major_Products.size() <= 0 ) {
            return false;
        }
        for ( Num_Major_Product__c Num_Major_Product : Existed_Num_Major_Products ) {
            if (String.isBlank(Num_Major_Product.key__c)) {
                continue;
            }
            // 2018年7月25日 SWAG-B2Z344 仅获取当前用户数据存入map中  start by 张玉山
            boolean flag = false;
            for (User user : users) {
                if (user.Alias.equals(Num_Major_Product.user_Alias__c)) {
                    flag = true;
                    break;
                }
            }
            if (flag) {
                Num_Major_ProductMap.put(Num_Major_Product.key__c, Num_Major_Product);
            }
            // 2018年7月25日 SWAG-B2Z344 仅获取当前用户数据存入map中  end by 张玉山
        }
        system.debug('Num_Major_ProductMap' + Num_Major_ProductMap.keySet());
        return true;
    }

    // ユーザの検索
    private List<User> getUserList(Boolean searchByDpt, Boolean searchByProvince, Boolean defaultSearch) {
        // String soql = 'select Id, Salesdepartment__c, Province__c, Alias, Job_Category__c, Product_specialist_incharge_dept__c,Use_Start_Date__c,'
        String soql = 'select Id, Salesdepartment__c, Province__c, Alias, Job_Category__c,Use_Start_Date__c,'
                      + ' ProfileId, Profile.Name, UserRoleId, UserRole.Name, Sales_Speciality__c, Post__c,HR_Post__c,'
                      + ' Product_specialist_incharge_product__c,Responsible_for_Products_Concurrently__c'
                      + ' from User where IsActive = true and Test_staff__c = false and UserType = \'Standard\' ';
        if (defaultSearch || productUser == '产品担当') {
            soql += ' and Sales_Speciality__c = \'产品担当\'';
        } else {
            soql += ' and Sales_Speciality__c <> \'产品担当\'';
        }
        // 职种
        if (defaultSearch || String.isBlank(loginUser.Job_Category__c)) {
            soql += ' and (Job_Category__c = \'销售推广\' or Job_Category__c = \'销售市场\')';
        } else {
            soql += ' and Job_Category__c = \'' + loginUser.Job_Category__c + '\'';
        }
        // 销售工作内容
        if (!String.isBlank(loginUser.Consumable_sales__c)) {
            soql += ' and Consumable_sales_formula__c = \'' + loginUser.Consumable_sales__c + '\'';
        }
        // 本部にて検索の場合、省を無視
        if (searchByDpt) {
            loginUser.Province__c = null;
            // 省にて検索の場合、本部を無視
        } else if (searchByProvince) {
            salesDpt = null;
            // 職位にて検索の場合
        } else {}

        if (!String.isBlank(salesDpt)) {
            soql += ' and Salesdepartment__c = \'' + salesDpt + '\'';
        }
        if (!String.isBlank(loginUser.Province__c)) {
            soql += ' and Province__c = \'' + loginUser.Province__c + '\'';
        }
        if (String.isBlank(salesDpt) && String.isBlank(loginUser.Province__c)) {
            soql += ' and Salesdepartment__c = \'' + adminDpt + '\'';
        }

        if (checkAll) {
            soql += ' and (Post__c = \'一般\' or Post__c = \'高级\' or Post__c = \'主管\')';
        } else {
            //soql += ' and (Post__c <> \'一般\' and Post__c <> \'高级\' and Post__c <> \'主管\')';
            // SetPersonalTargetControllerと同じ、「全部」ではない
            soql += ' and (Post__c = \'一般\' or Post__c = \'高级\' or Post__c = \'主管\' or Post__c = \'副经理\' or Post__c = \'经理\' or Post__c = \'副部长\' or Post__c = \'部长\')';
        }
        soql += ' order by Salesdepartment__c, Province__c, UserRole.Name';

        return Database.query(soql);
    }

    // 数据赋值
    private void setBean(Integer year) {
        // 取得当前年度目标数据
        Opportunity[] opportunitys = [select
                                      Id, OwnerId, Opportunity_Category__c, Proportion__c, CloseDate,
                                      Amount, Objective__c, Target_category__c, Important_Key_product_category__c,
                                      SAP_Province__c, RecordTypeId, OCM_Target_period__c, Owner_System__c
                                      from Opportunity
                                      where Target_category__c = :target_category
                                              // and Important_Key_product_category__c = :opp.Important_Key_product_category__c   xiongyl
                                              and RecordTypeId = :rt.Id
                                                      and OwnerId in :users
                                                      //20210225 ljh WLIG-BV8CHF update  财年 start
                                                      //and OCM_Target_period__c = :currentPeriod];
                                                      and OCM_Target_period__c = :currentPeriodOld];
                                                      //20210225 ljh WLIG-BV8CHF update  财年 end

        list<Num_Major_Product__c> Existed_Num_Major_Products = [select key__c, Num_Of_OPD__c, user_Alias__c, SAP_Province__c,
                                   Is_Processing__c, iYear__c from Num_Major_Product__c where iYear__c = : iYear ];
        system.debug('Existed_Num_Major_Products' + Existed_Num_Major_Products);
        // 当前年度没有数据时，显示信息
        system.debug('opportunitys.size()' + opportunitys.size()
                     + ' isPast:' + isPast
                     + 'iYear:' + iYear + 'currentYear:' + currentYear);
        if (Existed_Num_Major_Products.size() <= 0 && isPast && iYear < currentYear && checkCurrentDate()) {
            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;
            Date dateNow = Date.today();
            Integer iMonth  = dateNow.month();
            Integer iDay = dateNow.day();
            if (iYear < currentYear && !(currentYear - iYear == 1 && iMonth == 4
                                         && iDay <= Integer.valueOf(System.Label.SetPersonalTarget_buffer_day))) {
                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.OwnerId).substring(0, 15) + '_' + opp.Target_category__c + '_' + opp.Important_Key_product_category__c
                             + '_' + opp.Opportunity_Category__c + '_' + String.valueOf(opp.CloseDate);
                oppsMap.put(key, opp);
            }
        }

        OpportunityLineItem[] opportunityLineItems = [select Id, OpportunityId, Quantity, UnitPrice, NumberOfObjective__c,
                              Objective__c from OpportunityLineItem where OpportunityId in :opportunitys];
        oliMap = new Map<Id, OpportunityLineItem>();
        // 2018年7月6日 SWAG-AZHBH7 注释掉 by张玉山
        /*for (OpportunityLineItem oli : opportunityLineItems) {
            oliMap.put(oli.OpportunityId, oli);
        }*/
        // 2018年7月6日 SWAG-AZHBH7 读取中间既存表 by张玉山
        getNum_Major_Productmap();

        dataBeans = new List<DataBean>();
        for (Integer u = 0; u < users.size(); u++) {
            DataBean dataBean = new DataBean(users[u], provinceMap.get(users[u].Province__c), users[u].Province__c,
                                             oppsMap, iYear, target_category, oliMap, pcList);
            // 2018年7月6日 SWAG-AZHBH7 与既有中间表数据进行对比，然后更新至visualforce page by 张玉山
            for (Integer j = 0; j < pcList.size(); j++) {
                ImportantProductCategory__c pc = pcList[j];
                // 数据检索Key
                string key = ('' + users[u].Id).substring(0, 15) + '_' + target_category + '_' + pc.importantProductGoaIName__c + '_' + pc.depName__c;
                //system.debug('+++++++ Num_Major_ProductMap check step1:' + key);

                if (Num_Major_ProductMap.containsKey(key)) {
                    Num_Major_Product__c Num_Major_Product = Num_Major_ProductMap.get(key);
                    dataBean.oppInput[j].Num_Of_OPD__c = Num_Major_Product.Num_Of_OPD__c;
                } else {
                    dataBean.oppInput[j].Num_Of_OPD__c = null;
                }
            }
            dataBeans.add(dataBean);
        }

    }

    // 是否删除整行数据
    /*   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 < amountCategory.size(); j++) {
                       String amountC = amountCategory[j];
                       // 数据检索Key
                       String key = db.opportunity.SAP_Province__c + '_' + target_category + '_' + opp.Important_Key_product_category__c + '_' + amountC + '_' + 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>();
        system.debug('=====saveLogic-0');
        Savepoint sp = Database.setSavepoint();
        try {
            Map<String, Decimal> oppAmount = new Map<String, Decimal>();
            Map<String, String> saveAmountCategoryMap = new Map<String, String>();
            //2018年7月5日 SWAG-AZHBH7 中间表初始化 by 张玉山
            list<Num_Major_Product__c> InsertNum_Major_Products = new list<Num_Major_Product__c>();
            list<Num_Major_Product__c> UpdateNum_Major_Products = new list<Num_Major_Product__c>();

            for (Integer d = 0; d < dataBeans.size(); d++) {
                DataBean db = dataBeans[d];

                // 寄存数据比例值是否变化
                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.user.Id).substring(0, 15) + '_' + 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) {
                    system.debug('=====saveLogic-1');
                    continue;
                }
                User u = new User();
                // 2018年7月6日  SWAG-AZHBH7 与中间表已有数据进行对比后决定插入或更新至中间表并赋值  by张玉山
                for (Integer j = 0; j < pcList.size(); j++) {
                    // 数据检索Key
                    ImportantProductCategory__c pc = pcList[j];
                    string key = ('' + db.user.Id).substring(0, 15) + '_' + target_category + '_' +
                                 pc.importantProductGoaIName__c + '_' + pc.depName__c;
                    system.debug('key：' + key);
                    if (Num_Major_ProductMap.containsKey(key)) {
                        Num_Major_Product__c Num_Major_Product = Num_Major_ProductMap.get(key);
                        if (Num_Major_Product.Num_Of_OPD__c == db.oppInput[j].Num_Of_OPD__c) {
                            continue;
                        }
                        Num_Major_Product.Num_Of_OPD__c = db.oppInput[j].Num_Of_OPD__c;
                        Num_Major_Product.user_Alias__c = db.user.Alias;
                        Num_Major_Product.SAP_Province__c = db.user.Province__c;
                        Num_Major_Product.iYear__c = iYear;
                        Num_Major_Product.Is_Processing__c = true;
                        UpdateNum_Major_Products.add(Num_Major_Product);
                    } else {
                        if (db.oppInput[j].Num_Of_OPD__c == null || db.oppInput[j].Num_Of_OPD__c == 0) {
                            continue;
                        }
                        Num_Major_Product__c Num_Major_Product = new Num_Major_Product__c();
                        Num_Major_Product.key__c = key;
                        Num_Major_Product.Num_Of_OPD__c = db.oppInput[j].Num_Of_OPD__c;
                        Num_Major_Product.user_Alias__c = db.user.Alias;
                        Num_Major_Product.SAP_Province__c = db.user.Province__c;
                        Num_Major_Product.iYear__c = iYear;
                        Num_Major_Product.Is_Processing__c = true;
                        InsertNum_Major_Products.add(Num_Major_Product);
                    }
                }


//                if (db.opportunity.Owner_System__c == null) {
//                    if (isDelete(db) == false) {
//                      system.debug('=====saveLogic-2');
//                        continue;
//                    }
//                }

                //2018年7月5日 SWAG-AZHBH7 注释掉， 迁移至SetPersonalProductTargetBatch by 张玉山
                // 一年分成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.user.Id + '_' + target_category + '_' + pc.importantProductGoaIName__c + '_' + pc.depName__c + '_' + sTagetDay;

                        // 每月数据赋值
                        Opportunity newopp = new Opportunity();
                        if (oppsMap.containskey(key)) {
                            newopp = oppsMap.get(key);
                            if (db.oppInput[j].Num_Of_OPD__c == null || db.oppInput[j].Num_Of_OPD__c == 0) {
                                deleteList.add(newopp);
                                continue;
                            }
                            newopp.OwnerId = db.user.Id;
                            newopp.Owner_System__c = db.user.Id;
                            newopp.Num_Of_OPD__c = db.oppInput[j].Num_Of_OPD__c;
                            String depName = (pc.depName__c == null || pc.depName__c == '') ? 'GI' : pc.depName__c;
                            newopp.Proportion__c = proportion.get(depName)[i];
                            oppAmount.put(newopp.Id, db.oppInput[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.oppInput[j].Num_Of_OPD__c == null || db.oppInput[j].Num_Of_OPD__c == 0) {
                                continue;
                            }
                            newopp.Name = db.user.Alias + ' ' + pc.importantProductGoaIName__c ;
                            newopp.StageName = '目標';
                            newopp.OwnerId = db.user.Id;
                            // トリガをスルーのため、ここでやります
                            newopp.Owner_System__c = db.user.Id;
                            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.oppInput[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.user.Province__c;
                            newopp.RecordTypeId = rt.Id;
                            newopp.OCM_Target_period__c = currentPeriod;

                            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.user.Alias + '的数据操作完成，之后的数据请再次输入并保存。'));
                    break;
                }

                */
            }
            // 2018年7月6日 SWAG-AZHBH7 将数据存入或更新至中间表 by 张玉山
            //system.debug('++++++++++++++InsertNum_Major_Products:'+InsertNum_Major_Products);
            //system.debug('++++++++++++++UpdateNum_Major_Products:'+UpdateNum_Major_Products);
            if ( InsertNum_Major_Products.size() > 0 ) {
                insert InsertNum_Major_Products;
            }
            if ( UpdateNum_Major_Products.size() > 0 ) {
                update UpdateNum_Major_Products;
            }

            //2018年7月5日 SWAG-AZHBH7 迁移至SetPersonalProductTargetBatch by 张玉山
            /*
            // トリガをスルー
            StaticParameter.EscapeOpportunityBefUpdTrigger = true;
            StaticParameter.EscapeOpportunityHpDeptUpdTrigger = true;
            StaticParameter.EscapeSyncOpportunityTrigger = true;
            StaticParameter.EscapeNFM001Trigger = true;
            StaticParameter.EscapeNFM001AgencyContractTrigger = true;
            StaticParameter.EscapeNFM007Trigger = true;

            // 更新数据库
            if (insertList.size() > 0) {
                insert insertList;
                system.debug('=====saveLogic-3');
                Map<String,PricebookEntry> pricebookEntryMap = new Map<String,PricebookEntry>();
                // 製品を検索
                for (ImportantProductCategory__c pc : pcList){
                    String dep = pc.depName__c;
                    Map<String, String> impmap = getImpProductMap(dep);
                    // TODO GI BFなどの判別は要らない？
                    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 + '-' + pc.depName__c));
                        return false;
                    }
                    pricebookEntryMap.put(pc.importantProductGoaIName__c + '_' + pc.depName__c, pbes[0]);

                }
                // 商談新規後、商談商品作成
                List<OpportunityLineItem> oli = new List<OpportunityLineItem>();
                for (Opportunity insOpp : [select Id,Important_Key_product_category__c,Opportunity_Category__c,Amount,Num_Of_OPD__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;
                system.debug('=====saveLogic-4');
                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) {system.debug('=====saveLogic-5');delete deleteList;}
            */
            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;
        }
    }

    //2018年7月5日 SWAG-AZHBH7 迁移至SetPersonalProductTargetBatch by 张玉山
    /*
    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 DataBeanForSort  implements Comparable{
    //public ImportantProductCategory__c importantProduct { get; private set; }
    // public String sortSeq { get; private set; }
    //  DataBeanForSort(){}
    // DataBeanForSort(ImportantProductCategory__c importantProductCategory){
    //this.importantProduct = importantProductCategory;
    //  this.sortSeq = importantProductCategory.sort__c;
    // }

    // 排序
    // public Integer compareTo(Object obj) {
    // ImportantProductCategory__c info = (ImportantProductCategory__c)(obj);
    // if (this.sortSeq == info.sort__c) {
    // return 0;
    // }
    //if (this.sortSeq > info.sort__c) {
    //return 1;
    // }
    //  return -1;
    // }
//}

    // 数据类
    class DataBean {
        // 担当者信息
        public User user { get; private set; }
        // 担当者信息
        public Opportunity opportunity { get; set; }
        // 总金额，画面用
        public Opportunity[] oppInput { get; set; }
        // 本部表示用
        public String department { get; private set; }
        // 是否变化 0：无 1：有
        public String isChanged { get; set; }
        // 标题数量
        public String sortTile { get;  private set; }

        // 构造方法
        DataBean(User user, String salesDpt, String province, Map<String, Opportunity> oppMap, Integer iYear, String category,
                 Map<Id, OpportunityLineItem> oliMap, List<ImportantProductCategory__c> pcList2) {
            this.user = user;
            this.opportunity = new Opportunity();
            this.oppInput = 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];
            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;
                // 2018年7月10日 SWAG-AZHBH7 从Opportunity赋值到vf page上 by 张玉山
                /*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.user.Id + '_' + 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 (oliMap.get(oppMap.get(key).Id) != null) {
                            if (isCntMap.get(pc.importantProductGoaIName__c + '_' + pc.depName__c) == false) {
                                amountSum += oliMap.get(oppMap.get(key).Id).Objective__c == null ? 0 : oliMap.get(oppMap.get(key).Id).Objective__c;
                            } else {
                                amountSum += oliMap.get(oppMap.get(key).Id).NumberOfObjective__c == null ? 0 : oliMap.get(oppMap.get(key).Id).NumberOfObjective__c;
                            }
                        }
                    }
                }
                if (amountSum > 0) {
                    if (category == '重点产品目标(金额)') {
                        amountSum = amountSum.setScale(2);
                        a.Amount = amountSum;
                    } else {
                        amountSum = amountSum.round();
                        a.Num_Of_OPD__c = amountSum;
                    }
                }
                */
                this.oppInput.add(a);
                //xiongyl--end
            }
        }
    }

    // 職位チェックボックスリスト作成
    class Position {
        public String positionName { get; private set; }
        public Boolean check { get; set; }

        public Position(String positionName, Boolean flg) {
            this.positionName = positionName;
            this.check = flg;
        }
    }
}