public with sharing class NewDBMCAgentPDFAdnMceConfigController {

    public List<String> TopProductModel =new List<String>();
    public EstimateInfo targetObj { get; private set; }
    public List<EstimateInfo> targetObjList { get; private set; }
    public String  RecordTypeName { get; private set; }
    private Integer nameMax = 23;
    private Integer rowSize = 35; 
    private Integer commentMax = 5;
    private Integer lineNo = 0;
    public Integer year { get; private set; }
    public String flag { get; private set; }
    public Boolean ETCDBMC { get; private set; }

    public Integer getTargetObjSize() {
        return this.targetObjList.size();
    }
    public NewDBMCAgentPDFAdnMceConfigController() {


    }
    public NewDBMCAgentPDFAdnMceConfigController(ApexPages.StandardController controller) {
    }
    public void init() {
        TopProductModel.add('CF-LV1I');
        TopProductModel.add('CF-LV1L');
        TopProductModel.add('CV-V1');
        TopProductModel.add('GIF-LV1');
        TopProductModel.add('OER-AW');
        TopProductModel.add('OER-A');
        // 获取合同ID
        String MCId = ApexPages.currentPage().getParameters().get('id');
        List<MaintanceContractPack__c> Mc = [select id,
                                              name,
                                              Estimation_Id__c,
                                              Estimation_Id__r.Estimate_Target__c,Contract_Type__c,
                                              SalesOfficeCode_selection__c,
                                              Management_Code__c,
                                              FieldRequest_quotation_Amount__c,
                                              Total_FieldRequest_quotation_In_Words__c,
                                              Small_Repair_Time__c,
                                              Big_Repair_Time__c,
                                              Inspection_Time__c,
                                              Negotiate_Mean__c,
                                              First_Party_Contract_Number__c,
                                              Term_Of_Payment__c,
                                              one_off_payment_agreed_period__c
                                              from
                                              MaintanceContractPack__c
                                              where id =:MCId];
        if (Mc[0].Estimation_Id__c == null) {
            throw new ControllerUtil.myException('该合同没有decide');
        }
        //小合同
                List<Maintenance_Contract__c> MCList = [select
                                                        id,
                                                        Name,
                                                        Department_Class__r.Name,
                                                        Department__r.Name,
                                                        Service_Contract_Staff__c,
                                                        Payment_Plan_Sum_First__c,
                                                        Payment_Plan_Date_First__c,
                                                        Payment_Plan_Sum_Fifth__c,
                                                        Payment_Plan_Date_Fifth__c,
                                                        Payment_Plan_Sum_Third__c,
                                                        Payment_Plan_Date_Third__c,
                                                        Payment_Plan_Sum_Forth__c,
                                                        Payment_Plan_Date_Forth__c,
                                                        Payment_Plan_Sum_Second__c,
                                                        Payment_Plan_Date_Second__c,
                                                        Payment_Plan_Sum_Sixth__c,
                                                        Payment_Plan_Date_Sixth__c,
                                                        MainLeaderManager__c,
                                                        Dealer__r.Name,
                                                        Service_Contract_Staff__r.JingliApprovalManager__c,
                                                        User_Salesdepartment__c,
                                                        User_Salesdepartment_Sec__c,
                                                        Service_Contract_Staff__r.Salesdepartment__c,
                                                        Small_Repair_Time__c,
                                                        Big_Repair_Time__c,
                                                        Live_Technical_Support_Time__c,
                                                        Engineer_Name__c,
                                                        Phone_Number__c,
                                                        Tour_Check__c,
                                                        Inspection_Time__c,
                                                        Dedust__c,
                                                        Negotiate_Mean__c,
                                                        First_Party_Contract_Number__c,
                                                        Second_Party_Contract_Number__c,
                                                        Term_Of_Payment__c,
                                                        one_off_payment_agreed_period__c,
                                                        Contract_Amount__c,
                                                        Total_Contract_Amount_In_Words__c,
                                                        Service_Contract_Staff__r.Name,
                                                        Total_Payment_Time__c,
                                                        Payment_Plan_Sum_First_in_Word__c,
                                                        Payment_Plan_Sum_Second_in_Word__c,
                                                        Payment_Plan_Sum_Third_in_Word__c,
                                                        Payment_Plan_Sum_Forth_in_Word__c,
                                                        Payment_Plan_Sum_Fifth_in_Word__c,
                                                        Payment_Plan_Sum_Sixth_in_Word__c,
                                                        Estimation_Id__c,
                                                        SalesOfficeCode_selection__c,
                                                        Hospital__r.Name,
                                                        Management_Code__c,
                                                        Contract_Start_Date__c,
                                                        Contract_End_Date__c,
                                                        Total_Contract_Number__c,
                                                        Is_New_Contract__c,
                                                        Hospital__c,
                                                        Estimate_Asset_Cnt__c
                                                        from
                                                        Maintenance_Contract__c
                                                        where
                                                        MaintanceContractPack__c = :MCId order by Management_Code__c ASC];
        // 判断 合同是否存在                                      
        if (Mc.size() == 0) {
            throw new ControllerUtil.myException('维修合同不存在');
        }
        ETCDBMC = false;
        if (Mc[0].Estimation_Id__r.Estimate_Target__c.equals('医院') && Mc[0].Contract_Type__c.equals('服务合同')) {
            ETCDBMC = true;
        }
        // 合同存在 通过最新确认的报价获取报价编码id
        List<MaintanceContractPackEstimate__c> MCPE = [select id,
                                                        name,
                                                        Maintenance_Contract_Estimate__c
                                                        from
                                                        MaintanceContractPackEstimate__c
                                                        where id = :Mc[0].Estimation_Id__c];
        List<String> splitValues = new List<String>();
        if (MCPE[0].Maintenance_Contract_Estimate__c.contains(',')) {
             // 将 合同报价编码 进行切割 并查询
             splitValues = MCPE[0].Maintenance_Contract_Estimate__c.split(',');
        }else {
            splitValues.add(MCPE[0].Maintenance_Contract_Estimate__c);
        }
        if (splitValues.size() == 0 ) {
            throw new ControllerUtil.myException('该合同尚未报价，请报价后在行打印');
        }
        //    System.debug(splitValues);
        // 通过合同报价编码 找到合同编号id
        // new List<Maintenance_Contract_Estimate__c>();
        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,
                                                                    RecordType.DeveloperName
                                                                    FROM Maintenance_Contract_Estimate__c WHERE name in :splitValues];

       this.targetObj = new EstimateInfo(mceList,Mc,MCList);
       targetObjList = new List<EstimateInfo>();
       EstimateInfo tmpTargetObj = new EstimateInfo(mceList,Mc,MCList);
       RecordTypeName = mceList[0].RecordType.DeveloperName;

       // 通过合同编号获取设备
            List<String> mceIdList = new List<String>();
            List<Maintenance_Contract_Asset_Estimate__c> listName =new List<Maintenance_Contract_Asset_Estimate__c>();
            for (Maintenance_Contract_Estimate__c mce : mceList) {
                mceIdList.add(mce.Id);
            }
            List<Maintenance_Contract_Asset_Estimate__c> MaintenanceCAE = [select Id, Name, Asset__c, Maintenance_Contract_Estimate__r.Department__c,
                                                                                Asset__r.OwnershipMachine_No__c,
                                                                                Product_Manual__r.Asset_Model_No__c,
                                                                                Asset__r.Name, Asset__r.SerialNumber, Asset__r.InstallDate,
                                                                                Maintenance_Contract_Estimate__r.Maintenance_Contract__r.Management_Code__c,
                                                                                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
                                                                                from Maintenance_Contract_Asset_Estimate__c
                                                                                where Maintenance_Contract_Estimate__c in :mceIdList
                                                                                order by Maintenance_Contract_Estimate__r.Maintenance_Contract__r.Management_Code__c ASC];

            for(Maintenance_Contract_Asset_Estimate__c tarAsse : MaintenanceCAE){
                listName.add(tarAsse);
            }
            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>();
            Integer cnt = 0;
            for(Maintenance_Contract_Asset_Estimate__c tarAsse : listName){
                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);
            listName=topAsset;
            for(Maintenance_Contract_Asset_Estimate__c mcae :listName) {
                // 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 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;
                }
                Integer icnt = iname;
                if (iname < icomment) {
                    icnt = icomment;
                }
                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,Mc,MCList);
                }
                lineNo += 1;
                tmpTargetObj.addAssetInfo(lineNo, mcae, nameMax,commentMax);
            }
            if (tmpTargetObj.assetInfoList.size() > 0) {
                targetObjList.add(tmpTargetObj);
            }
            
            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;
            }
            System.debug('打印结果：'+tmpTargetObj);
    }
    private static Map<String, String> companyApiMap = new Map<String, String> {
        '北京RC' => '奥林巴斯（北京）销售服务有限公司',
        '上海RC' => '奥林巴斯（北京）销售服务有限公司上海分公司',
        '广州RC' => '奥林巴斯（北京）销售服务有限公司广州分公司',
        '沈阳RC' => '奥林巴斯（北京）销售服务有限公司沈阳分公司',// 2024-3-11 WYL 	DB202403065302 update
        //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;}
        public Maintenance_Contract__c MC {get; private set;}
        public List<Maintenance_Contract__c> MCL {get; private set;}
        public MaintanceContractPack__c MCD {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, List<MaintanceContractPack__c> Mc, List<Maintenance_Contract__c> MCList) {
            if (estimateList.size() > 0) {
                this.MCL = MCList;// 小合同
                this.MC = MCList[0];
                this.MCD = Mc[0];
                this.estimate = estimateList[0];
                this.assetInfoList = new List<AssetInfo>();
                this.BCompany = companyApiMap.get(MCD.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 String Management_Code {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.Management_Code = mcae.Maintenance_Contract_Estimate__r.Maintenance_Contract__r.Management_Code__c;
            // 名前 ':' の対応
            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);
        }
    }
}