public without sharing class ConsumTrialPDFController {
    // TODO 需要确认每页显示明细数量
    // 20211210 ljh SFDC-C923SR update start
    // private final static Integer LINE_COUNT_PER_PAGE_TOP = 18;  // 每页显示的明细数量 TOP
    // private final static Integer LINE_COUNT_PER_PAGE_CENTER = 23;  // 每页显示的明细数量 CENTER
    // private final static Integer LINE_COUNT_PER_PAGE_BOTTOM = 23;  // 每页显示的明细数量 BOTTON
    private final static Integer LINE_COUNT_PER_PAGE_TOP = 16;  // 每页显示的明细数量 TOP
    private final static Integer LINE_COUNT_PER_PAGE_CENTER = 21;  // 每页显示的明细数量 CENTER
    private final static Integer LINE_COUNT_PER_PAGE_BOTTOM = 21;  // 每页显示的明细数量 BOTTON
    // 20211210 ljh SFDC-C923SR update end

    private final static Integer HOSP_BREAK_LINE_MAX_LEN = 19;  // 医疗机构名 每行最大字数
    private final static Integer SHIP_BREAK_LINE_MAX_LEN = 19;  // 发货地址 每行最大字数
    public Consum_Apply__c targetConsumApply { get; set; }  // 耗材备品申请
    private String targetConsumApplyId;  // 耗材备品申请Id
    public String hospitalName { get; set;}  // 医疗机构名
    public String shippmentAddress { get; set;}  // 发货地址

    public List<PdfPageClass> pdfPageList { get; set; }  // 所有PDF页集合
    public Integer pageTotalCnt { get; set; }  // pdf总页数
    public Integer consumApplySetDetailListSize { get; set; }  // 耗材备品总数量
    public String errorMsg { get; set; }  // 错误信息

    public string staticResource { get; private set; }
    public string staticResourceCon { get; private set; }
    public string staticResourceFile { get; private set; }
    public string BRSrc{get;private set;}
    public string QRSrc{get;private set;}

    public ConsumTrialPDFController() {
        targetConsumApplyId = ApexPages.currentPage().getParameters().get('id');
        if (String.isBlank(targetConsumApplyId)) {
            throw new ControllerUtil.myException('参数错误：请指定Id。');
        }
        pdfPageList = new List<PdfPageClass>();
        staticResource = JSON.serialize(PIHelper.getPIIntegrationInfo('Consum_Apply_Equipment_Set_Detail__c'));
        staticResourceCon = JSON.serialize(PIHelper.getPIIntegrationInfo('Consum_Apply__c'));
        staticResourceFile = JSON.serialize(PIHelper.getPIIntegrationInfo('Document'));
    }

    /**
     * @description 画面初始化处理
     */
    public void init() {
        // 获取耗材备品申请
        targetConsumApply = getTargetConsumApply();
        if (targetConsumApply == null) {
            errorMsg = '耗材备品申请不存在。';
            ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.ERROR, errorMsg));
            return;
        }

        BRSrc = GetImageBase64(targetConsumApply.BRId__c);
        QRSrc = GetImageBase64(targetConsumApply.QRId__c);
        

        // 获取耗材备品配套一览明细
        List<Consum_Apply_Equipment_Set_Detail__c> targetConsumSetDetailList = getTargetConsumSetDetailList();

        // 生成pdf页面的配套一览明细明细
        if (targetConsumSetDetailList != null) {
            createPdfPage(targetConsumSetDetailList);
        }
    }

    /**
     * @description 获取耗材备品申请的详细信息
     * @return pdf生成的耗材备品申请
     */
    private Consum_Apply__c getTargetConsumApply() {
        Consum_Apply__c targetConsumApplyObj;
        List<Consum_Apply__c> consumApplyList = [
                SELECT Id
                     , Name
                     , Name_No__c // 20211210 ljh SFDC-C923SR add
                     , QRId__c
                     , BRId__c // 20211210 ljh SFDC-C923SR add
                     , demo_purpose2__c  // 出借目的
                     // 申请人信息
                     , Salesdept__c  // 所属本部名
                     , WorkPlace__c  // 所属办事处名
                     , Person_In_Charge__r.Name  // 姓名
                     , ApplyPerson_Phone__c  // 联系电话
                     // 医疗机构信息
                     , Hospital__r.Name  // 医疗机构名
                     , Account__r.Department_Name__c  // 科室名
                     // 发货详细
                     , Shippment_adress_detail__c  // 发送办事处地址详细
                     , Direct_shippment_address__c  // 直送发送地址
                     , Shipment_address__r.Post_Code__c  // 邮编
                     , Post_Code__c  // 邮编
                     , Loaner_received_staff__c  // 接收人姓名
                     , Loaner_received_staff_phone__c  // 接收人电话
            		,AWS_Data_Id__c
                  FROM Consum_Apply__c
                 WHERE Id = :targetConsumApplyId
        ];

        if (consumApplyList.size() > 0) {
            targetConsumApplyObj = consumApplyList[0];

            // 医疗机构名 hospitalName
            // 分行显示
            String HospNameTemp = targetConsumApplyObj.Hospital__r.Name;
            if (!String.isBlank(HospNameTemp)) {
                Integer HospSize = HospNameTemp.length();
                if (HospSize <= HOSP_BREAK_LINE_MAX_LEN) {
                    HospitalName = HospNameTemp;
                } else {
                    HospitalName = HospNameTemp.substring(0, HOSP_BREAK_LINE_MAX_LEN) + '\n' + HospNameTemp.substring(HOSP_BREAK_LINE_MAX_LEN, HospSize);
                }
            }

            // 发货地址 shippmentAddress
            // 分行显示
            String ShippMentAdrTemp = null;
            if (targetConsumApplyObj.Shippment_adress_detail__c != null) {
                ShippMentAdrTemp = targetConsumApplyObj.Shippment_adress_detail__c;
            } else {
                ShippMentAdrTemp = targetConsumApplyObj.Direct_shippment_address__c;
            }

            Integer ShipAdrSize = ShippMentAdrTemp == null ? 0 : ShippMentAdrTemp.length();
            if (ShipAdrSize <= 26) {
                shippmentAddress = ShippMentAdrTemp;
            } else if (ShipAdrSize > 26 && ShipAdrSize <= 52) {
                shippmentAddress = ShippMentAdrTemp.substring(0,26)+ '\n' +ShippMentAdrTemp.substring(26,ShipAdrSize);
            } else {
                shippmentAddress = ShippMentAdrTemp.substring(0,26)+'\n'+ShippMentAdrTemp.substring(26,52) + '\n'+ShippMentAdrTemp.substring(52,ShipAdrSize);
            }
        }

        return targetConsumApplyObj;
    }

    /**
     * @description 获取耗材备品配套一览明细的详细信息, 相同一览的明细型号相同
     * @return pdf生成的耗材备品配套一览明细
     */
    private List<Consum_Apply_Equipment_Set_Detail__c> getTargetConsumSetDetailList() {
        List<Consum_Apply_Equipment_Set_Detail__c> consumApplySetDetailList = [
                SELECT Id
                     , Name
                     , Fixture_Model_No_F__c  // 明细型号
                     , ProductName__c  // 中文名称
                     , Consumable_Guaranteen_end_F__c  // 消耗品有效期
                     , Show_demonstration__c  // 展示/演示
                     , Trial_Num__c  // 试用数量
                     , Consum_Start_Date__c  // 使用期限
                     , Case_OR_animal_organ__c  // 病例/动物脏器
                     , Trial_User__c  // 试用者
                     , Follower_User__c  // 跟台者
                     , Follower_User__r.Name
                     , Spare__c  // 备用
                     , Comment__c  // 备注
                     , AWS_Data_Id__c
                     , ManagementCode__c  // 管理编码 yc 耗材追溯
                     , EquipmentManagementCode__c  // 备品管理码 yc 耗材追溯
                  FROM Consum_Apply_Equipment_Set_Detail__c
                 WHERE Consum_Apply_Equipment_Set__r.Consum_Apply__c = :targetConsumApplyId  // 耗材备品配套一览.耗材备品申请
                   AND (Cancel_Select__c = false OR NG_Select_Again__c = true)
                //    AND Shipment_request_time2__c != null //Commented By Li Jun 20220422 for PIPL
              ORDER BY Consum_Apply_Equipment_Set__r.Consum_Apply__c, Consum_Apply_Equipment_Set__c, Fixture_Model_No_F__c, Degree_Of_Importance__c
        ];
        if (consumApplySetDetailList.size() > 0) {
            return consumApplySetDetailList;
        } else {
            return null;
        }
    }

    /**
     * @description 生成pdf页面的配套一览明细明细
     * @param consumApplySetDetailList 取得的借用耗材备品明细集合
     */
    private void createPdfPage(List<Consum_Apply_Equipment_Set_Detail__c> consumApplySetDetailList) {
        // 用行数算出页数
        consumApplySetDetailListSize = consumApplySetDetailList.size();

        //新建PDF页面
        PdfPageClass pdfPage = new PdfPageClass();
        for (Integer i = 0; i < consumApplySetDetailListSize; i++) {
            // 有明细则用明细，没明细则用空行填满页面
            if (pdfPageList.size() == 0
                && pdfPage.equipSetDetailList.size() >= LINE_COUNT_PER_PAGE_TOP) {
                pdfPageList.add(pdfPage);
                pdfPage = new PdfPageClass();

            }
            else if (pdfPageList.size() > 0
                && pdfPage.equipSetDetailList.size() >= LINE_COUNT_PER_PAGE_CENTER) {
                pdfPageList.add(pdfPage);
                pdfPage = new PdfPageClass();
            }
            pdfPage.equipSetDetailList.add(consumApplySetDetailList[i]);

        }
        pdfPageList.add(pdfPage);
        if (pdfPage.equipSetDetailList.size() > LINE_COUNT_PER_PAGE_BOTTOM) {
            pdfPage = new PdfPageClass();
            pdfPageList.add(pdfPage);
        }
        Integer m = (pdfPageList.size() == 1 ? (LINE_COUNT_PER_PAGE_TOP - pdfPage.equipSetDetailList.size()) : (LINE_COUNT_PER_PAGE_BOTTOM - pdfPage.equipSetDetailList.size()));
        for (Integer i = 0; i < m; i ++) {
            pdfPage.equipSetDetailList.add(new Consum_Apply_Equipment_Set_Detail__c());
        }

        pageTotalCnt = pdfPageList.size();
    }


    /**
     * @description Pdf页面内容
     */
    public class PdfPageClass {
        // 借用耗材备品发货清单中每一行: 耗材备品配套一览明细
        public List<Consum_Apply_Equipment_Set_Detail__c> equipSetDetailList { get; private set; }
        /**
        @description
        */
        public PdfPageClass() {
            equipSetDetailList = new List<Consum_Apply_Equipment_Set_Detail__c>();
        }
    }

    public static string GetImageBase64(string id){
        List<Attachment> atts = [SELECT Id, IsDeleted, ParentId, Name, IsPrivate, ContentType, BodyLength, Body, OwnerId, CreatedDate, CreatedById, LastModifiedDate, LastModifiedById, SystemModstamp, Description FROM Attachment where id=:id];
        if (atts.size()==0) {
            return null;
        }
        return 'data:image/png;base64,' + EncodingUtil.base64Encode(atts[0].body);
    }
}