public with sharing class InsReportPDFController {
    public Inspection_Report__c ir { get; private set; }
    public User usr { get; private set; }
    public List<ItemBean> itemList { get; private set; }
    public List<DetailBean> detailList { get; private set; }
    public List<DetailBean> workList { get; private set; }
    
    public String sign { get; private set; }
    //add by rentx 20210707 start
    public String startfen {get;set;}
    public String endfen {get;set;}
    //add by rentx 20210707 end
    
    // 20220222 PI改造 by Bright---start
    public string staticResource { get; private set; }
    public string staticResourceFile { get; private set; }
    // 20220222 PI改造 by Bright---end

    public Integer getItemCount() {
        return itemList.size();
    }
    // 最初ページ行数
    private static Integer firstRowSize = 18;
    // 途中ページ行数
    private static Integer rowSize = 27;
    // 最後ページ行数
    private static Integer lastRowSize = 21;
    
    private static Integer codeMax = 6;
    
    private static Integer nameMax = 20;
    
    private static Integer commentMax = 15;
    
    public InsReportPDFController(){
        // 20220222 PI改造 by Bright---start
        staticResource = JSON.serialize(PIHelper.getPIIntegrationInfo('Inspection_Report__c'));
        staticResourceFile = JSON.serialize(PIHelper.getPIIntegrationInfo('Document'));
        // 20220222 PI改造 by Bright---end
    }

    public void init() {
        //add by rentx 20210707 start
        startfen = '';
        endfen = '';
        //add by rentx 20210707 end

        String id = ApexPages.currentPage().getParameters().get('id');
        ir = this.getReportData(id);
        //add by rentx 20210707 start
        if (ir.StartMinute_Page__c != null) {
            startfen = ir.StartMinute_Page__c.length() == 1 ? '0' + ir.StartMinute_Page__c : ir.StartMinute_Page__c;
        }
        if (ir.EndMinute_Page__c != null) {
            endfen = ir.EndMinute_Page__c.length() == 1 ? '0' + ir.EndMinute_Page__c : ir.EndMinute_Page__c;
        }
        //add by rentx 20210707 end

        sign = ApexPages.currentPage().getParameters().get('sign');
        
        usr = [select Alias__c from User where Id = :ir.Reporter__c];
        
        itemList = new List<ItemBean>();
        detailList = new List<DetailBean>();
        Integer cnt = 1;
        DetailBean work = null;
        workList = new List<DetailBean>();
        //add byr entx 20210831 start
        // Set<Id> assIdset = new Set<Id>();
        //add byr entx 20210831 end
        for (Inspection_Item__c record : this.getItemData(id)) {
            //add byr entx 20210831 start
            // assIdset.add(record.AssetId__c);
            //add byr entx 20210831 end 
            String productName = '';
            String productNo = '';
            String diagnosis = record.Diagnosis__c == null ? '' : record.Diagnosis__c;
            
            if (record.AssetId__c != null) {
                productName = record.AssetId__r.Name;
            } else if (record.Product_Manual__c != null) {
                productName = record.Product_Manual__r.Name;
            }
            
            if (productName.indexOf(':') >= 0) {
                productNo = productName.subString(0, productName.indexOf(':'));
                productName = productName.subString(productName.indexOf(':') + 1);
            } else if (productName.indexOf('：') >= 0) {
                productNo = productName.subString(0, productName.indexOf('：'));
                productName = productName.subString(productName.indexOf('：') + 1);
            }
            
            Integer icode = (productNo.length() / codeMax) + (Math.mod(productNo.length(), codeMax) > 0 ? 1 : 0);
            Integer iname = (productName.length() / nameMax) + (Math.mod(productName.length(), nameMax) > 0 ? 1 : 0);
            Integer icomment = (diagnosis.length() / commentMax) + (Math.mod(diagnosis.length(), commentMax) > 0 ? 1 : 0);
            
            // 1レコードに対し、最大何行になるのを計算
            // productNo、productName、diagnosis、それぞれ長さを計算、最大の行を取得
            // ここのロジックは、QuotePdfExtensionControllerを参照する（そっちのロジックは一番いい）
            // TODO xud 但し、等幅文字ではない限り、改行計算に限界あります
            List<String> codeArray = new List<String>();
            List<String> nameArray = new List<String>();
            List<String> commentArray = new List<String>();
            for ( Integer j = 0; j < icode; j++) {
                if (( j + 1) == icode) {
                    codeArray.add( productNo.substring( j * codeMax));
                }
                else {
                    codeArray.add( productNo.substring( j * codeMax, (j+1) * codeMax));
                }
            }
            for ( Integer j = 0; j < iname; j++) {
                if (( j + 1) == iname) {
                    nameArray.add( productName.substring( j * nameMax));
                }
                else {
                    nameArray.add( productName.substring( j * nameMax, (j+1) * nameMax));
                }
            }
            for ( Integer j = 0; j < icomment; j++) {
                if (( j + 1) == icomment) {
                    commentArray.add( diagnosis.substring( j * commentMax));
                }
                else {
                    commentArray.add( diagnosis.substring( j * commentMax, (j+1) * commentMax));
                }
            }
            
            Integer icnt = codeArray.size();
            if (icnt < nameArray.size()) {
                icnt = nameArray.size();
            }
            if (icnt < commentArray.size()) {
                icnt = commentArray.size();
            }
            
            for ( Integer k = 0; k < icnt; k++) {
                if (k == 0) {
                    work = new DetailBean(record);
                    work.lineNo = cnt;
                    work.delimiter = ':';
                }
                else {
                    work = new DetailBean( );
                    work.delimiter = '';
                }
                work.productNo = k < codeArray.size() ? codeArray[k] : '';
                work.productName = k < nameArray.size() ? nameArray[k] : '';
                work.diagnosis = k < commentArray.size() ? commentArray[k] : '';
                if (work.lineNo != null) work.isRecord = true;
                workList.add(work);
            }
            cnt++;
        }
        cnt = 1;
        for (Integer i = 0; i < workList.size(); i++) {
            detailList.add(workList[i]);
            if (cnt == firstRowSize) {
                itemList.add(new ItemBean(detailList));
                detailList = new List<DetailBean>(); 
            }
            if (cnt == firstRowSize + rowSize) {
                itemList.add(new ItemBean(detailList));
                detailList = new List<DetailBean>(); 
                cnt = firstRowSize;
            }
            cnt++;
        }
        
        if (detailList.size() > 0) {
            if (detailList.size() > lastRowSize) {
                List<DetailBean> tmpBean1 = new List<DetailBean>();
                List<DetailBean> tmpBean2 = new List<DetailBean>();
                for (Integer i = 0; i < lastRowSize; i++) {
                    tmpBean1.add(detailList[i]);
                }
                itemList.add(new ItemBean(tmpBean1));
                for (Integer i = lastRowSize; i < detailList.size(); i++) {
                    tmpBean2.add(detailList[i]);
                }
                itemList.add(new ItemBean(tmpBean2));
            } else {
                itemList.add(new ItemBean(detailList));
            }
        }
        //add by rentx 20210831 start 查询修理
        // Map<Id,String> assRemap = new Map<Id,String>();
        // List<Repair__c> replist = [select id,Delivered_Product__c from Repair__c where InsReport__c = :id AND Delivered_Product__c in :assIdset];
        // if (replist != null && replist.size() > 0) {
        //     for (Repair__c rep : replist) {
        //         assRemap.put(rep.Delivered_Product__c, '');
        //     }
        // }
        // for (ItemBean item : itemList) {
        //     for (DetailBean deb : item.detailList) {
        //         if (assRemap.containsKey(deb.rec.AssetId__c)) {
        //             //送修
        //             deb.isSongxiu = '是';
        //         }else{
        //             deb.isSongxiu = '否';
        //         }
        //     }
        // }
        //add by rentx 20210831 end 查询修理
    }
    
    private Inspection_Report__c getReportData(String id) {
        Schema.DescribeSobjectResult d = Inspection_Report__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 += ', Hospital__r.Name, Department__r.Department_Name__c ';
        soql += ',Contract__r.Maintenance_Contract_No__c,Contract__r.Service_contract_target_number__c,Contract__r.dianjiansum__c';
        // soql += '';
        soql += ' from Inspection_Report__c where Id = \'' + id + '\'';
        
        return Database.query(soql);
    }
    
    private List<Inspection_Item__c> getItemData(String id) {
        Schema.DescribeSobjectResult d = Inspection_Item__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 += ', AssetId__r.Service_Agreement_formula__c, AssetId__r.Name, Product_Manual__r.Name,Inspection_ReportId__r.Contract__c';
        soql += ' from Inspection_Item__c where Inspection_ReportId__c = \'' + id + '\' order by Name';
        
        return Database.query(soql);
    }
    
    public class ItemBean {
        public Integer pageCnt { get; set; }
        public List<DetailBean> detailList { get; set; }
        
        public ItemBean(List<DetailBean> detailList) {
            this.detailList = new List<DetailBean>();
            this.detailList.addAll(detailList);
        }
    }
    
    public class DetailBean {
        public Integer lineNo { get; set; }
        public String productNo { get; set; }
        public String delimiter { get; set; }
        public String productName { get; set; }
        public String serialNo { get; set; }
        public String diagnosis { get; set; }
        public String isNormal { get; set; }
        public Date lastRepair { get; set; }
        public Inspection_Item__c rec { get; set; }
        public Boolean isRecord { get; set; }
        //add by rentx 20210831 start
        public String isSongxiu{get ; set;}
        public String isHTsb{get ; set;}
        //add by rentx 20210831 end

        public DetailBean(Inspection_Item__c record) {
            this.rec = record;
            this.serialNo = '';
            if (record.Product_Manual__c != null) {
                this.serialNo = record.SerialNo_Manual__c;
            } else {
                this.serialNo = record.SerialNumber__c;
            }
            
            isNormal = record.ItemStatus__c;
            lastRepair = record.LastSFDCRepairReturn_day__c;
            //add by rentx 20210831 start
            List<Repair__c> rclist = [select id from Repair__c where InsReport__c = :record.Inspection_ReportId__c AND Delivered_Product__c = :record.AssetId__c limit 1];
            if (rclist != null && rclist.size() > 0) {
                isSongxiu = '是';
            }else{
                isSongxiu = '否';
            }
            if (record.Inspection_ReportId__r.Contract__c == null) {
                isHTsb = '否';
            }else {
                isHTsb = '是';
            }
            //add by rentx 20210831 end
            isRecord = false;
        }
        
        public DetailBean() {
            isRecord = false;
        }
    }
}