public with sharing class MceConfigPDFController {
    /** 処理対象の見積オブジェクトです。 */
    public EstimateInfo targetObj { get; private set; }
    /** 見積オブジェクトのリスト（改ページ用） */
    public List<EstimateInfo> targetObjList { get; private set; }
    /** 1ページに表示する明細の数です。 */
    //public Boolean HideOrNot{ get; private set; }
    private Integer rowSize = 30;   // TODO カスタムラベルに定義
    
    private Integer nameMax = 20;   //名称最大长度 全是中文的话 最多18 但因为不会全是中文 所以设为20
    private Integer commentMax = 5; //备注最大长度
    //private Integer modelNoMax = 9; //型号最大长度

    private Integer lineNo = 0;
    
    /** 最終ページに表示する明細の数です。 */
    //private Integer lastRowSize = 24;
    /** 印刷するページ数です。 */
    //public Integer maxPageNumber { get; private set; }
    //2021-11-30 fy add LJPH-C8W8FV 置顶 start
    public List<String> TopProductModel =new List<String>();
    //2021-11-30 fy add LJPH-C8W8FV 置顶 end

    public String  RecordTypeName { get; private set; }
    public Integer year { get; private set; }
    public String flag { get; private set; }
    public Integer getTargetObjSize() {
        return this.targetObjList.size();
    }
    
    /**
     * Visualforceページがアクセスするコンストラクタです。
     * 印刷するデータを収集し、インスタンス変数にセットします。
     * @param controller スタンダードコントローラーのインスタンス
     */
    public MceConfigPDFController(ApexPages.StandardController controller) {
    }
    public void init() {
        //2021-11-30 fy add LJPH-C8W8FV 置顶 start
        TopProductModel.add('CF-LV1I');
        TopProductModel.add('CF-LV1L');
        TopProductModel.add('CV-V1');
        TopProductModel.add('GIF-LV1');
        TopProductModel.add('OER-AW');
        TopProductModel.add('OER-A');
        //2021-11-30 fy add LJPH-C8W8FV 置顶 end
        String targetEstimateId = ApexPages.currentPage().getParameters().get('id');
        flag = ApexPages.currentPage().getParameters().get('flag');
        // 見積情報を取得、必ずあるはず
        List<Maintenance_Contract_Estimate__c> mceList = [SELECT Id, Name, Maintenance_Contract__c, Estimate_Target__c, Dealer__r.Name,
                                                                 Maintenance_Contract__r.Management_Code__c, CreatedBy.fen_corp_name__c, 
                                                                 Maintenance_Contract__r.Hospital__r.Name, Department__c,
                                                                 Contract_Range__c, Contract_Esti_Start_Date__c, Contract_Esti_End_Date__c,
                                                                 Contract_Start_Date__c, Contract_End_Date__c,Maintenance_Contract__r.SalesOfficeCode_selection__c,
                                                                 Estimate_Trial_Money__c, Maintenance_Price__c, NotUse_Oxygenated_Water__c,
                                                                 Examination_Price__c, Service_contract_target_number__c, Append_Condition_Price__c,
                                                                 Discount_Price__c, Discount_Percentage__c, Last_Discount__c, Asset_Sum_Price__c,
                                                                 Print_Contract__c, Print_RepairPrice__c, Print_DiscountPercentage__c,
                                                                 Print_DiscountPrice__c, Print_ListPrice__c, Print_MaintePrice__c, Print_SumPrice__c,
                                                                 Is_New_Contract__c, // HWAG-B5C88S 2018/11/06
                                                                 RecordType.DeveloperName
                                                            FROM Maintenance_Contract_Estimate__c WHERE Id = :targetEstimateId];
        // 見積を取得できない場合
        if (mceList.size() == 0) {
            throw new ControllerUtil.myException('报价不存在');
        }
        
        this.targetObj = new EstimateInfo(mceList);
        targetObjList = new List<EstimateInfo>();
        EstimateInfo tmpTargetObj = new EstimateInfo(mceList);

        RecordTypeName = mceList[0].RecordType.DeveloperName;
        // 明細の設定
        Integer cnt = 0;
        List<Maintenance_Contract_Asset_Estimate__c> MaintenanceCAE = [SELECT Id, Name, Asset__c, Maintenance_Contract_Estimate__r.Department__c,
                        //2021-11-30 fy add LJPH-C8W8FV 置顶 start
                        Asset__r.OwnershipMachine_No__c,
                        //2021-11-30 fy add LJPH-C8W8FV 置顶 end
                        //2021-11-30 fy add LJPH-C8W8FV 置顶 start
                        Product_Manual__r.Asset_Model_No__c,
                        //2021-11-30 fy add LJPH-C8W8FV 置顶 end
                        Asset__r.Name, Asset__r.SerialNumber, Asset__r.InstallDate,
                        Asset__r.Product2.Name,
                        Product_Manual__c, Product_Manual__r.Name, IsNew__c,
                        Maintenance_Price_Month__c, Estimate_List_Price__c,
                        Check_Result__c, Repair_Price__c, Comment__c,Characteristic__c,
                        Check_Object__c //wangweipeng 20210610
                   FROM Maintenance_Contract_Asset_Estimate__c
                  WHERE Maintenance_Contract_Estimate__c = :this.targetObj.estimate.Id
                  ORDER BY Product_Manual__c, Asset__r.SerialNumber, Asset__r.Name, Asset__r.Department_Name__c, Asset__r.InstallDate];
                  system.debug('检查::::::'+MaintenanceCAE);
                //2021-11-30 fy add LJPH-C8W8FV 置顶 start
                List<Maintenance_Contract_Asset_Estimate__c> topAsset =new List<Maintenance_Contract_Asset_Estimate__c>();
                List<Maintenance_Contract_Asset_Estimate__c> otherAsset =new List<Maintenance_Contract_Asset_Estimate__c>();
                
                for(Maintenance_Contract_Asset_Estimate__c tarAsse : MaintenanceCAE){
                    if(TopProductModel.contains(tarAsse.Asset__r.OwnershipMachine_No__c)||TopProductModel.contains(tarAsse.Product_Manual__r.Asset_Model_No__c)){
                        topAsset.add(tarAsse);
                    }else{
                        otherAsset.add(tarAsse);
                    }
                }
                topAsset.addAll(otherAsset);
                MaintenanceCAE=topAsset;
                //2021-11-30 fy add LJPH-C8W8FV 置顶 end
        for(Maintenance_Contract_Asset_Estimate__c mcae :MaintenanceCAE) {
            //for(Integer a=0;a<50;a++){
            //tmpTargetObj.addAssetInfo(mcae);
            //HideOrNot = false;
            system.debug(mcae.Product_Manual__r.Name+':::::::::::'+mcae.Product_Manual__c);
            String sname = '';
            if (mcae.Asset__c !=  null) {
                sname = mcae.Asset__r.Product2.Name == null ? '' : mcae.Asset__r.Product2.Name;
            } else {
                sname = mcae.Product_Manual__r.Name == null ? '' : mcae.Product_Manual__r.Name;
            }
            String smodelNo = '';
            String scomment = mcae.Comment__c == null ? '' : mcae.Comment__c;
            if (sname.indexOf(':') >= 0) {
                smodelNo = sname.subString(0, sname.indexOf(':')+1);
                sname = sname.subString(sname.indexOf(':')+1);
            } else if (sname.indexOf('：') >= 0) {
                smodelNo = sname.subString(0, sname.indexOf('：')+1);
                sname = sname.subString(sname.indexOf(':')+1);
            } else {
                smodelNo = '';
            }

            //型号行数
            /*Integer imodelNo =(smodelNo.length() / modelNoMax) + (Math.mod(smodelNo.length(), modelNoMax) > 0 ? 1 : 0);
            if(imodelNo == 0){
                imodelNo = 1;
            }*/

            //机器名行数
            
            Integer iname = (sname.length() / nameMax) + (Math.mod(sname.length(), nameMax) > 0 ? 1 : 0);
            if (iname == 0) {
                iname = 1;
            }
            //备注行数
            Integer icomment = (scomment.length() / commentMax) + (Math.mod(scomment.length(), commentMax) > 0 ? 1 : 0);
            if (icomment == 0) {
                icomment = 1;
            }
            //没个td中的实际行数
            Integer icnt = iname;
            if (iname < icomment) {
                /*if(icomment < imodelNo){
                    icnt = imodelNo;
                }else{
                    icnt = icomment;
                }*/
                icnt = icomment;
            }/*else{
                if(icomment < imodelNo){
                    if(iname < imodelNo){
                        icnt = imodelNo;
                    }
                }
            }*/

            
            if (mcae.Asset__c !=  null) {
                mcae.Asset__r.Name = smodelNo + sname;
            } else {
                mcae.Product_Manual__r.Name = smodelNo + sname;
                system.debug('测试一下这个位置sname'+sname);
            }
            
            cnt+=icnt;
            //
            if (cnt > this.rowSize) {
                cnt = icnt;
                //HideOrNot = false;
                targetObjList.add(tmpTargetObj);
                tmpTargetObj = new EstimateInfo(mceList);
                
            }


            // 改ページ判断
            lineNo += 1;
            tmpTargetObj.addAssetInfo(lineNo, mcae, nameMax,commentMax);
            
            /*if (icnt > 1) {
                for (Integer i = 0; i < icnt; i++) {
                    if  (i == 0) {//第一行
                        if (mcae.Asset__c !=  null) {
                            if (i + 1 == iname) {
                                mcae.Asset__r.Name = smodelNo + sname;
                            } else {
                                mcae.Asset__r.Name = smodelNo + sname.substring(0, nameMax);
                            }
                        } else {
                            if (i + 1 == iname) {
                                mcae.Product_Manual__r.Name = smodelNo + sname;
                                system.debug('测试一下这个位置sname'+sname);
                            } else {
                                mcae.Product_Manual__r.Name = smodelNo + sname.substring(0, nameMax);
                                //mcae.Product_Manual__r.Name = '哈哈哈哈';
                            }
                        }
                        if (i + 1 == icomment) {
                            mcae.Comment__c = scomment;
                        } else {
                            mcae.Comment__c = scomment.substring(0, commentMax);
                        }
                        lineNo += 1;
                        tmpTargetObj.addAssetInfo(lineNo, mcae,HideOrNot);
                    } else {
                        system.debug('Before clone::::'+mcae.Product_Manual__r.Name);
                        Maintenance_Contract_Asset_Estimate__c newmcae = mcae.clone();
                        if (mcae.Asset__c !=  null) {
                            if (i < iname) {
                                if (i + 1 == iname) {
                                    newmcae.Asset__r.Name = sname.substring(i*nameMax);
                                } else {
                                    newmcae.Asset__r.Name = sname.substring(i*nameMax, (i+1)*nameMax);
                                }
                            } else {
                                newmcae.Asset__r.Name = '';
                            }
                        } else {
                            if (i < iname) {
                                if (i + 1 == iname) {
                                    newmcae.Product_Manual__r.Name = sname.substring(i*nameMax);
                                } else {
                                    newmcae.Product_Manual__r.Name = sname.substring(i*nameMax, (i+1)*nameMax);
                                }
                            } else {
                                system.debug('Before Clear::::::'+newmcae.Product_Manual__r.Name);
                                //newmcae.Product_Manual__r.Name = '';
                                HideOrNot = true;
                            }
                        }
                        if (i < icomment) {
                            if (i + 1 == icomment) {
                                newmcae.Comment__c = scomment.substring(i*commentMax);
                            } else {
                                newmcae.Comment__c = scomment.substring(i*commentMax, (i+1)*commentMax);
                            }
                        } else {
                            newmcae.Comment__c = '';
                        }
                        tmpTargetObj.addAssetInfo(lineNo, newmcae,HideOrNot);
                        
                        AssetInfo ainfo = tmpTargetObj.assetInfoList.get(tmpTargetObj.assetInfoList.size()-1);
                        ainfo.lineNo = null;
                        ainfo.assetModelNo = null;
                        ainfo.assetSerialNumber = null;
                    }
                    // 改ページ判断
                    if (cnt == this.rowSize) {
                        cnt = 0;
                        HideOrNot = false;
                        targetObjList.add(tmpTargetObj);
                        tmpTargetObj = new EstimateInfo(mceList);
                    }
                    cnt++;
                }
            } else {
                lineNo += 1;
                if (mcae.Asset__c != null) {
                    mcae.Asset__r.Name = smodelNo + sname;
                } else {
                    mcae.Product_Manual__r.Name = smodelNo + sname;
                    system.debug('::::测试极端'+smodelNo + sname);
                }
                tmpTargetObj.addAssetInfo(lineNo, mcae,HideOrNot);
                // 改ページ判断
                if (cnt == this.rowSize) {
                    cnt = 0;
                    HideOrNot = false;
                    targetObjList.add(tmpTargetObj);
                    tmpTargetObj = new EstimateInfo(mceList);
                }
                cnt++;
            }*/
        }
        
        if (tmpTargetObj.assetInfoList.size() > 0) {
            targetObjList.add(tmpTargetObj);
        }
        
        // 会計年度計算、ただしここは 日本の年度ではない
//        Integer y = this.targetObj.estimate.Contract_Esti_Start_Date__c.year();
//        Integer m = this.targetObj.estimate.Contract_Esti_Start_Date__c.month();
        Integer y = this.targetObj.estimate.Contract_Start_Date__c.year();
        Integer m = this.targetObj.estimate.Contract_Start_Date__c.month();
        if (m >= 4) {
            this.year = y;
        } else {
            this.year = y;  // y - 1;
        }
    }
    
    private static Map<String, String> companyApiMap = new Map<String, String> {
        '北京RC' => '奥林巴斯（北京）销售服务有限公司',
        '上海RC' => '奥林巴斯（北京）销售服务有限公司上海分公司',
        '广州RC' => '奥林巴斯（北京）销售服务有限公司广州分公司',
        '沈阳RC' => '奥林巴斯（北京）销售服务有限公司',
        //wangweipeng  2021/07/30   start
        '成都RC' => '奥林巴斯（北京）销售服务有限公司成都维修分公司',
        '西安RC' => '奥林巴斯（北京）销售服务有限公司西安维修分公司',
        '杭州RC' => '奥林巴斯（北京）销售服务有限公司杭州维修分公司'
        //wangweipeng  2021/07/30   start
    };

    /**
     * 印刷するデータを格納するオブジェクを定義する、親
     */
    public class EstimateInfo {
        public Maintenance_Contract_Estimate__c estimate {get; private set;}
        public List<AssetInfo> assetInfoList {get; private set;}
        public String BCompany {get; private set;}
        public String HospitalName {get; private set;}
        
        private String returnNewStr(String hospitalName){
            String hospitalNames = '';
            if(hospitalName.contains('/')){
                Integer index = hospitalName.lastIndexOf('/');
                hospitalNames = hospitalName.substring(0,index)+'<br/>'+hospitalName.substring(index+1);
            }else{
                if(hospitalName.length()>22){
                    hospitalNames = hospitalName.substring(0,22)+'<br/>'+hospitalName.substring(22);
                }else{
                    hospitalNames = hospitalName;
                }
                
            }
            return hospitalNames;
        }
        
        public EstimateInfo(List<Maintenance_Contract_Estimate__c> estimateList) {
            if (estimateList.size() > 0) {
                this.estimate = estimateList[0];
                this.assetInfoList = new List<AssetInfo>();
                this.BCompany = companyApiMap.get(estimate.Maintenance_Contract__r.SalesOfficeCode_selection__c);
                String Hospital = estimate.Maintenance_Contract__r.Hospital__r.Name;
                
                this.HospitalName = returnNewStr(Hospital);
            }
        }
        public void addAssetInfo(Integer lno, Maintenance_Contract_Asset_Estimate__c mcae, Integer nameMax, Integer commentMax) {
            this.assetInfoList.add(new AssetInfo(lno, mcae, estimate, nameMax, commentMax));
        }
    }
                                   
    /**
     * 印刷するデータを格納するオブジェクを定義する、子供
     */
    public class AssetInfo {
        public Integer lineNo {get; private set;}
        public Maintenance_Contract_Asset_Estimate__c mcae {get; private set;}
        public String assetModelNo {get; private set;}
        public String assetName {get; private set;}
        public String assetSerialNumber {get; private set;}
        public String assetComment {get; private set;}
        //public boolean NeedHide {get;private set;}
        public AssetInfo() {
            this.mcae = null;
        }
        

        private String Substr(Integer length, String parameter){
            String params = '';
            Integer size = (parameter.length() / length) + (Math.mod(parameter.length(), length) > 0 ? 1 :0);
            if(size == 0){
                size = 1;
            }
            for(Integer I =0; I<size;I++){
                String s;
                if(I == (size-1)){
                    s = parameter.substring(I*length,parameter.length());
                }else{
                    s = parameter.substring(I*length,(I+1)*length)+'<br/>';
                }
                
                params += s;
            }
            return params;
        }


        public AssetInfo(Integer lineNo, Maintenance_Contract_Asset_Estimate__c mcae, Maintenance_Contract_Estimate__c estimate, Integer nameMax, Integer commentMax) {
            this.lineNo = lineNo;
            this.mcae = mcae;

            //this.NeedHide = HideOrNot;
            if (mcae.Asset__c != null) {
                // Assetある
                this.assetName = mcae.Asset__r.Name+'';
                this.assetSerialNumber = mcae.Asset__r.SerialNumber;
            } else {
                // 手入力
                this.assetName = mcae.Product_Manual__r.Name+'';
                this.assetSerialNumber = '新购入';
            }
            // 名前 ':' の対応
            this.assetName = assetName == null ? '' : assetName;
            String assetModelNotemp;
            String assetNametemp;
            if (this.assetName.indexOf(':') >= 0) {
                assetModelNotemp = this.assetName.subString(0, this.assetName.indexOf(':'));
                assetNametemp = this.assetName.subString(this.assetName.indexOf(':')+1);
            }
            else if (this.assetName.indexOf('：') >= 0) {
                assetModelNotemp = this.assetName.subString(0, this.assetName.indexOf( '：'));
                assetNametemp = this.assetName.subString(this.assetName.indexOf('：')+1);
            }
            else {
                this.assetModelNo = '';
            }
            this.assetModelNo  = assetModelNotemp == null ? '' : assetModelNotemp;
            //this.assetModelNo = Substr(modelNoMax,assetModelNotemp);
            assetNametemp = assetNametemp == null ? '' : assetNametemp;
            this.assetName = Substr(nameMax,assetNametemp);
            String assetCommenttemp = mcae.Comment__c == null ? '' : mcae.Comment__c;
            this.assetComment = Substr(commentMax,assetCommenttemp);



        }
    }
}