global with sharing class ContentPreviewController {
    public String hpId { get; private set; }
    public String hpName { get; private set; }
    public String docId { get; set; }
    public String xlsId { get; private set; }
    public String msg { get; private set; }
    public List<String> pdfpptList { get; private set; }
    
    public String comment { get; set; }
    public Daily_Report__c dummyReport { get; set; }
    
    public Boolean disableDL { get; private set; }
    public Boolean isError { get; private set; }
    public Boolean noDoc { get; private set; }
    public Boolean refBtnNG { get; private set; }
    
    //public static String hpName { get; private set; }
    public static List<SelectOption> pdfTypeOpts  { get; private set; }
    static {
        pdfTypeOpts = new List<SelectOption>();
    }
    
    
    public ContentPreviewController() {
        pdfpptList = new List<string>();
        disableDL = false;
        isError = false;
        noDoc = false;
        refBtnNG = false;
        
        dummyReport = new Daily_Report__c();
    }
    
    // PDFもPPTもこれを呼ぶ
    @RemoteAction
    global static Map<String, Object> getDocumentBody(String did) {
        Map<String, Object> rtn = new Map<String, Object>();
        
        List<Document> doc = ControllerUtil.getPdfBlobForPreview(did);
        rtn.put('body', EncodingUtil.Base64Encode(doc[0].Body));
        rtn.put('name', doc[0].Name.split('_')[1] + '_' + doc[0].Name.split('_')[2]);
        rtn.put('time', doc[0].Name.substring(0, 4) + '年' + doc[0].Name.substring(4, 6) + '月' + doc[0].Name.substring(6, 8) + '日');
        rtn.put('type', doc[0].Name.split('_')[2]);
        
        return rtn;
    }
    
    @RemoteAction
    global static void saveComment(String subject, String comment, String docId, String hpId) {
        Task tsk = new Task(
            // Owner固定で王海娟にする
            OwnerId = '00510000000gWAQ',
            Subject = subject,
            Description = comment,
            PdfDocumentId__c = docId,
            ActivityDate = System.today()
        );
        insert tsk;
    }
    
    public void init() {
        hpId = System.currentPageReference().getParameters().get('id');
        
        List<Account> accs = [select Id, Name, Account2__r.AnalysisContentId__c, Account2__r.AnalysisContentDate__c, State_Master__r.Assistant__c from Account where Id = :hpId];
        if (accs.size() > 0) {
            hpName = accs[0].Name;
            dummyReport.OwnerId = accs[0].State_Master__r.Assistant__c;
            
            // ユーザ権限
            User u = [select CanDownloadHospitalPPT__c, Service_proposal__c, Sales_analysis_proposal__c, Sales_proposal__c from User where Id = :UserInfo.getUserId()];
            if (u.CanDownloadHospitalPPT__c == false) {
                disableDL = true;
            }
            if (u.Service_proposal__c == false && u.Sales_analysis_proposal__c == false && u.Sales_proposal__c == false) {
                msg = '您没有足够的权限执行所请求的操作。如果需要访问，请联系记录所有人或管理员。';
                isError = true;
                return;
            }
            // TODO xudan PDFタイプ出すの優先順
            if (String.isBlank(accs[0].Account2__r.AnalysisContentId__c) == false) {
                // AnalysisContentId__cは固定フォーマット
                List<String> docStrIds = accs[0].Account2__r.AnalysisContentId__c.split(',');
                // Documentを検索し、作成日を見る
                List<Document> doc = ControllerUtil.getPdfBlobForPreview(docStrIds[0]);
                if (doc.size() < 1) {
                    noDoc = true;
                    msg = '该客户的现状分析数据已过期。请点击【现状分析文档更新】按钮作成最新的文档。';
                    return;
                }
                Date createdDate = accs[0].Account2__r.AnalysisContentDate__c;
                // 有効期限を超えたら、ドキュメント作成を要求する
                if (createdDate.daysBetween(Date.today()) > Integer.valueOf(System.Label.AnalysisDocValidDay)) {
                    noDoc = true;
                    msg = '该客户的现状分析数据已过期。请点击【现状分析文档更新】按钮作成最新的文档。';
                    return;
                }
                // 今日作成したファイルを再度更新できない
                if (createdDate.year() == Date.today().year()
                        && createdDate.month() == Date.today().month()
                        && createdDate.day() == Date.today().day()) {
                    refBtnNG = true;
                }
                
                String pdfType = '';
                Map<String, String> pdfTypeIdMap = new Map<String, String>();
                if (u.Service_proposal__c) {
                    pdfType = '服务提案书';
                    pdfTypeIdMap.put(pdfType, docStrIds[0]);
                    pdfTypeOpts.add(new SelectOption(docStrIds[0], pdfType));
                }
                if (u.Sales_analysis_proposal__c) {
                    pdfType = '销售提案书';
                    pdfTypeIdMap.put(pdfType, docStrIds[1]);
                    pdfTypeOpts.add(new SelectOption(docStrIds[1], pdfType));

                }
                if (u.Sales_proposal__c) {
                    pdfType = '业绩分析提案书';
                    pdfTypeIdMap.put(pdfType, docStrIds[2]);
                    pdfTypeOpts.add(new SelectOption(docStrIds[2], pdfType));
                }

                pdfpptList.add(docStrIds[0] + '_' + docStrIds[3]);
                pdfpptList.add(docStrIds[1] + '_' + docStrIds[4]);
                pdfpptList.add(docStrIds[2] + '_' + docStrIds[5]);
                
                docId = String.valueOf(pdfTypeIdMap.get(pdfType));
                xlsId = docStrIds[6];
            }
            // データなし
            else {
                noDoc = true;
                msg = '该客户还没有现状分析数据。请点击【现状分析文档更新】按钮作成最新的文档。';
            }
        }
        // 権限なし
        else {
            msg = '您没有足够的权限执行所请求的操作。如果需要访问，请联系记录所有人或管理员。';
            isError = true;
        }
    }
    
    // ダウンロード依頼
    public void sendDlRequest() {
        BatchIF_Log__c b = new BatchIF_Log__c();
        // タイプ
        b.Type__c = 'DlRequest';
        // 病院名
        b.Log__c = hpName;
        // 提案書タイプ
        List<Document> doc = ControllerUtil.getPdfBlobForPreview(docId);
        b.Log2__c = doc[0].Name.split('_')[2];
        // URL
        b.Log3__c = URL.getSalesforceBaseUrl().toExternalForm() + '/apex/ContentPreview?id=' + hpId;
        // 依頼者
        b.OwnerId = dummyReport.OwnerId;
        b.Is_Error__c = 0;
        ControllerUtil.insertBatchIfLog(b);
    }
    
    // 更新依頼
    public void sendRefRequest() {
        Integer h = Integer.valueOf(System.Label.AnalysisRequestValidH);
        Datetime dt = System.now().addHours(-h);
        List<BatchIF_Log__c> bif = ControllerUtil.getBatchIfLogForRequest('RefRequest', hpId, dt);
        // 1時間内、同じ取引先へのリクエストがあれば、エラー
        if (bif.size() > 0) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, h + '小时之内已经受理了相同的请求，请等待处理完成'));
        }
        else {
            BatchIF_Log__c b = new BatchIF_Log__c();
            // タイプ
            b.Type__c = 'RefRequest';
            // 病院
            b.Account__c = hpId;
            // 番号
            //b.DocRequestNo__c = 'DOC' + ControllerUtil.generateRandomStr(9);
            b.RequestStatus__c = 'Request';
            b.Is_Error__c = 0;
            ControllerUtil.insertBatchIfLog(b);
            
            b = [select Name from BatchIF_Log__c where Id = :b.id];
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '您的请求已发出，编号为' + b.Name + '，请确认您的邮件'));
        }
    }
}