/**
 * @param id stdController.getId()
 * @param t  selectedTab  病院の場合、戦略科室のId、戦略科室の場合、Account_Number_of_case__c の Id、default 今期 or 一番新しい期 の Id
 */
public with sharing class AccountTargetHospitalController {
    public String recordId { get; private set; }
    public String recordDeveloperName { get; private set; }

    public String selectedTab { get; set; }

    // 病院用
    public List<Account> dcList { get; private set; }
    public Integer getDcCount() {
        return dcList.size();
    }

    // 戦略科室用
    public List<AccountTarget> historyList { get; private set; }
    public Integer getHistoryCount() {
        return historyList.size() - 1;          // 新規用も historyList.add() しているため
    }
    public class AccountTarget {
        public Account_Number_of_target__c rec { get; private set; }
        public String year_c { get; private set; }
        public AccountTarget(Account_Number_of_target__c rec) {
            this.rec = rec;
            //WLIG-BV8CHF 20210226 you  start
            //this.year_c = '' + rec.OCM_Period__c;
            this.year_c = 'FY' + (Integer.valueOf(rec.OCM_Period__c.substring(0, 3)) + 1868) ;
            //WLIG-BV8CHF 20210226 you  end
        }
    }

    public AccountTargetHospitalController(ApexPages.StandardController stdController) {
        recordId = stdController.getId();
        // 初始化
        dcList = new List<Account>();
        historyList = new List<AccountTarget>();
    }

    public void init() {
        if (recordId == null) {
            recordId = ApexPages.currentPage().getParameters().get('id');
        }

        List<Account> acc = [select Id, RecordType.DeveloperName from Account where Id = :recordId];
        if (acc.size() <= 0) {
            throw new ControllerUtil.myException('没有指定参数');
        }

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

        // URLのパラメータ
        String paramT = System.currentPageReference().getParameters().get('t');         // 戦略科室時、年度のレコードIdを指定
        Boolean hasParamT = false;
        Boolean hasThisPeriod = false;

        // 病院の場合
        if (acc[0].RecordType.DeveloperName == 'HP') {
            recordDeveloperName = acc[0].RecordType.DeveloperName;

            Set<String> devNameSet = new Set<String>();
            for (Target_account_manage__c setting : layoutMap.values()) {
                devNameSet.add(setting.department_class__c);
            }

            List<Account> tmpDcList = [select Id, Department_Class_Label__c, RecordType.DeveloperName from Account where ParentId = :recordId order by Department_Class_Label__c];
            if (tmpDcList.size() > 0) {
                for (Account dc : tmpDcList) {
                    if (devNameSet.contains(dc.Department_Class_Label__c)) {
                        dcList.add(dc);
                    }
                }
                if (dcList.size() > 0) {
                    selectedTab = dcList[0].Id;
                } else {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '没有找到数据'));
                }
            } else {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '没有找到数据'));
            }
        }

        // 戦略科室の場合
        else {
            // 検索条件
            Date dateToday = Date.today();
            Integer year = dateToday.year();
            Integer month = dateToday.month();
            if (month < 4) {
                year -= 1;
            }
            // 今年度以降のデータを探す
            String thisYearOCMPeriod = String.valueOf(year - 1867 + 'P');
            String nextYearOCMPeriod = String.valueOf(year - 1867 + 'P');

            // 病例数 取得、未来、今期、過去4年分、計5年+ になります。
            // 前提、期ごと１件しかないこと
            List<String> pOCMPeriodList = new List<String>();
            for (Integer i = 0; i < 5; i++) {
                pOCMPeriodList.add(String.valueOf(year - 1867 - i + 'P'));
            }
            // 戦略科室
            List<Account_Number_of_target__c> acList = Database.query(this.makeSoql(recordId, pOCMPeriodList, thisYearOCMPeriod));
            if (acList.size() > 0) {
                for (Account_Number_of_target__c ac : acList) {
                    // 今期のデータがあれば、今期を選択
                    if (thisYearOCMPeriod == ac.OCM_Period__c) {
                        selectedTab = ac.Id;
                        hasThisPeriod = true;
                    }
                    if ('' + ac.Id == paramT) {
                        hasParamT = true;
                    }
                    historyList.add(new AccountTarget(ac));
                }
                // 今期のデータがなければ、最大期を選択
                if (hasThisPeriod == false) {
                    selectedTab = acList[acList.size() - 1].Id;
                }
            }
            historyList.add(new AccountTarget(new Account_Number_of_target__c(OCM_Period__c = nextYearOCMPeriod)));
        }

        if (hasParamT) {
            selectedTab = paramT;
        }
    }

    private String makeSoql(String accId, List<String> pOCMPeriodList, String thisYearOCMPeriod) {
        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 = \'' + accId + '\''
             + ' and (OCM_Period__c IN :pOCMPeriodList or OCM_Period__c > :thisYearOCMPeriod)'
             + ' order by OCM_Period__c';

        return soql;
    }
}