/**
 * @param province 省（複数）
 * @param text 項目
 * @param cond 条件
 * @param val  値
 * @param tab  選択したtab名
 * @param ocm 0 | null(1)
 */
global without sharing class ProvinceEvaluationController {
    public Daily_Report__c dummyDr { get; set; }
    // カスタム設定
    public static Map<Integer, Personal_Evaluation__c> peSettingsMap { get; private set; }
    static {
        peSettingsMap = new Map<Integer, Personal_Evaluation__c> ();
        List<Personal_Evaluation__c> peList = Personal_Evaluation__c.getall().values();
        for(Personal_Evaluation__c pe : peList){
            if (pe.IsProvince__c == false) continue;
            if (pe.IsActive__c == false) {
                if (pe.Tab_Index__c == 50) peSettingsMap.put(Integer.valueOf(pe.Tab_Index__c), pe);
                else continue;
            }
            peSettingsMap.put(Integer.valueOf(pe.Tab_Index__c), pe);
        }
    }
    
    // TabJS から カスタム設定を呼び出すときつかう
    @RemoteAction
    global static Map<String, Object> getPeSettings(String tabName) {
        Map<String, Object> rtn = new Map<String, Object>();
        String rtnStr = null;
        List<Personal_Evaluation__c> peList = Personal_Evaluation__c.getall().values();
        for(Personal_Evaluation__c pe : peList) {
            if (pe.IsProvince__c == false) continue;
            if (pe.Api_Name__c == tabName) {
                rtnStr = JSON.serialize(pe);
            }
        }
        if (String.isBlank(rtnStr) == false) {
            rtn = (Map<String, Object>) JSON.deserializeUntyped(rtnStr);
        }
//            // SMARMデータを検索
//            String fromUserId = UserInfo.getUserId();
//            if (toUserId == 'Nothing') toUserId = null;
//            
//            Schema.DescribeSobjectResult s = SMARM__c.sObjectType.getDescribe();
//            Map<String, Schema.SObjectField> fieldMap = s.fields.getMap();
//            List<SMARM__c> sList = ControllerUtil.getSmarmByUser(fieldMap, fromUserId, toUserId);
//            
//            if (sList.size() > 0) {
//                Integer clipCnt = 0;
//                Set<Object> reportNameSet = new Set<Object>();
//                for (Integer i = 1; i <= Integer.valueOf(System.Label.SmarmClipNum); i++) {
//                    String reportNameApi = 'ReportName' + i + '__c';
//                    if (fieldMap.get(reportNameApi) != null && sList[0].get(reportNameApi) != null) {
//                        clipCnt++;
//                        reportNameSet.add(sList[0].get(reportNameApi));
//                    }
//                }
//                // Clipした総件数を入れる
//                rtn.put('ClipCnt', clipCnt);
//                rtn.put('SmarmId', sList[0].Id);
//                // PeSettingマップのReportNameがreportNameSetに存在するか
//                for (String key : rtn.keySet()) {
//                    // 念のため、Reportx_x_Name__cの項目だけを見る
//                    if (key.startsWith('Report') && key.endsWith('Name__c')) {
//                        if (reportNameSet.contains(rtn.get(key))) {
//                            String clipKey = key.replace('Name__c', 'SmarmClip');
//                            rtn.put(clipKey, 1);
//                        }
//                    }
//                }
//            }
//        }
        return rtn;
    }

    public static Map<Integer, String> peSettingsMapHasIdx { get; private set; }
    static {
        peSettingsMapHasIdx = new Map<Integer, String>();
        for(Integer i = 1; i < 99; i++) {
            peSettingsMapHasIdx.put(i, 'false');
            if (peSettingsMap.get(i) != null) {
                peSettingsMapHasIdx.put(i, 'true');
            }
        }
    }
    public static String getPersonalEvaluationSettingJson() {
        return JSON.serialize(peSettingsMap);
    }
    public String selectedTab { get; set; }     // Tabのページ専用、initにて値をセット
    public Integer tabIdx { get; set; }         // InTabのページ専用、init2にて値をセット
    public Static Integer getFirstTabIdx() {
        for(Integer i = 1; i < 99; i++) {
            if (peSettingsMap.get(i) != null) {
                return i;
            }
        }
        return 0;
    }
    
    // 省、ユーザの省(在开发报表可以选择)を見る、JSON？
    public String getProvince() {
        Boolean first = true;
        String aaa = '\'';
        String rtn = '';
        for ( SelectOption so : provinceSelectedOpts ) {
            if (first) {
System.debug('first getValue=' + so.getValue());
                rtn = aaa + so.getValue() + aaa;
                first = false;
System.debug('first rtn=' + rtn);
            } else {
System.debug('getValue=' + so.getValue());
                rtn += ',' + aaa + so.getValue() + aaa;
System.debug('rtn=' + rtn);
            }
        }
        return rtn;
    }
    private Set<String> provinceSelectable;
    public List<SelectOption> provinceOpts  { get; set; }
    public Integer getProvinceOptsSize() {
        return provinceOpts.size();
    }
    public List<SelectOption> provinceSelectedOpts  { get; set; }
    public String[] provinceSelected { get; set; }
    
    // 検索条件
    /*
    public static List<SelectOption> textOpts { get; private set; }
    static {
        textOpts = new List<SelectOption>();
        textOpts.add(new SelectOption('','-无-'));
        textOpts.add(new SelectOption('S:Post__c', Schema.SObjectType.User.fields.Post__c.label));
        textOpts.add(new SelectOption('S:Job_Category__c', Schema.SObjectType.User.fields.Job_Category__c.label));
    }
    public static List<SelectOption> equalOpts { get; private set; }
    static {
        equalOpts = new List<SelectOption>();
        equalOpts.add(new SelectOption('equals','等于'));
        equalOpts.add(new SelectOption('notequals','不等于'));
        equalOpts.add(new SelectOption('contains','包含'));
        equalOpts.add(new SelectOption('notcontains','不包含'));
    }
    public String text1 { get; set; }
    public String cond1 { get; set; }
    public String val1 { get; set; }
    */
    
    // 登陆用户、検索条件に兼用
    public User loginUser { get; set; }
    
    // コメントして、Taskに残す
    @RemoteAction
    global static PersonalEvaluation__c saveComment(String userId, String recordTypeId, String subject, String comment, String base64Img, String tabName, String rptName, String rptNum, String province) {
        // Tab Api NameからTab Nameを取得
        // タブ：subject = tabName、レポート：subject = rptName、よって
        String subjectMoji = subject;
        for (Personal_Evaluation__c pe : Personal_Evaluation__c.getall().values()) {
            if (pe.Api_Name__c == subject) {
                subjectMoji = pe.Name;
                break;
            }
        }
        Task tsk = new Task(
            OwnerId = userId,
            Subject = subjectMoji,
            Description = comment,
            ActivityDate = System.today()
        );
        province = province.replace('\'', '');
        province = province.replace('"', '');
        province = province.replace(',', ';');
        
        PersonalEvaluation__c pec = null;
        if (String.isBlank(tabName)) {
            insert tsk;
            /*
            Document doc = new Document();
            // DeveloperNameをrandomに
            if (String.isBlank(base64Img) == false) {
                doc.Name = subjectMoji;
                doc.DeveloperName = 'pe_' + ControllerUtil.generateRandomStr(18);
                doc.Type = 'png';
                doc.Body = EncodingUtil.base64Decode(base64Img.removeStart('data:image/png;base64,'));
                ControllerUtil.createDocForEmail(new Document[]{doc});
            }
            */
            pec = new PersonalEvaluation__c(
                OwnerId = userId,
                RecordTypeId = recordTypeId,
                ReportName__c = subjectMoji,
                Comment__c = comment,
                Task_ID__c = tsk.Id,
                Graph1__c = String.isBlank(base64Img) ? null : '<img src=\"' + base64Img + '\"></img>',
                Province__c = province
            );
            
            insert pec;
            pec.ReportUrlText__c = '/apex/PersonalEvaluationReport?pecId=' + pec.Id;
            update pec;
            
            // 以前のロジックを保留
            if (String.isBlank(base64Img)) {
                tsk.ReportUrlText__c = pec.ReportUrlText__c;
            }
            // 新ロジック
            else {
                tsk.ReportUrlText__c = '/apex/PersonalEvaluationCommentImg?id=' + pec.Id;
            }
            tsk.PersonalEvaluation_ID__c = pec.Id;
        } else {
            //tsk.ReportUrlText__c = '/apex/PersonalEvaluation?user=' + userId + '&tab=' + tabName;
            insert tsk;
            /*
            Document doc = new Document();
            if (String.isBlank(base64Img) == false) {
                doc.Name = subjectMoji;
                doc.DeveloperName = 'pe_' + ControllerUtil.generateRandomStr(18);
                doc.Type = 'png';
                doc.Body = EncodingUtil.base64Decode(base64Img.removeStart('data:image/png;base64,'));
                ControllerUtil.createDocForEmail(new Document[]{doc});
            }
            */
            pec = new PersonalEvaluation__c(
                OwnerId = userId,
                RecordTypeId = recordTypeId,
                TabName__c = subjectMoji,
                Comment__c = comment,
                Task_ID__c = tsk.Id,
                Graph1__c = String.isBlank(base64Img) ? null : '<img src=\"' + base64Img + '\"></img>',
                Province__c = province,
                ReportUrlText__c = tsk.ReportUrlText__c
            );
            insert pec;
            // 以前のロジックを保留
            if (String.isBlank(base64Img)) {
                tsk.ReportUrlText__c = '/apex/PersonalEvaluation?user=' + userId + '&tab=' + tabName;
            }
            // 新ロジック
            else {
                tsk.ReportUrlText__c = '/apex/PersonalEvaluationCommentImg?id=' + pec.Id;
            }
            tsk.PersonalEvaluation_ID__c = pec.Id;
        }
//        if (String.isBlank(base64Img) == false) {
//            Attachment attach = new Attachment(
//                contentType = 'image/png',
//                name = comment,
//                parentId = tsk.Id,
//                body = EncodingUtil.base64Decode(base64Img)
//            );
//            insert attach;
//        }
        update tsk;
        
        return pec;
    }
    
    // 20150729 xudan 個人評価の送信ロジック
    // saveCommentの時点で、画像はまだSFDCに保存されなかったから、メールに添付できません
    @RemoteAction
    global static void sendPeEmail(String pecId) {
        PersonalEvaluation__c pe = new PersonalEvaluation__c(
            Id = pecId,
            SendEmail__c = true
        );
        update pe;
    }
    
    // MB のグラグを作成用
    @ReadOnly
    @RemoteAction
    global static String getJsonSAP(String dcName, String Province,String current_fiscalyear) {
        List<String> Plist = Province.split(',');
        Personal_Evaluation__c pes = peSettingsMap.get(50);
        String sql_6_1 = pes.Report6_1_Sql__c;
        String sql_6_2 = pes.Report6_2_Sql__c;
        String sql_6_3 = pes.Report6_3_Sql__c;
        if (String.isBlank(dcName) == false) {
            sql_6_1 += ' and Opportunity_Category__c=:dcName';
            sql_6_2 += ' and GBIC__c=:dcName';
            sql_6_3 += ' and GBIC__c=:dcName';
        }
        List<AggregateResult> MB_Target = Database.query(sql_6_1 + (pes.Report6_1_Sql1__c == null ? '' : ' ' + pes.Report6_1_Sql1__c) + (pes.Report6_1_Sql2__c == null ? '' : ' ' + pes.Report6_1_Sql2__c));
        Map<String, Map<String, Double>> rtn = new Map<String, Map<String, Double>>();
        Map<String, Double> rtnTargetWt = new Map<String, Double>();
        Map<String, Double> rtnTargetNum = new Map<String, Double>();
        for(AggregateResult ar : MB_Target) {
            rtnTargetWt.put(String.valueOf(ar.get('GBIC')), ar.get('wt') == null ? 0 : Decimal.valueOf(String.valueOf(ar.get('wt'))));
            rtnTargetNum.put(String.valueOf(ar.get('GBIC')), ar.get('num') == null ? 0 : Decimal.valueOf(String.valueOf(ar.get('num'))));
        }
        List<AggregateResult> MB_Ship = Database.query(sql_6_2 + (pes.Report6_2_Sql1__c == null ? '' : ' ' + pes.Report6_2_Sql1__c) + (pes.Report6_2_Sql2__c == null ? '' : ' ' + pes.Report6_2_Sql2__c));
        Map<String, Double> rtnShipWt = new Map<String, Double>();
        Map<String, Double> rtnShipNum = new Map<String, Double>();
        for(AggregateResult ar : MB_Ship) {
            rtnShipWt.put(String.valueOf(ar.get('GBIC')), ar.get('wt') == null ? 0 : Decimal.valueOf(String.valueOf(ar.get('wt'))));
            rtnShipNum.put(String.valueOf(ar.get('GBIC')), ar.get('num') == null ? 0 : Decimal.valueOf(String.valueOf(ar.get('num'))));
        }
        List<AggregateResult> MB_BackOrder = Database.query(sql_6_3 + (pes.Report6_3_Sql1__c == null ? '' : ' ' + pes.Report6_3_Sql1__c) + (pes.Report6_3_Sql2__c == null ? '' : ' ' + pes.Report6_3_Sql2__c));
        Map<String, Double> rtnBackOrderWt = new Map<String, Double>();
        Map<String, Double> rtnBackOrderNum = new Map<String, Double>();
        for(AggregateResult ar : MB_BackOrder) {
            rtnBackOrderWt.put(String.valueOf(ar.get('GBIC')), ar.get('wt') == null ? 0 : Decimal.valueOf(String.valueOf(ar.get('wt'))));
            rtnBackOrderNum.put(String.valueOf(ar.get('GBIC')), ar.get('num') == null ? 0 : Decimal.valueOf(String.valueOf(ar.get('num'))));
        }
        rtn.put('Target_wt', rtnTargetWt);
        rtn.put('Ship_wt', rtnShipWt);
        rtn.put('BackOrder_wt', rtnBackOrderWt);
        rtn.put('Target_num', rtnTargetNum);
        rtn.put('Ship_num', rtnShipNum);
        rtn.put('BackOrder_num', rtnBackOrderNum);
        return JSON.serialize(rtn);
    }

    // MB注残(JsonMB_BackOrder) 订单数/未付款数/无用户合同书
    @ReadOnly
    @RemoteAction
    global static String getJsonMBSA(String dcName, String Province) {
        List<String> Plist = Province.split(',');
        Personal_Evaluation__c pes = peSettingsMap.get(50);
        String sql_7_1 = pes.Report7_1_Sql__c;
        if (String.isBlank(dcName) == false) {
            sql_7_1 += ' and Opportunity_Category__c=:dcName';
        }
        Map<String, Double> rtn = new Map<String, Double>();
        List<AggregateResult> MB_SA = Database.query(sql_7_1 + (pes.Report7_1_Sql1__c == null ? '' : ' ' + pes.Report7_1_Sql1__c) + (pes.Report7_1_Sql2__c == null ? '' : ' ' + pes.Report7_1_Sql2__c));
        rtn.put('Order', MB_SA[0].get('Order') == null ? 0 : Decimal.valueOf(String.valueOf(MB_SA[0].get('Order'))));
        rtn.put('NClct', MB_SA[0].get('NClct') == null ? 0 : Decimal.valueOf(String.valueOf(MB_SA[0].get('NClct'))));
        rtn.put('NCtrc', MB_SA[0].get('NCtrc') == null ? 0 : Decimal.valueOf(String.valueOf(MB_SA[0].get('NCtrc'))));
        return JSON.serialize(rtn);
    }

    // MB询价 引合のステージ単位での件数 
    @ReadOnly
    @RemoteAction
    global static String getJsonForcast(String dcName, String Province) {
        List<String> Plist = Province.split(',');
        Personal_Evaluation__c pes = peSettingsMap.get(50);
        String sql_7_3 = pes.Report7_3_Sql__c;
        if (String.isBlank(dcName) == false) {
            sql_7_3 += ' and Opportunity_Category__c=:dcName';
        }
        Map<String, Integer> rtn = new Map<String, Integer>();
        Date forcastDay;
        Date maxForcastDay;
        forcastDay = System.today();
        maxForcastDay = forcastDay.addMonths(6);    // TODO 年度末 ?
        maxForcastDay = Date.newInstance(maxForcastDay.year(), maxForcastDay.month(), 1);
        maxForcastDay = maxForcastDay.addDays(-1);
        List<Opportunity> mbList = Database.query(sql_7_3 + (pes.Report7_3_Sql1__c == null ? '' : ' ' + pes.Report7_3_Sql1__c) + (pes.Report7_3_Sql2__c == null ? '' : ' ' + pes.Report7_3_Sql2__c));
        if (mbList.size() > 0) {
//            forcastDay = mbList[0].Sales_forecast_day_BA__c;
//            forcastDay = Date.newInstance(forcastDay.year(), forcastDay.month(), 1);
//            maxForcastDay = mbList[mbList.size() - 1].Sales_forecast_day_BA__c;
//            maxForcastDay = Date.newInstance(maxForcastDay.year(), maxForcastDay.month(), 1);
            for (Opportunity mb : mbList) {
                Integer cnt = rtn.get(mb.Sales_forecast_YM_BA__c);
                if (cnt == null) {
                    cnt = 0;
                }
                cnt++;
                rtn.put(mb.Sales_forecast_YM_BA__c, cnt);
            }
        }
        // Listに変換
        List<Map<String, Integer>> rtnList = new List<Map<String, Integer>>();      // Map<String, Integer> には１つペアしかない
        while (forcastDay <= maxForcastDay) {
            String yyyymm = '' + forcastDay.year() * 100 + forcastDay.month();
            String ymKey = yyyymm.mid(2, 2) + '年' + yyyymm.right(2) + '月';
            Integer cnt = rtn.get(ymKey);
            if (cnt == null) {
                cnt = 0;
            }
            rtnList.add(new Map<String, Integer>{ymKey => cnt});
            forcastDay = forcastDay.addMonths(1);
        }
        return JSON.serialize(rtnList);
    }

    // MB のグラグを作成用
    @ReadOnly
    @RemoteAction
    global static String getJsonOppSum(String dcName, String Province) {
        List<String> Plist = Province.split(',');
        // MB データの取得
        Personal_Evaluation__c pes = peSettingsMap.get(50);
        String sql_8_1 = pes.Report8_1_Sql__c;
        String sql_8_2 = pes.Report8_2_Sql__c;
        String sql_8_3 = pes.Report8_3_Sql__c;
        if (String.isBlank(dcName) == false) {
            sql_8_1 += ' and Opportunity_Category__c=:dcName';
            sql_8_2 += ' and Opportunity_Category__c=:dcName';
            sql_8_3 += ' and Opportunity_Category__c=:dcName';
        }
        List<AggregateResult> MB_Opp_Bid = Database.query(sql_8_1 + (pes.Report8_1_Sql1__c == null ? '' : ' ' + pes.Report8_1_Sql1__c) + (pes.Report8_1_Sql2__c == null ? '' : ' ' + pes.Report8_1_Sql2__c));
        List<AggregateResult> MB_Opp_Auth = Database.query(sql_8_2 + (pes.Report8_2_Sql1__c == null ? '' : ' ' + pes.Report8_2_Sql1__c) + (pes.Report8_2_Sql2__c == null ? '' : ' ' + pes.Report8_2_Sql2__c));
        List<AggregateResult> MB_Opp_A = Database.query(sql_8_3 + (pes.Report8_3_Sql1__c == null ? '' : ' ' + pes.Report8_3_Sql1__c) + (pes.Report8_3_Sql2__c == null ? '' : ' ' + pes.Report8_3_Sql2__c) + ' and Competitor__c = \'A\'');
        List<AggregateResult> MB_Opp_B = Database.query(sql_8_3 + (pes.Report8_3_Sql1__c == null ? '' : ' ' + pes.Report8_3_Sql1__c) + (pes.Report8_3_Sql2__c == null ? '' : ' ' + pes.Report8_3_Sql2__c) + ' and Competitor__c = \'B\'');
        List<AggregateResult> MB_Opp_C = Database.query(sql_8_3 + (pes.Report8_3_Sql1__c == null ? '' : ' ' + pes.Report8_3_Sql1__c) + (pes.Report8_3_Sql2__c == null ? '' : ' ' + pes.Report8_3_Sql2__c) + ' and Competitor__c = \'C\'');
        List<AggregateResult> MB_Opp_D = Database.query(sql_8_3 + (pes.Report8_3_Sql1__c == null ? '' : ' ' + pes.Report8_3_Sql1__c) + (pes.Report8_3_Sql2__c == null ? '' : ' ' + pes.Report8_3_Sql2__c) + ' and Competitor__c = \'D\'');
        List<AggregateResult> MB_Opp_E = Database.query(sql_8_3 + (pes.Report8_3_Sql1__c == null ? '' : ' ' + pes.Report8_3_Sql1__c) + (pes.Report8_3_Sql2__c == null ? '' : ' ' + pes.Report8_3_Sql2__c) + ' and Competitor__c = \'E\'');
        Map<String, Map<String, Double>> rtn = new Map<String, Map<String, Double>>();
        Map<String, Double> oppBid = new Map<String, Double>();
        oppBid.put('wt', MB_Opp_Bid[0].get('wt') == null     ? 0 : Decimal.valueOf(String.valueOf(MB_Opp_Bid[0].get('wt'))));
        oppBid.put('num', MB_Opp_Bid[0].get('num') == null   ? 0 : Decimal.valueOf(String.valueOf(MB_Opp_Bid[0].get('num'))));
        Map<String, Double> oppAuth = new Map<String, Double>();
        oppAuth.put('wt', MB_Opp_Auth[0].get('wt') == null   ? 0 : Decimal.valueOf(String.valueOf(MB_Opp_Auth[0].get('wt'))));
        oppAuth.put('num', MB_Opp_Auth[0].get('num') == null ? 0 : Decimal.valueOf(String.valueOf(MB_Opp_Auth[0].get('num'))));
        Map<String, Double> oppA = new Map<String, Double>();
        oppA.put('wt', MB_Opp_A[0].get('wt') == null         ? 0 : Decimal.valueOf(String.valueOf(MB_Opp_A[0].get('wt'))));
        oppA.put('num', MB_Opp_A[0].get('num') == null       ? 0 : Decimal.valueOf(String.valueOf(MB_Opp_A[0].get('num'))));
        Map<String, Double> oppB = new Map<String, Double>();
        oppB.put('wt', MB_Opp_B[0].get('wt') == null         ? 0 : Decimal.valueOf(String.valueOf(MB_Opp_B[0].get('wt'))));
        oppB.put('num', MB_Opp_B[0].get('num') == null       ? 0 : Decimal.valueOf(String.valueOf(MB_Opp_B[0].get('num'))));
        Map<String, Double> oppC = new Map<String, Double>();
        oppC.put('wt', MB_Opp_C[0].get('wt') == null         ? 0 : Decimal.valueOf(String.valueOf(MB_Opp_C[0].get('wt'))));
        oppC.put('num', MB_Opp_C[0].get('num') == null       ? 0 : Decimal.valueOf(String.valueOf(MB_Opp_C[0].get('num'))));
        Map<String, Double> oppD = new Map<String, Double>();
        oppD.put('wt', MB_Opp_D[0].get('wt') == null         ? 0 : Decimal.valueOf(String.valueOf(MB_Opp_D[0].get('wt'))));
        oppD.put('num', MB_Opp_D[0].get('num') == null       ? 0 : Decimal.valueOf(String.valueOf(MB_Opp_D[0].get('num'))));
        Map<String, Double> oppE = new Map<String, Double>();
        oppE.put('wt', MB_Opp_E[0].get('wt') == null         ? 0 : Decimal.valueOf(String.valueOf(MB_Opp_E[0].get('wt'))));
        oppE.put('num', MB_Opp_E[0].get('num') == null       ? 0 : Decimal.valueOf(String.valueOf(MB_Opp_E[0].get('num'))));

        rtn.put('oppBid',  oppBid);
        rtn.put('oppAuth', oppAuth);
        rtn.put('oppA',    oppA);
        rtn.put('oppB',    oppB);
        rtn.put('oppC',    oppC);
        rtn.put('oppD',    oppD);
        rtn.put('oppE',    oppE);
        return JSON.serialize(rtn);
    }
    
    public ProvinceEvaluationController() {
        //Apexpages.currentPage().getHeaders().put('X-UA-Compatible', 'IE=8');
        provinceSelectable = new Set<String>();
        provinceOpts = new List<SelectOption>();
        provinceSelectedOpts = new List<SelectOption>();
        provinceSelected = new String[]{};
    }
    
    // 画面初始化(<apex:tabPanel>外側)
    public void init() {
        dummyDr = new Daily_Report__c();
        
        Boolean hasUrlParam = false;
        if (loginUser == null) {
            loginUser = [Select Id, Alias, Name, Post__c, Job_Category__c, UserRoleId, UserRole.Name, Additional_Role__c, Salesdepartment__c, Province__c, Province_select__c, pe_tab_range__c From User where Id = :Userinfo.getUserId()];
        }
        
        // 省
        List<String> plist = new List<String>();
        String provinceParam = System.currentPageReference().getParameters().get('province');
        if (String.isBlank(provinceParam)) {
            // loginUserの値を使う
            plist = new List<String>{loginUser.Province__c};
        } else {
            //loginUser.Province__c = provinceParam;
            provinceParam = provinceParam.replaceAll('\'', '');
            plist = provinceParam.split(',');
            hasUrlParam = true;
        }

        // 省プルダウンを作成、自分の省は選択できる、以外は項目を見る
        if (String.isBlank(loginUser.Province_select__c) == false) {
            Map<String, String> proCanSeeMap = new Map<String, String>();
            for (String pro : loginUser.Province_select__c.split(';', -1)) {
                //provinceOpts.add(new SelectOption(pro, pro));
                proCanSeeMap.put(pro, pro);
                provinceSelectable.add(pro);
            }
            // カスタムラベルに定義した順番で出力
            for (String str : System.Label.ProvinceOrder_for_Evaluation.split(',')) {
                if (proCanSeeMap.containsKey(str)) {
                    provinceOpts.add(new SelectOption(str, str));
                }
            }
        }
        // 選択済みの省を設定
        for (String selectedP : plist) {
            if (provinceSelectable.contains(selectedP)) {
                provinceSelectedOpts.add(new SelectOption(selectedP, selectedP));
                provinceSelected.add(selectedP);
            }
        }
        

        // tab
        String tabParam = System.currentPageReference().getParameters().get('tab');
System.debug('tabParam:' + tabParam);
        if (String.isBlank(tabParam)) {
            // Controllerの値をそのままつかう
            if (String.isBlank(selectedTab)) {
System.debug('selectedTab:' + selectedTab);
                selectedTab = peSettingsMap.get(getFirstTabIdx()).Api_Name__c;
System.debug('selectedTab:' + selectedTab);
            }
        } else {
            selectedTab = tabParam;
            hasUrlParam = true;
        }
    }
    
    // 画面初始化(<apex:tabPanel>内側)
    public void init2() {
        if (loginUser == null) {
            loginUser = [Select Id, Alias, Name, Post__c, Job_Category__c, UserRoleId, UserRole.Name, Additional_Role__c, Salesdepartment__c, Province__c, Province_select__c, pe_tab_range__c From User where Id = :Userinfo.getUserId()];
        }

        // 省、省優先
        String province = '';
        String provinceParam = System.currentPageReference().getParameters().get('province');
        if (String.isBlank(provinceParam)) {
            // Controllerの値をそのままつかう
        } else {
            //loginUser.Province__c = provinceParam;
            province = provinceParam.replaceAll('\'', '');
        }

        // 省プルダウンを作成、自分の省は選択できる、以外は項目を見る
        if (String.isBlank(loginUser.Province_select__c) == false) {
            Map<String, String> proCanSeeMap = new Map<String, String>();
            for (String pro : loginUser.Province_select__c.split(';', -1)) {
                //provinceOpts.add(new SelectOption(pro, pro));
                proCanSeeMap.put(pro, pro);
                provinceSelectable.add(pro);
            }
            // カスタムラベルに定義した順番で出力
            for (String str : System.Label.ProvinceOrder_for_Evaluation.split(',')) {
                if (proCanSeeMap.containsKey(str)) {
                    provinceOpts.add(new SelectOption(str, str));
                }
            }
        }
        // 選択済みの省を設定
        if (String.isBlank(province) == false) {
            List<String> plist = province.split(',');
            for (String selectedP : plist) {
                if (provinceSelectable.contains(selectedP)) {
                    provinceSelectedOpts.add(new SelectOption(selectedP, selectedP));
                    provinceSelected.add(selectedP);
                }
            }
        }

        // tabIdx
        String tabIdxParam = System.currentPageReference().getParameters().get('tabIdx');
        if (String.isBlank(tabIdxParam)) {
            // Controllerの値をそのままつかう
        } else {
            tabIdx = Integer.valueOf(tabIdxParam);
            selectedTab = peSettingsMap.get(tabIdx).Api_Name__c;
        }
    }
    
    // 本部と省のURL
    public String getProvinceUrl() {
        PageReference pr = System.currentPageReference();
        String orgP = pr.getParameters().get('province');
        String orgB = pr.getParameters().get('tab');
        pr.getParameters().put('province', null);
        pr.getParameters().put('tab', selectedTab);
        String rtn = pr.getUrl();
        pr.getParameters().put('province', orgP);
        pr.getParameters().put('tab', orgB);
        return rtn;
    }
}