public with sharing class AccountTargetTabController {
    //private static integer SECTIONMAX = 10;
    private static integer FIELDMAX = 100;

    // private Account dept ; //lt 20230419 DB202303610487 目标客户页面增加市场目标产品信息  市场目标产品 共同推进 add  { get; private set; }
    public Account dept { get; private set; }//lt 20230419 DB202303610487 目标客户页面增加市场目标产品信息  市场目标产品 共同推进 add  { get; private set; }

    private Target_account_manage__c layout;
    private Map<String, Target_account_manage__c> layoutMap;
    private Map<String, Schema.SObjectField> layoutFieldMap;

    public HistoryBean history { get; set; }
    public String accId { get; private set; }

    public Boolean refreshAll { get; private set; }
    public Boolean dupliErr { get; private set; }
    public String dupliID { get; private set; }

    public List<String> ocmOptions { get; private set; }
    public List<SelectOption> ocmYearOptions { get; private set; }
    //public Map<String,id> RecordTypeMap;

    public Integer getDataSize() {
        return (history == null || history.dataList == null) ? 0 : history.dataList.size();
    }

    public AccountTargetTabController() {
        refreshAll = false;
        dupliErr = false;
        ocmOptions = new List<String>();
        ocmYearOptions = new List<SelectOption>();
        history = null;

        layout = new Target_account_manage__c();
        layoutMap = Target_account_manage__c.getAll();
        if (layoutMap.values().size() <= 0) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '无法获取自定义设置'));
            return;
        }

        Schema.DescribeSobjectResult acl = Target_account_manage__c.sObjectType.getDescribe();
        layoutFieldMap = acl.fields.getMap();
    }

    public void init() {
/*        RecordTypeMap = new Map<String,Id>();
        RecordTypeMap.put('Department_Class_GI','01210000000QmhoAAC');//戦略科室分類 消化科
        RecordTypeMap.put('Department_Class_ET','01210000000QmhoAAC');//戦略科室分類ET
        RecordTypeMap.put('Department_Class_BF','01210000000QmhyAAC');//戦略科室分類 呼吸科
        RecordTypeMap.put('Department_Class_GS','01210000000QmvDAAS');//戦略科室分類 普外科
        RecordTypeMap.put('Department_Class_URO','01210000000QmutAAC');//戦略科室分類 泌尿科
        RecordTypeMap.put('Department_Class_GYN','01210000000QmuyAAC');//戦略科室分類 婦人科
        RecordTypeMap.put('Department_Class_ENT','01210000000Qmv3AAC');//戦略科室分類 耳鼻喉科
        RecordTypeMap.put('Department_Class_OTH','01210000000Qmv8AAC');//戦略科室分類 その他*/
        String recordId = System.currentPageReference().getParameters().get('id');
        accId = System.currentPageReference().getParameters().get('accid');

        dept = [select Id, ParentId, RecordType.DeveloperName, Department_Class_Label__c from Account where Id = :accId];
        for (Target_account_manage__c setting : layoutMap.values()) {
            if (dept.Department_Class_Label__c == setting.department_class__c) {
                layout = setting;
            }
        }
        if (layout.Id == null) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '无法获取自定义设置'));
            return;
        }

        // 今年±1期のみを出す
        Date dateToday = Date.today();
        Integer year = dateToday.year();
        Integer month = dateToday.month();
        if (month < 4) {
            year -= 1;
        }
        // OCM期、画面からremoveするデータを設定
        Schema.DescribeFieldResult fieldResult = Account_Number_of_target__c.OCM_Period__c.getDescribe();
        List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
        for(Schema.PicklistEntry f : ple) {
            if (f.getValue() == String.valueOf(year - 1867 - 1 + 'P')
                || f.getValue() == String.valueOf(year - 1867 + 'P')
                || f.getValue() == String.valueOf(year - 1867 + 1 + 'P')) {
                continue;
            }
            ocmOptions.add(f.getValue());
        }
        // OCM年度、画面からremoveするデータを設定
        Schema.DescribeFieldResult fieldResultYear = Account_Number_of_target__c.OCM_Year__c.getDescribe();
        List<Schema.PicklistEntry> pley = fieldResultYear.getPicklistValues();
/*
        for(Schema.PicklistEntry f : pley) {
            if (f.getValue() == String.valueOf(year - 1 + '年度')
                || f.getValue() == String.valueOf(year + '年度')
                || f.getValue() == String.valueOf(year + 1 + '年度')) {
                continue;
            }
            ocmYearOptions.add(f.getValue());
        }
*/
        //ocmYearOptions.add(new SelectOption(String.valueOf(year - 1 + '年度'),String.valueOf(year - 1 + '年度')));
        //WLIG-BV8CHF 20201222 you  start
        //ocmYearOptions.add(new SelectOption(String.valueOf(year + '年度'),String.valueOf(year - 1867 + 'P')));
        ocmYearOptions.add(new SelectOption(String.valueOf(year + '年度'),String.valueOf('FY'+(year + 1 ))));
        //WLIG-BV8CHF 20201222 you  end
        //ocmYearOptions.add(new SelectOption(String.valueOf(year + 1 + '年度'),String.valueOf(year - 1867 + 1 + 'P')));

        if (String.isBlank(recordId) == true) {
            List<Account_Number_of_target__c> tmpList = Database.query(this.makeSoql2());
            if (tmpList.size() > 0) {
                //history = new HistoryBean(tmpList[0].clone(false, true), layout, layoutFieldMap);
                history = new HistoryBean(new Account_Number_of_target__c(), layout, layoutFieldMap);
                //history.rec.OCM_Period__c = null;
                //history.rec.OCM_Year__c = null;
            } else {
                history = new HistoryBean(new Account_Number_of_target__c(), layout, layoutFieldMap);
            }
        } else {
            selectData(recordId);
        }
    }

    // 重複エラーが発生する時、js alertを出し、＋タブを消すため、画面リフレッシュ必要
    // 正常で終了する時、新規追加されたタブを出すため、画面リフレッシュ必要
    // 合わせて、refreshAllフラグを設定
    public void save() {
        Savepoint sp = Database.setSavepoint();
        try {
            // 新規
            if (history.rec.Id == null) {
                history.rec.OCM_Period__c = changeY2P(history.rec.OCM_Year__c);

                // 重複チェック
                List<Account_Number_of_target__c> tmp = [select Id from Account_Number_of_target__c where Account__c = :accId and OCM_Period__c = :history.rec.OCM_Period__c];
                if (tmp.size() > 0) {
                    dupliID = tmp[0].Id;
                    dupliErr = true;
                    refreshAll = true;
                    return;
                }

                //history.rec.RecordTypeid = RecordTypeMap.get(dept.RecordType.DeveloperName);
                history.rec.Account__c = dept.Id;
                history.rec.Account_HP__c = dept.ParentId;

                insert history.rec;
                refreshAll = true;
            }
            // 更新
            else {
                history.rec.OCM_Period__c = changeY2P(history.rec.OCM_Year__c);
                update history.rec;
                selectData(history.rec.Id);
            }

            List<Account> dcList = [select id from account where id = :accId];
            List<Account_Number_of_target__c> upsertList = OpdAmountBatch.main(dcList);
            if (upsertList.size() > 0) upsert upsertList;

            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '保存完了。'));
        } catch (Exception ex) {
            Database.rollback(sp);
            ApexPages.addMessages(ex);
        }
    }

    private String changeY2P(String ocmYear) {
        Integer y = Integer.valueOf(ocmYear.substring(0, 4));
        return y - 1867 + 'P';
    }

    private void selectData(String recordId) {
        List<Account_Number_of_target__c> tmpList = Database.query(this.makeSoql(recordId));
        if (tmpList.size() > 0) {
            history = new HistoryBean(tmpList[0], layout, layoutFieldMap);
        }
        else {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '没有数据。'));
        }
    }

    private String makeSoql(String recordId) {
        Schema.DescribeSobjectResult d = Account_Number_of_target__c.sObjectType.getDescribe();
        Map<String, Schema.SObjectField> fieldMap = d.fields.getMap();

        String soql = 'select ';
        String fields = '';
        for (String field : fieldMap.keySet()) {
            if (fields.length() > 0) {
                fields += ', ';
            }
            fields += field;
        }
        soql += fields;
        soql += ' from Account_Number_of_target__c where Id = :recordId';
        return soql;
    }

    private String makeSoql2() {
        Schema.DescribeSobjectResult d = Account_Number_of_target__c.sObjectType.getDescribe();
        Map<String, Schema.SObjectField> fieldMap = d.fields.getMap();

        String soql = 'select ';
        String fields = '';
        for (String field : fieldMap.keySet()) {
            if (fields.length() > 0) {
                fields += ', ';
            }
            fields += field;
        }
        soql += fields;
        soql += ' from Account_Number_of_target__c where Account__c = \'' + this.accId + '\''
             + ' order by OCM_Period__c desc limit 1';

        return soql;
    }

    public class HistoryBean {
        public Account_Number_of_target__c rec { get; set; }
        public List<OutputData> dataList { get; set; }
        public Boolean isPast { get; set; }
        public List<String> emptyLineLeft {get; set;}
        public List<String> emptyLineRight {get; set;}

        public HistoryBean(Account_Number_of_target__c record, Target_account_manage__c layout, Map<String, Schema.SObjectField> layoutFieldMap) {
            rec = record;
            dataList = new List<OutputData>();
            isPast = false;
            Date dateToday = Date.today();
            Integer year = dateToday.year();
            Integer month = dateToday.month();
            if (month < 4) {
                year -= 1;
            }
            Integer day = dateToday.day();
            Integer buffer = Integer.valueOf(System.Label.Account_target_buffer_day);
            String strY = record.OCM_Year__c;
            if (strY != null && strY != '') {
                Integer intY = Integer.valueOf(strY.substring(0, 4));
                if (intY < year && !(year - intY == 1 && month == 4 && day <= buffer)) {
                    isPast = true;
                }
            }            

            for (Integer i = 1; i <= FIELDMAX; i++) {
                String strI = 'field' + i + '__c';
                if (layoutFieldMap.containsKey(strI) == false) continue;
                String fieldStr = String.valueOf(layout.get(strI));
                if (String.isBlank(fieldStr) == false) {
                    dataList.add(new OutputData(record, fieldStr));
                }
            }

            // 2022/01/07 ssm 增加左右空行 start
            emptyLineLeft = new List<String>();
            emptyLineRight = new List<String>();
            // 左侧固定有4行，右侧固定有7行，判断dataList长度确定在哪边加行
            if (dataList.size() > 0 && dataList.size() < 3) {
                for (Integer i = 0; i < 3 - dataList.size(); i++) {
                    emptyLineLeft.add('');
                }
            } else if (dataList.size() > 3){
                for (Integer i = 0; i < dataList.size() - 3; i ++) {
                    emptyLineRight.add('');
                }
            }
            // 2022/01/07 ssm 增加左右空行 end
        }
    }

    class OutputData {
        //public Account_Number_of_target__c rec { get; set; }
        public String label1 { get; private set; }
        public String field1 { get; private set; }
        public String label2 { get; private set; }
        public String field2 { get; private set; }
        public String label3 { get; private set; }
        public String field3 { get; private set; }

        // 2020/07/14 taoqz add start
        public String label4 { get; private set; }
        public String field4 { get; private set; }
        // 2020/07/14 taoqz add start

        public OutputData(Account_Number_of_target__c record, String jsonField) {
            //this.rec = record;
            Map<String, Object> m = (Map<String, Object>) JSON.deserializeUntyped(jsonField);
            String label = String.valueOf(m.get('label'));
            String api = String.valueOf(m.get('api'));
            this.label1 = '目标数：' + label;
            this.field1 = 'Target_amount_' + api + '__c';
            this.label2 = 'OPD对象：' + label;
            this.field2 = 'OPD_' + api + '__c';
            this.label3 = 'OPD数：' + label;
            this.field3 = 'OPD_amount_' + api + '__c';

            // 2020/07/14 taoqz add start
            this.label4 = 'OPD计划月：' + label;
            this.field4 = 'OPD_PlanMonth_' + api + '__c';
            // 2020/07/14 taoqz add end

        }
    }

}