public with sharing class SetProvinceTargetController {
    // 当前期
    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 SetProvinceTargetController() {
        //Apexpages.currentPage().getHeaders().put('X-UA-Compatible', 'IE=8');
    }

    // 本部プルダウン
    public List<SelectOption> getSalesDptOpts() {
        List<SelectOption> salesDpt = new List<SelectOption>();
        salesDpt.add(new SelectOption('0.无','--无--'));
        salesDpt.add(new SelectOption('1.华北','1.华北'));
        salesDpt.add(new SelectOption('2.东北','2.东北'));
        salesDpt.add(new SelectOption('3.西北','3.西北'));
        salesDpt.add(new SelectOption('4.华东','4.华东'));
        salesDpt.add(new SelectOption('5.华南','5.华南'));
        salesDpt.add(new SelectOption('6.西南','6.西南'));
        return salesDpt;
    }
    
    //  现在年度
    private Integer currentYear;
    //  当前年度
    private Integer iYear;

    private String target_category;  // 省目标
    public User loginUser { get; set; }          // 登陆用户
    private RecordType rt;           // 目标的数据类型
    private Map<String, List<Double>> proportion;    // 比重
    
    private Map<String,List<String>> salesDptMap;  //本部-省对应关系
    private Map<String,String> provinceMap;        //省-本部对应关系
    
    // 既存目标数据
    private Map<String, Opportunity> oppsMap;
    //2021/12/28 中间表寄存数据 by ld fy
    private Map<String,Provincial_Goal_Setting_Input__c> Provincial_Goal_Setting_InputMap;
    public Provincial_Goal_Setting_Input__c[] Existed_Provincial_Goal_Setting_Input;
    private List<Provincial_Goal_Setting_Input__c> upsertPGSIList;
    private Map<String, Provincial_Goal_Setting_Input__c> Provincial_Goal_Setting_InputMap1;
    private Map<String, OCM_Management_Province__c> OCM_MpMap;
    private List<String> AllOwnerSystem;
    private static String[] CIfromass = new String[] {'GI','ET','BF','GDP'};
    private static String[] SPfromass = new String[] {'GS','URO','GYN','ENT','ENG'};
    // 金额分类
    //private static String[] amountCategory = new String[] {'GI','ET','BF','GS','URO','GYN','ENT','OTH'};
    //省目标(SetProvinceTarget):隐藏OTH。追加ENG。
    private static String[] amountCategory = new String[] {'GI','ET','BF','GS','URO','GYN','ENT','ENG'};
    //SWAG-C9YDDE  2021/12/28 fy start
    // private static String[] amountCategory = new String[] {'GDP','GI','ET','BF','GS','URO','GYN','ENT','ENG'};
    //SWAG-C9YDDE  2021/12/28 fy end
    //CHAN-BDQBLX  20210129 you start
    public string csvAsString {get; set;}
    public String[] csvFileLines {get; set;}
    //fy 修改 start
    public String users6_ID = System.Label.s6_ID;
    public boolean JianDangfalg { get; set; }
    //fy 修改 end
    private static String[] titlepage = new String[] {'销售本部', '省','GI', 'ET', 'BF', 'GS', 'URO', 'GYN', 'ENT', 'ENG'};
    //SWAG-C9YDDE  2021/12/28 fy start
    // private static String[] titlepage = new String[] {'销售本部', '省', '担当','GDP','GI', 'ET', 'BF', 'GS', 'URO', 'GYN', 'ENT', 'ENG'};
    //SWAG-C9YDDE  2021/12/28 fy end
    public Integer detailCountLimit{get;private set;}
    private Map<String, Opportunity> oppsMap1;
    private List<Opportunity> upsertAMPList ;
    private List<Opportunity> deleteAMPList ;
    //CHAN-BDQBLX  20210129 you end
    // 画面初始化
    public Pagereference init() {
        JianDangfalg=false;
        //fy 修改 20220412
        System.debug('users6_ID:  '+users6_ID);
        System.debug('当前用户简档:  '+UserInfo.getProfileId());
        String userProfileId = UserInfo.getProfileId();
        if(!String.isBlank(userProfileId)){
            userProfileId=userProfileId.substring(0,15);
        }
        System.debug('当前用户简档截取:  '+userProfileId);
        List<String> user6IdList = users6_ID.split(',');
        for(String user6id : user6IdList){
            if(user6id==userProfileId){
            // if(user6id=='00e10000000xnpR'){
                JianDangfalg=true;
                break;
            }
        }
        System.debug('user6IdList:  '+user6IdList);
        System.debug('JianDangfalg:  '+JianDangfalg);
        if(JianDangfalg){
            amountCategory = new String[] {'GDP','GI','ET','BF','GS','URO','GYN','ENT','ENG'};
            titlepage = new String[] {'销售本部', '省','GDP','GI', 'ET', 'BF', 'GS', 'URO', 'GYN', 'ENT', 'ENG'};
        }
        System.debug('amountCategory===:  '+amountCategory);
        //fy 修改 20220412
        //CHAN-BDQBLX  20210129 you start
        oppsMap1 = new Map<String, Opportunity>();
        detailCountLimit = 10000;
        upsertAMPList = new List<Opportunity>();
        deleteAMPList = new List<Opportunity>();
        //CHAN-BDQBLX  20210129 you end
        //SWAG-C9YDDE  2021/12/28 fy start
        Provincial_Goal_Setting_InputMap1 = new Map<String, Provincial_Goal_Setting_Input__c>();
        upsertPGSIList = new List<Provincial_Goal_Setting_Input__c>();
        //SWAG-C9YDDE  2021/12/28 fy end
        // 现在时间
        Date dateNow = Date.today();
        Integer year = dateNow.year();
        Integer month = dateNow.month();
        if (month < 4) {
            year -= 1;
        }
        // 初始化
        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;
        // 金额分类
        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);
            proportion.put('_ENG', doubleENG);
        }
        // 当前用户信息
        if (loginUser == null) {
            loginUser = [Select Id, Salesdepartment__c, ProfileId From User where Id = :Userinfo.getUserId()];
        }
        
        getsalesDptMap();
        salesDpt = '0.无';
        
        // 所有本年度属于省目标的目标
        if (target_category == null) {
            target_category = '省目标';
        }
        // 目标的数据类型
        if (rt == null) {
            rt = [select Id from RecordType where SobjectType = 'Opportunity' and IsActive = true and DeveloperName = 'Target'];
        }
        // 数据赋值
        setBean(iYear);
        system.debug('dataBeans+++'+dataBeans[0]);
        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();
        }
        

        setBean(iYear);
    }
   //CHAN-BDQBLX  20210129 you start 导出方法
    public Pagereference exportBycsv() {
        setBean(iYear);

        system.debug('进来了');
        return page.SetProvinceTargetcsv;
    }
     //导入方法
    public PageReference importCSVFile() {
        try{
            if(JianDangfalg){
                titlepage = new String[] {'销售本部', '省','GDP','GI', 'ET', 'BF', 'GS', 'URO', 'GYN', 'ENT', 'ENG'};
            }
            String csvData = ApexPages.currentPage().getParameters().get('csvData');
            // 将内容转换成为中文
            if(!Test.isRunningTest()){
                //csvAsString = bitToString(csvFileBody, 'gb2312');
                csvAsString = csvData;
                system.debug('==csvAsString=='+csvAsString);
            }            
            // 拆成每一行
            csvFileLines = csvAsString.split('\n');
            system.debug(csvFileLines.size());
            Boolean ValFlag = false;
            String exportByVal = '';
            ApexPages.Message successMsg = new ApexPages.Message(ApexPages.severity.INFO, '');
            // 需要根据情况来解析,查看表头是否一致
            if (csvFileLines.size() > 0) {
                string[] titlecsv = csvFileLines[0].trim().split(',');//
                system.debug(titlecsv + '==titlepage==' + titlepage);
                if(titlepage.size()!=titlecsv.size()){
                    ValFlag = true;
                    exportByVal = '表头不一致，请严格按照导出模板填写';
                }else{
                    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>();//省份
                getOCMManagementProvince();
                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);
                        // fy 20220107
                        szMap.put(bu+'_'+ sf, csvRecordData);
                        sfs.add(sf);//把省份放进去 
                    }
                }
                if (null != sfs && sfs.size() > 0) {
                    // this.getOppprtunity_List(sfs);
                    this.getProvincial_Goal_Setting_Input(sfs);//根据省份年份，获取当前系统中已经存在得数据 放到map中
                }
                // List<User> userList  = new List<User>();
                // // System.debug('==UserInfoList=='+UserInfoList);
                // 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);
                // }
                //fy 修改 20220412
                Integer GDP_Number = 0;
                Integer GI_Number = 0;
                Integer ET_Number = 0;
                Integer BF_Number = 0;
                Integer GS_Number = 0;
                Integer URO_Number = 0;
                Integer GYN_Number = 0;
                Integer ENT_Number = 0;
                Integer ENG_Number = 0;
                if(JianDangfalg){
                    //2021/12/28 中间表寄存数据 by ld fy
                    GDP_Number = 2;
                    //2021/12/28 中间表寄存数据 by ld fy
                    GI_Number = 3;
                    ET_Number = 4;
                    BF_Number = 5;
                    GS_Number = 6;
                    URO_Number = 7;
                    GYN_Number = 8;
                    ENT_Number = 9;
                    ENG_Number = 10;
                }else{
                    GI_Number = 2;
                    ET_Number = 3;
                    BF_Number = 4;
                    GS_Number = 5;
                    URO_Number = 6;
                    GYN_Number = 7;
                    ENT_Number = 8;
                    ENG_Number = 9;
                }
                upsertPGSIList = new List<Provincial_Goal_Setting_Input__c>();//初始化，解决重复导入数据 id重复得问题
                for (String key : szMap.keySet()) {
                    //取用户的Id
                    // String userid = '';
                    OCM_Management_Province__c userid = new OCM_Management_Province__c();
                    String key_shengfen=key.split('_')[1];//省份
                    //GI助理
                    String GIassistant='';
                    //SP助理
                    String SPassistant='';
                    // String key_dandang= '';
                    // if(key.split('_').size()>=3){
                    //      key_dandang=key.split('_')[2];//把担当取出来
                    // }
                    if (OCM_MpMap.containskey(key_shengfen)) {
                        // userid = userMap.get(key_shengfen);
                        userid = OCM_MpMap.get(key_shengfen);
                        if(userid.GI_assistant__c!=null){
                            GIassistant=userid.GI_assistant__c;
                        }
                        if(userid.SP_assistant__c!=null){
                            SPassistant=userid.SP_assistant__c;
                        }
                    } else {
                        System.debug('==key==='+key);
                        //用户不存在要提醒
                        continue;
                    }
                    system.debug('==userid=='+userid+'\n');
                    List<String> csvRecordData = szMap.get(key);
                    //2021/12/28 中间表寄存数据 by ld fy
                    Provincial_Goal_Setting_Input__c upsertPGSI = new Provincial_Goal_Setting_Input__c();
                    //获取导入数量
                    //fy 修改 20220412
                    if(JianDangfalg){
                        Decimal GDP_Amount = String.isNotBlank(csvRecordData[GDP_Number]) ? Decimal.valueOf(csvRecordData[GDP_Number]) : 0.00;
                        DataSplicing(GDP_Amount,key_shengfen + '_GDP',Provincial_Goal_Setting_InputMap1,GIassistant,csvRecordData);
                    }
                    //fy 修改 20220412
                    Decimal GI_Amount = String.isNotBlank(csvRecordData[GI_Number]) ? Decimal.valueof(csvRecordData[GI_Number]) : 0.00;
                     
                    DataSplicing(GI_Amount,key_shengfen + '_GI',Provincial_Goal_Setting_InputMap1,GIassistant,csvRecordData);
                        
                    Decimal ET_Amount = String.isNotBlank(csvRecordData[ET_Number]) ? Decimal.valueOf(csvRecordData[ET_Number]) : 0.00;
                    DataSplicing(ET_Amount,key_shengfen + '_ET',Provincial_Goal_Setting_InputMap1,GIassistant,csvRecordData);
                        
                    Decimal BF_Amount = String.isNotBlank(csvRecordData[BF_Number]) ? Decimal.valueOf(csvRecordData[BF_Number]) : 0.00;
                    DataSplicing(BF_Amount,key_shengfen + '_BF',Provincial_Goal_Setting_InputMap1,GIassistant,csvRecordData);

                        
                    Decimal GS_Amount = String.isNotBlank(csvRecordData[GS_Number]) ? Decimal.valueOf(csvRecordData[GS_Number]) : 0.00;
                    DataSplicing(GS_Amount,key_shengfen + '_GS',Provincial_Goal_Setting_InputMap1,SPassistant,csvRecordData);
                       
                    Decimal URO_Amount = String.isNotBlank(csvRecordData[URO_Number]) ? Decimal.valueOf(csvRecordData[URO_Number]) : 0.00;
                    DataSplicing(URO_Amount,key_shengfen + '_URO',Provincial_Goal_Setting_InputMap1,SPassistant,csvRecordData);
                        
                    Decimal GYN_Amount = String.isNotBlank(csvRecordData[GYN_Number]) ? Decimal.valueOf(csvRecordData[GYN_Number]) : 0.00;
                    DataSplicing(GYN_Amount,key_shengfen + '_GYN',Provincial_Goal_Setting_InputMap1,SPassistant,csvRecordData);
                    system.debug('ENG_Number--->'+csvRecordData[ENG_Number]);
                    Decimal ENT_Amount = String.isNotBlank(csvRecordData[ENT_Number]) ? Decimal.valueOf(csvRecordData[ENT_Number]) : 0.00;
                    DataSplicing(ENT_Amount,key_shengfen + '_ENT',Provincial_Goal_Setting_InputMap1,SPassistant,csvRecordData);
                    system.debug('ENG_Number--->'+csvRecordData[ENG_Number]);
                    //因为最后一列数据有空格，所以加.trim()
                    Decimal ENG_Amount = String.isNotBlank(csvRecordData[ENG_Number]) ? Decimal.valueOf(csvRecordData[ENG_Number].trim()) : 0.00;
                    // Decimal.valueOf(String str)
                    DataSplicing(ENG_Amount,key_shengfen + '_ENG',Provincial_Goal_Setting_InputMap1,SPassistant,csvRecordData);
                    
                    //拼接Key
                }
                if(null!=upsertPGSIList && upsertPGSIList.size()>0){
                upsert upsertPGSIList;
                }
                // if(null!=upsertAMPList && upsertAMPList.size()>0){
                //     system.debug('upsertAMPList=='+upsertAMPList.size()+'=upsertAMPList=='+upsertAMPList+'\n');
                //     upsert upsertAMPList;
                // }
                // if(null!=deleteAMPList && deleteAMPList.size()>0){
                //     delete deleteAMPList;
                // }
                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.getLineNumber() + ':'+ e.getMessage());
            ApexPages.addMessage(errorMessage);
       }
    return null; 
}
    // 最终得数据处理，
    private void DataSplicing(Decimal amount, String key, Map<String, Provincial_Goal_Setting_Input__c> ampMap, String userid,List<String> csvRecordData) {//去进行最终数据得插入，更新或删除操作
        Provincial_Goal_Setting_Input__c upsertPGSI = new Provincial_Goal_Setting_Input__c();
        //system.debug('==amount=='+amount+'==key=='+key+'==ampMap=='+ampMap+'\n');   
            if (ampMap.containskey(key)) {
                upsertPGSI = ampMap.get(key);
                if (amount > 0) {
                    if(amount != upsertPGSI.Amount__c){
                        upsertPGSI.Amount__c = amount;
                        upsertPGSI.Owner_System__c = userId;
                        upsertPGSI.Is_Processing__c = true;
                        upsertPGSIList.add(upsertPGSI);
                    }
                } else {
                    //不用删除了，允许 数据是空的存在
                    upsertPGSI.Amount__c = null;
                    upsertPGSI.Is_Processing__c = true;
                    upsertPGSI.Owner_System__c = userId;
                    upsertPGSIList.add(upsertPGSI);
                }
            } else {
                if (amount > 0) {
                    upsertPGSI.Amount__c = amount;
                    upsertPGSI.key__c = key;
                    upsertPGSI.Owner_System__c = userId;
                    upsertPGSI.SAP_Province__c = csvRecordData[1];
                    upsertPGSI.Department__c = csvRecordData[0];
                    upsertPGSI.iYear__c = iYear;
                    upsertPGSI.Is_Processing__c = true;
                    upsertPGSI.Target_Source__c = 'SetProvinceTarget';
                    upsertPGSIList.add(upsertPGSI);
                } else {
                    //允许 数据是空的存在
                    upsertPGSI.Amount__c = null;
                    upsertPGSI.key__c = key;
                    upsertPGSI.Owner_System__c = userId;
                    upsertPGSI.SAP_Province__c = csvRecordData[1];
                    upsertPGSI.Department__c = csvRecordData[0];
                    upsertPGSI.iYear__c = iYear;
                    upsertPGSI.Is_Processing__c = true;
                    upsertPGSI.Target_Source__c = 'SetProvinceTarget';
                    upsertPGSIList.add(upsertPGSI);
                }
            }
    }
    private List<User> getUserList(List<String> UserInfoList) {//根据上传文件中得本部，省份，担当，职位 得到了user 信息
        String soql = 'select Id,Alias from User where IsActive = true'
                      + ' and Alias IN :UserInfoList order by Salesdepartment__c, Province__c';
        System.debug('==soql==' + soql);
        return Database.query(soql);
    }
     /*private void getOppprtunity_List(Set<String> sfs) {// 取得当前年度目标数据
        oppsMap1 = new Map<String, Opportunity>();
        Opportunity[] opportunitys = [select
                        Id, OwnerId, Opportunity_Category__c, Proportion__c, CloseDate,
                        Amount, Objective__c, Target_category__c,
                        SAP_Province__c, RecordTypeId, OCM_Target_period__c, Owner_System__c,Owner_System__r.Name
                 from Opportunity
                where Target_category__c = :target_category
                  and RecordTypeId = :rt.Id
                  and Target_Source__c = 'SetProvinceTarget'
                  //20210225 ljh WLIG-BV8CHF update  财年 start
                  //and OCM_Target_period__c = :currentPeriod
                  and OCM_Target_period__c = :currentPeriodOld
                  //20210225 ljh WLIG-BV8CHF update  财年 start
                  and SAP_Province__c in :sfs];
        for (Opportunity opp : opportunitys) {
            if (opp.OwnerId != null && opp.Opportunity_Category__c != null && opp.CloseDate !=null){
                //  目标 key : Province + _ + Opportunity_Category__c + _ + CloseDate(yyyy-mm-dd)
                String key = opp.SAP_Province__c + '_' + opp.Opportunity_Category__c + '_' + String.valueOf(opp.CloseDate);
                oppsMap1.put(key, opp);
            }
        }
    }*/
   //CHAN-BDQBLX  20210129 you end 
    // 点击保存按钮
    public Pagereference saveBtn() {
        this.saveLogic();
        setBean(iYear);
        
        ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.INFO, '保存成功。');
        ApexPages.addMessage(msg);
        return null;
    }
    
    // 点击返回按钮
    public Pagereference backBtn() {
        // HOMEに戻る
        PageReference ref = new Pagereference('/home/home.jsp');
        ref.setRedirect(true);
        return ref;
    }
    
    // 数据赋值
    private void setBean(Integer year) {
        if(JianDangfalg){
            amountCategory = new String[] {'GDP','GI','ET','BF','GS','URO','GYN','ENT','ENG'};
        }
        // 取得当前年度目标数据
        Opportunity[] opportunitys = [select
                        Id, OwnerId, Opportunity_Category__c, Proportion__c, CloseDate,
                        Amount, Objective__c, Target_category__c,
                        SAP_Province__c, RecordTypeId, OCM_Target_period__c, Owner_System__c,Owner_System__r.Name
                 from Opportunity
                where Target_category__c = :target_category
                  and RecordTypeId = :rt.Id
                  and Target_Source__c = 'SetProvinceTarget'
                  //20210225 ljh WLIG-BV8CHF update  财年 start
                  //and OCM_Target_period__c = :currentPeriod];
                  and OCM_Target_period__c = :currentPeriodOld];
                  //20210225 ljh WLIG-BV8CHF update  财年 start
        // 当前年度没有数据时，显示信息
        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.Opportunity_Category__c != null && opp.CloseDate !=null){
                //  目标 key : Province + _ + Opportunity_Category__c + _ + CloseDate(yyyy-mm-dd)
                String key = opp.SAP_Province__c + '_' + opp.Opportunity_Category__c + '_' + String.valueOf(opp.CloseDate);
                oppsMap.put(key, opp);
            }
        }
        getProvincial_Goal_Setting_InputMap();
        dataBeans = new List<DataBean>();
        List<String> provinces = salesDptMap.get(salesDpt);
        for (String pro : provinces) {
            DataBean dataBean = new DataBean(provinceMap.get(pro), pro, oppsMap, iYear);
            // 2020/12/28 与既有中间表数据进行对比 fy by ld start
            for (Integer j = 0; j < amountCategory.size(); j++) {
                String key = dataBean.Opportunity.SAP_Province__c + '_' + amountCategory[j];
                if (Provincial_Goal_Setting_InputMap.containsKey(key)){
                    Provincial_Goal_Setting_Input__c Provincial_Goal_Setting_Input = Provincial_Goal_Setting_InputMap.get(key);
                    dataBean.opportunity.Owner_System__c = Provincial_Goal_Setting_Input.Owner_System__c;
                    dataBean.amount[j].Amount = Provincial_Goal_Setting_Input.Amount__c;
                }
            }
            // 2020/12/28 与既有中间表数据进行对比 fy by ld end
            dataBeans.add(dataBean);
        }
        system.debug('dataBeans+++='+dataBeans);
    }
    
    //获取本部-省对应关系
    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('西藏自治区');
        AllOwnerSystem = provinceList;
        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('4.华东',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('西藏自治区');
        salesDptMap.put('6.西南',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('上海市','4.华东');
        provinceMap.put('江苏省','4.华东');
        provinceMap.put('浙江省','4.华东');
        provinceMap.put('福建省','4.华东');
        provinceMap.put('安徽省','4.华东');
        provinceMap.put('江西省','4.华东');
        
        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.西南');
    }
    
    // 是否删除整行数据
    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 sTargetDay = syear + '-' + smonth + '-01';
                Date targetDay = Date.valueOf(sTargetDay);
                // 按金额分类顺序处理
                for (Integer j = 0; j < amountCategory.size(); j++) {
                    String amountC = amountCategory[j];
                    // 数据检索Key
                    String key = db.opportunity.SAP_Province__c + '_' + amountC + '_' + sTargetDay;
                    if (oppsMap.containskey(key)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
    
    // 実際の保存ロジック
/*private void saveLogic() {
        List<Opportunity> saveList = new List<Opportunity>();
        List<Opportunity> deleteList = new List<Opportunity>();
        
        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 (Integer j = 0; j < amountCategory.size(); j++) {
                    String amountC = amountCategory[j];
                    // 数据检索Key
                    String key = db.opportunity.SAP_Province__c + '_' + amountC + '_' + sTargetDay;
                    // 每月数据赋值
                    Opportunity opp = new Opportunity();
                    if (oppsMap.containskey(key)) {
                        opp = oppsMap.get(key);
                        if (opp.Proportion__c != proportion.get(amountC)[i]) {
                            proportionChanged = true;
                            break;
                        }
                    }
                }
                if (proportionChanged) {
                    break;
                }
            }
            if (db.isChanged == '0' && !proportionChanged) {
                continue;
            }
            User u = new User();
            //Update 20160413 Start/
           if (db.opportunity.Owner_System__c == null) {
                if (isDelete(db) == false) {
                    continue;
                }
            }
            //Update 20160413 End/
            // 一年分成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 sTargetDay = syear + '-' + smonth + '-01';
                Date targetDay = Date.valueOf(sTargetDay);
                // 按金额分类顺序处理
                for (Integer j = 0; j < amountCategory.size(); j++) {
                    String amountC = amountCategory[j];
                    // 数据检索Key
                    String key = db.opportunity.SAP_Province__c + '_' + amountC + '_' + sTargetDay;
                    // 每月数据赋值
                    Opportunity opp = new Opportunity();
                    if (oppsMap.containskey(key)) {
                        opp = oppsMap.get(key);
                        //if (db.opportunity.Owner_System__c == null || db.amount[j].Amount == null || db.amount[j].Amount == 0) {
                        if (db.amount[j].Amount == null || db.amount[j].Amount == 0) {
                            deleteList.add(opp);
                            continue;
                        }
                    //Update 20160531 Start/
                       opp.OwnerId = db.opportunity.Owner_System__c;
                        opp.Owner_System__c = db.opportunity.Owner_System__c;
                    //Update 20160531 End/
                        opp.Proportion__c = proportion.get(amountC)[i];
                        opp.Amount = db.amount[j].Amount;
                    } else {
                        if (db.amount[j].Amount == null || db.amount[j].Amount == 0) {
                            continue;
                        }
                        opp.Name = db.opportunity.SAP_Province__c + ' 省目标';
                        opp.StageName = '目標';
                    //Update 20160531 Start/
                        opp.OwnerId = db.opportunity.Owner_System__c;
                        //トリガをスルーのため、ここでやります
                        opp.Owner_System__c = db.opportunity.Owner_System__c;
                    //Update 20160531 End/
                        opp.Opportunity_Category__c = amountC;
                        opp.Proportion__c = proportion.get(amountC)[i];
                        opp.CloseDate = targetDay;
                        opp.Amount = db.amount[j].Amount;
                        opp.Target_category__c = target_category;
                        opp.SAP_Province__c = db.opportunity.SAP_Province__c;
                        opp.RecordTypeId = rt.Id;
                        opp.Target_Source__c = 'SetProvinceTarget';
                        //20210225 ljh WLIG-BV8CHF update  财年 start
                        //opp.OCM_Target_period__c = currentPeriod;
                        opp.OCM_Target_period__c = currentPeriodOld;
                       //20210225 ljh WLIG-BV8CHF update  财年 end
                    }
                    // 加入保存列表
                    saveList.add(opp);
                }
            }
            // 数据库限制小于10000条
            if (saveList.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.EscapeNFM007Trigger = true;

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

    //反映到目标 fy 2021/12/28 SWAG-C9YDDE 
    //查询OCSM管理省 fy
    private void getOCMManagementProvince(){
        OCM_MpMap = new Map<String, OCM_Management_Province__c>();
        List<OCM_Management_Province__c> OCM_MpList = [select Id,Province__c,GI_assistant__c,SP_assistant__c,Name from OCM_Management_Province__c where Province__c in :AllOwnerSystem ];
        for ( OCM_Management_Province__c OCM_Mp : OCM_MpList ) {
            //过滤掉不符合条件的数据 fy
            if(OCM_Mp.Name!='集采课'&&OCM_Mp.Name!='青岛'){
                OCM_MpMap.put(OCM_Mp.Province__c, OCM_Mp);
            }
        }
    }
    public Pagereference UpdateBtn() {
        system.debug('=====UpdateBtn-1');
        boolean rs = saveLogic();
        setBean(iYear);
        system.debug('rs+++'+rs);
        Database.executeBatch(new SetProvinceTargetBatch(), 10);
        if (rs) {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, '反映到目标成功'));
        }
        return null;
    }
    private void getProvincial_Goal_Setting_Input(Set<String> sfs) {//根据省份年份，获取当前系统中已经存在得数据
        Provincial_Goal_Setting_InputMap1 = new Map<String, Provincial_Goal_Setting_Input__c>();

        list<Provincial_Goal_Setting_Input__c> Existed_Provincial_Goal_Setting_Input = [select id,Is_Processing__c, key__c,Target_Source__c,Amount__c,Department__c,SAP_Province__c,Owner_System__c,iYear__c
                                                                                FROM Provincial_Goal_Setting_Input__c where iYear__c = : iYear and SAP_Province__c in :sfs];
    
        for ( Provincial_Goal_Setting_Input__c Provincial_Goal_Setting_Input : Existed_Provincial_Goal_Setting_Input ) {
            if (String.isBlank(Provincial_Goal_Setting_Input.key__c)) {
                continue;
            }

            Provincial_Goal_Setting_InputMap1.put(Provincial_Goal_Setting_Input.key__c, Provincial_Goal_Setting_Input);

        }
    }
    // 2021/12/28 从中间表获取既有数据 fy
    private boolean getProvincial_Goal_Setting_InputMap() {
        Provincial_Goal_Setting_InputMap = new Map<String,Provincial_Goal_Setting_Input__c>();

        Existed_Provincial_Goal_Setting_Input = [select id,Is_Processing__c, key__c,Target_Source__c,Amount__c,Department__c,SAP_Province__c,Owner_System__c,iYear__c
                                                                FROM Provincial_Goal_Setting_Input__c where iYear__c = : iYear ];
        
        if (Existed_Provincial_Goal_Setting_Input.size() <= 0) {
            return false;
        }

        // 将所数据存入map中
        for ( Provincial_Goal_Setting_Input__c Provincial_Goal_Setting_Input : Existed_Provincial_Goal_Setting_Input ){
            if (String.isBlank(Provincial_Goal_Setting_Input.key__c)) {
                continue;
            }
            Provincial_Goal_Setting_InputMap.put(Provincial_Goal_Setting_Input.key__c,Provincial_Goal_Setting_Input);
        }

        return true;
    }
    //保存逻辑 fy 2021/12/28 SWAG-C9YDDE 
    private Boolean saveLogic() {
        List<Opportunity> saveList = new List<Opportunity>();
        List<Opportunity> deleteList = new List<Opportunity>();
        //fy 修改 20220412
        if(JianDangfalg){
            amountCategory = new String[] {'GDP','GI','ET','BF','GS','URO','GYN','ENT','ENG'};
        }
        //fy 修改 20220412
        Savepoint sp = Database.setSavepoint();
        try {
            List<Provincial_Goal_Setting_Input__c> InsertProvincial_Goal_Setting_Input = new list<Provincial_Goal_Setting_Input__c>();
            List<Provincial_Goal_Setting_Input__c> UpdateProvincial_Goal_Setting_Input = new list<Provincial_Goal_Setting_Input__c>();
            // 只处理当前本部数据
            //查询OCSM管理省 fy
            getOCMManagementProvince();
            system.debug('OCM_MpList+++'+OCM_MpMap);
            for (Integer d = 0; d < dataBeans.size(); d++){
                DataBean db = dataBeans[d];
                system.debug('db+++++++ ' + db);
                system.debug('amountCategory+++++++ ' + amountCategory);
                system.debug('Provincial_Goal_Setting_InputMap+++++++ ' + Provincial_Goal_Setting_InputMap);
                // if(String.isBlank(db.Opportunity.Owner_System__c))continue;
                for (Integer j = 0; j < amountCategory.size(); j++) {
                    // 数据检索Key
                    String key = db.Opportunity.SAP_Province__c + '_' + amountCategory[j];
                    system.debug('++++++++1+++++++ '+Provincial_Goal_Setting_InputMap.containsKey(key));
                    if(Provincial_Goal_Setting_InputMap.containsKey(key)) {
                        system.debug('++++++++2+++++++ ');
                        //临时表已经有了
                        Provincial_Goal_Setting_Input__c Provincial_Goal_Setting_Input = Provincial_Goal_Setting_InputMap.get(key);
                        if(Provincial_Goal_Setting_Input.Amount__c == db.amount[j].Amount) {
                            continue;
                        }else {
                            system.debug('++++++++5+++++++ '+OCM_MpMap.get('山东省'));
                            // system.debug('++++++++x+++++++ '+db.Opportunity.SAP_Province__c);
                            Provincial_Goal_Setting_Input.Amount__c = db.amount[j].Amount;
                            Provincial_Goal_Setting_Input.Department__c = db.department;
                            Provincial_Goal_Setting_Input.SAP_Province__c = db.Opportunity.SAP_Province__c;
                            String OWS='';
                            if(OCM_MpMap.containsKey(db.Opportunity.SAP_Province__c)){
                                if(CIfromass.contains(amountCategory[j])){
                                    OWS=OCM_MpMap.get(db.Opportunity.SAP_Province__c).GI_assistant__c;
                                }else if(SPfromass.contains(amountCategory[j])){
                                    OWS=OCM_MpMap.get(db.Opportunity.SAP_Province__c).SP_assistant__c;
                                }
                            }else{
                                continue;
                            }
                            Provincial_Goal_Setting_Input.Owner_System__c = OWS;
                            Provincial_Goal_Setting_Input.iYear__c = iYear;
                            Provincial_Goal_Setting_Input.Is_Processing__c = true;
                            Provincial_Goal_Setting_Input.Target_Source__c = 'SetProvinceTarget';
                            UpdateProvincial_Goal_Setting_Input.add(Provincial_Goal_Setting_Input);
                        }
                    }else {
                        system.debug('++++++++3+++++++ '+db.amount[j]);
                        system.debug('++++++++4+++++++ '+db.amount[j].Amount);
                        if (db.amount[j].Amount == null || db.amount[j].Amount == 0) {
                            continue;
                        }
                        Provincial_Goal_Setting_Input__c Provincial_Goal_Setting_Input = new Provincial_Goal_Setting_Input__c();
                        Provincial_Goal_Setting_Input.key__c = key;
                        Provincial_Goal_Setting_Input.Amount__c = db.amount[j].Amount;
                        Provincial_Goal_Setting_Input.Department__c = db.department;
                        Provincial_Goal_Setting_Input.SAP_Province__c = db.Opportunity.SAP_Province__c;
                        String OWS='';
                        if(OCM_MpMap.containsKey(db.Opportunity.SAP_Province__c)){
                            if(CIfromass.contains(amountCategory[j])){
                                OWS=OCM_MpMap.get(db.Opportunity.SAP_Province__c).GI_assistant__c;
                            }else if(SPfromass.contains(amountCategory[j])){
                                OWS=OCM_MpMap.get(db.Opportunity.SAP_Province__c).SP_assistant__c;
                            }
                        }else{
                            continue;
                        }
                        system.debug('++++++++9+++++++ '+OCM_MpMap.get(db.Opportunity.SAP_Province__c));
                        Provincial_Goal_Setting_Input.Owner_System__c = OWS;
                        Provincial_Goal_Setting_Input.iYear__c = iYear;
                        Provincial_Goal_Setting_Input.Is_Processing__c = true;
                        Provincial_Goal_Setting_Input.Target_Source__c = 'SetProvinceTarget';
                        InsertProvincial_Goal_Setting_Input.add(Provincial_Goal_Setting_Input);
                        system.debug('db.amount[j].Amount__c+++++++ ' + db.amount[j].Amount__c);
                    }
                }
            }
            system.debug('InsertProvincial_Goal_Setting_Input+++++++ ' + InsertProvincial_Goal_Setting_Input);
            if(InsertProvincial_Goal_Setting_Input.size() > 0) {
                insert InsertProvincial_Goal_Setting_Input;
            }
            if(UpdateProvincial_Goal_Setting_Input.size() > 0) {
                update UpdateProvincial_Goal_Setting_Input;
            }
            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;
        }
    }
    // 数据类
    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  20210129 you start  导出用name
        public String ownername { get; private set; }
        //CHAN-BDQBLX  20210129 you end 
        // 构造方法
        DataBean(String salesDpt, String province, Map<String, Opportunity> oppMap, Integer iYear) {
            boolean JianDangfalg = false;
            this.opportunity = new Opportunity();
            this.amount = new List<Opportunity>();
            this.opportunity.SAP_Province__c = province;
            this.department = salesDpt;
            this.isChanged = '0';
            //fy 20220418
            String userProfileId = UserInfo.getProfileId();
            if(!String.isBlank(userProfileId)){
                userProfileId=userProfileId.substring(0,15);
            }
            System.debug('当前用户简档截取:  '+userProfileId);
            List<String> user6IdList = System.Label.s6_ID.split(',');
            for(String user6id : user6IdList){
                if(user6id==userProfileId){
                // if(user6id=='00e10000000xnpR'){
                    JianDangfalg=true;
                    break;
                }
            }
            if(JianDangfalg){
                amountCategory = new String[] {'GDP','GI','ET','BF','GS','URO','GYN','ENT','ENG'};
            }
            //fy 20220418
            // 按金额分类，查找数据，并设值
            for (Integer i = 0; i < amountCategory.size(); i++) {
                String amountC = amountCategory[i];
                Opportunity a = new Opportunity();
                a.Opportunity_Category__c = amountC;
                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 + '_' + amountC + '_' + strY + '-' + strM + '-01';
                    if (oppMap.containskey(key)) {
/*************************Update 20160531 Start*************************/
                        if (oppMap.get(key).Owner_System__c != null) {
                            this.opportunity.Owner_System__c = oppMap.get(key).Owner_System__c;
                        }
                        //CHAN-BDQBLX  20210129 you start 
                        this.ownername = oppMap.get(key).Owner_System__r.Name;
                        //CHAN-BDQBLX  20210129 you end 
                        a.Amount = oppMap.get(key).Amount;
/*************************Update 20160531 End***************************/
                        amountSum += oppMap.get(key).Objective__c == null ? 0 : oppMap.get(key).Objective__c;
                    }
                }
                if (amountSum > 0) {
                    amountSum = amountSum.setScale(2);
                    a.Amount = amountSum;
                }
                this.amount.add(a);
            }
        }
    }
}