/**
 * wangweipeng    2021/08/04
 * 打印点检计划报告书的pdf
 */
public without sharing class PrintInspectupReportPDFController {
    public String loginPerson{get;set;}//当前登录人id
    public String loginPersonName{get;set;}//当前登录人名字
    public String parameter{get;set;}//父页面传过来的参数
    public String produceText {get;set;}//生成类型
    public String assetType{get;set;}//保有设备类型
    public List<String> assetList{get;set;}//保有设备具体内容
    public Boolean isPaging{get;set;}//是否分页
    public Boolean activeOn {get;set;}//洗消信息
    // 230829 zzm 增加显示字段 Diagnosis__c 故障描述 start
    public Boolean onePlan {get;set;}//是否显示故障描述
    // 230829 zzm 增加显示字段 Diagnosis__c 故障描述 end

    public List<String> inspectupPlanIdList {get;set;}//点检计划id
    public String maintenanceContractId{get;set;}//合同id
    public Integer pageCnt{get;set;}//如果分页，那么需要分几页

    //维修合同信息
    public Maintenance_Contract__c maintenanceContract{get;set;}
    //洗消信息
    public Maintenance_Contract__c InspectionReportData{get;set;}
    //产品信息和产品点检信息
    public List<List<DataObject>> listData{get;set;}
    //key
    public List<String> inspectupPlanKey{get;set;}
    //是否展示结果
    public Boolean resultFlag{get;set;}

    public PrintInspectupReportPDFController() {
        //获取当前登录人id
        loginPerson = (Userinfo.getUserId()).substring(0,15);
        //获取当前登录人中文名
        loginPersonName = Userinfo.getName();
        //获取参数
        parameter = System.currentPageReference().getParameters().get('parameter');
        maintenanceContractId = '';//合同id
        produceText = '';//生成类型
        inspectupPlanIdList = new List<String>();//点检信息
        listData = new List<List<DataObject>>();
        maintenanceContract = new Maintenance_Contract__c();
        InspectionReportData = new Maintenance_Contract__c();
        inspectupPlanKey = new List<String>();
        assetList = new List<String>();
        assetType = '';
        activeOn = false;
        isPaging = false;
        pageCnt = 0;
	// 230829 zzm 增加显示字段 Diagnosis__c 故障描述 start
        onePlan = false;
	// 230829 zzm 增加显示字段 Diagnosis__c 故障描述 end
    }
    public PageReference init(){
        //获取参数
        getParameterData();
        try{
            //获取合同数据
            String maintenanceContractSQL = makeTextMaintenanceContractSQl();
            List<Maintenance_Contract__c> mcList = new List<Maintenance_Contract__c>();
            mcList = Database.query(maintenanceContractSQL);
            if (mcList.size() > 0) {
                maintenanceContract = mcList[0];
                InspectionReportData = mcList[0];
            }
            //首先点检计划
            String inspectupPlanSQl = makeTextInspectupPlanSQl();
            List<Inspectup_Plan__c> inspectupPlanList = Database.query(inspectupPlanSQl);
            //存放点检技术的id
            List<String> inspectupPlanId = new List<String>();
            if(inspectupPlanList != null && inspectupPlanList.size() > 0){
                for(Integer i = 0;i< inspectupPlanList.size();i++){
                    inspectupPlanId.add(inspectupPlanList[i].Id);
                    inspectupPlanKey.add(inspectupPlanList[i].Chack_Plan_NO__c+'次点检日');
                }
                               
            }
	    // 230829 zzm 增加显示字段 Diagnosis__c 故障描述 start
            if(inspectupPlanKey.size()==1){
                onePlan = true;
            }
	    // 230829 zzm 增加显示字段 Diagnosis__c 故障描述 end

            //获取点检报告书
            List<Inspection_Report__c> inspectionReportList =new List<Inspection_Report__c>();
            List<String> inspectionReportId = new List<String>();
            if(inspectupPlanId.size() > 0){
                String inspectionReportSQl = makeTextInspectionReportSQl(inspectupPlanId);
                inspectionReportList = Database.query(inspectionReportSQl);
                //存放点检报告书id
                if(inspectionReportList != null && inspectionReportList.size() > 0){
                    for(Integer i =0;i< inspectionReportList.size();i++){
                        inspectionReportId.add(inspectionReportList[i].Id);
                    }
                }
            }
            //获取点检报告书明细，包括设备明细
            List<Inspection_Item__c> inspectionItemList = new List<Inspection_Item__c>();
            System.debug('inspectionReportId：'+ inspectionReportId);
            if(inspectionReportId.size()>0){
                String inspectionItemSQl = makeTestInspectionItemSQl(inspectionReportId);
                System.debug('执行SQL：'+ inspectionItemSQl);
                inspectionItemList = Database.query(inspectionItemSQl);
            }
                        
            //获取维修合同设备信息
            String maintenanceContractAssetSQl = makeTestMaintenanceContractAsset();
            List<Maintenance_Contract_Asset__c> maintenanceContractAssetList = new List<Maintenance_Contract_Asset__c>();
            maintenanceContractAssetList = Database.query(maintenanceContractAssetSQl);

            if(maintenanceContractAssetList != null && maintenanceContractAssetList.size() > 0){
                //分组把保有设备分组
                //由于客户需要有分页功能，所以要首先要进行分组，查询每页展示的是那种类型的数据
                //如果客户没有选择分页，那么就把所有数据放到第一页里面
                List<String> assetNameList = new List<String>();
                //isPaging  是否分页（只有战略科室、科室和装机地点可以分页）  
                //assetList  如果有值，那么证明需要根据里面的数据进行分页
                if(isPaging && assetList.size() > 0){
                    //循环  维修合同/保有设备
                    for(Maintenance_Contract_Asset__c mcac : maintenanceContractAssetList){
                        String grouping = '';
                        //assetType  根据那种类型进行分页
                        if('1'.equals(assetType)){//战略科室分组
                            grouping = mcac.Asset__r.Acc_Department_Class_Name__c;
                        }else if('2'.equals(assetType)){//科室分组
                            grouping = mcac.Asset__r.Department_Name__c;
                        }else if('3'.equals(assetType)){//装机地点分组
                            grouping = mcac.Asset__r.Installation_Site__c;
                        }
                        if(assetNameList.size() > 0){
                            //用于判断在 assetNameList 分组的集合里面是否有重复的
                            boolean assetNameFlag = true;
                            for(String anl : assetNameList){
                                if(anl == grouping){
                                    assetNameFlag = false;
                                }
                            }
                            if(assetNameFlag){
                                if(grouping != ''){
                                    assetNameList.add(grouping);
                                }
                            }
                        }else{
                            if(grouping != ''){
                                assetNameList.add(grouping);
                            }
                        }
                    }
                }

                //不需要分页那么循环一回数据
                //如果 assetNameList 有数据，那么证明是需要给保有设备分页
                //如果没有数据，证明不需要分页，所以只循环一回就可以
                boolean falg = true;
                integer indexA = 0;
                integer indexSize = assetNameList.size();//用于还需要循环几次
                while(indexSize > 0 || falg){
                    falg = false;
                    if(indexSize > 0){
                        indexSize--;
                    }
                    //存放每一页的数据
                    List<DataObject> onePageList = new List<DataObject>();
                    //首先循环设备
                    for(Maintenance_Contract_Asset__c mcac : maintenanceContractAssetList){
                        //存放一条数据
                        DataObject dObj = new DataObject(inspectupPlanIdList);
                        //设备名称
                        String assetName = mcac.Asset__r.name;
                        //由于pdf 页面的宽度有限，那么设备名称太长的话会把表格撑大，所以需要截取换行
                        //目前设定名字长度超过 14个字符时，换行
                        if(assetName != null && assetName != ''){
                            if(assetName.length() > 14){
                                assetName = assetName.substring(0,13)+' \n ' + assetName.substring(13,assetName.length());
                            }
                        }
                        //设备编码
                        String assetNumber = mcac.Asset__r.SerialNumber;
                        dObj.deviceName = assetName;
                        dObj.serialNumber = assetNumber;
                        //判断是否需要分页
                        if(isPaging && assetList.size() > 0){
                            if('1'.equals(assetType)){//战略科室分组
                                if(assetNameList.size() <= 0 || assetNameList[indexA] != mcac.Asset__r.Acc_Department_Class_Name__c){
                                    continue;
                                }
                            }else if('2'.equals(assetType)){//科室分组
                                if(assetNameList.size() <= 0 || assetNameList[indexA] != mcac.Asset__r.Department_Name__c){
                                    continue;
                                }
                            }else if('3'.equals(assetType)){//装机地点分组
                                if(assetNameList.size() <= 0 || assetNameList[indexA] != mcac.Asset__r.Installation_Site__c){
                                    continue;
                                }
                            }
                        }
                        //判断是第几个点检,我们设定最多只能显示4次点检计划
                        integer index = 0;
                        //循环点检计划
                        for(Inspectup_Plan__c ipc : inspectupPlanList){
                            index++;
                            //由于一个设备可能在一个点检计划中多次使用，所以我们只需要获取最新的一个就可以
                            //获取到最新的以后，其他的就不需要了
                            boolean facilityFalg = false;
                            //循环点检报告书
                            System.debug('inspectionReportList数据打印：'+ inspectionReportList);
                            for(Inspection_Report__c irc:inspectionReportList){
                                //跳出循环，我们已经获取到当前设备当前点检计划的最新的结果和检测日
                                if(facilityFalg){
                                    break;
                                }
                                String inspectupPlan = irc.Inspectup_Plan__c;
                                //判断是否是当前点检计划的报告书吗
                                if(ipc.id == inspectupPlan){
                                    //循环点检报告书明细
                                    for(Inspection_Item__c iic : inspectionItemList){
                                        //判断是否是当前的报告书明细
                                        if(irc.id == iic.Inspection_ReportId__c){
                                            String iicAssetId = iic.AssetId__c;
                                            //设备id
                                            String assetId = mcac.Asset__c;
                                            if(iicAssetId != '' && iicAssetId != null && assetId != null && assetId != ''){
                                                iicAssetId = iicAssetId.substring(0,15);
                                                assetId = assetId.substring(0,15);
                                                if(assetId == iicAssetId){//查看设备是否一样
                                                    facilityFalg = true;
                                                    if(irc.Inspection_Date__c != null){
                                                        if(index == 1){
                                                            dObj.spotCheck1 = String.valueOf(irc.Inspection_Date__c);
                                                            // 231220 zzm 增加显示字段 Diagnosis__c 故障描述 --部分数据故障描述为空时报错 start
                                                            if(String.isNotBlank(iic.Diagnosis__c)) {
                                                                String decrible = ConvertString(iic.Diagnosis__c,30,false);
                                                                dObj.diagnosis = decrible;
                                                            } else {
                                                                dObj.diagnosis = '';
                                                            }
                                                           
                                                            // 231220 zzm 增加显示字段 Diagnosis__c --部分数据故障描述为空时报错 故障描述 end
                                                        }else if(index == 2){
                                                            dObj.spotCheck2 = String.valueOf(irc.Inspection_Date__c);
                                                        }else if(index == 3){
                                                            dObj.spotCheck3 = String.valueOf(irc.Inspection_Date__c);
                                                        }else if(index == 4){
                                                            dObj.spotCheck4 = String.valueOf(irc.Inspection_Date__c);
                                                        }
                                                    }
                                                    if(resultFlag){//判断是否需要结果值
                                                        if(iic.ItemStatus__c != '' && iic.ItemStatus__c != null){
                                                            if(index == 1){
                                                                dObj.spocCheckResult1 = iic.ItemStatus__c;
                                                            }else if(index == 2){
                                                                dObj.spocCheckResult2 = iic.ItemStatus__c;
                                                            }else if(index == 3){
                                                                dObj.spocCheckResult3 = iic.ItemStatus__c;
                                                            }else if(index == 4){
                                                                dObj.spocCheckResult4 = iic.ItemStatus__c;
                                                            }
                                                        }
                                                    }
                                                    //跳出循环，我们已经获取到当前设备当前点检计划的最新的结果和检测日
                                                    if(facilityFalg){
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        System.debug('inspect index:' +index);
                        onePageList.add(dObj);
                        
                    }
                    indexA++;
                    listData.add(onePageList);
                }
            }
        }catch(exception e){
            //失败提示
            ApexPages.addMessages(e);
        }
        return null;
    }

    //获取参数的值
    //参数时一个字符串，使用 ,, 两个逗号分割
    //第一个参数：   是否空白单据    
    //第二个参数：设备的限制，分为战略科室、科室、装机地点和机身号
    //第三个参数： 如果第二个参数为战略科室、科室和装机地点，那么就需要选择是那些具体的科室或地点
    //第四个参数: 如果第二个参数为战略科室、科室和装机地点  那么是可以分页的
    //第五个参数：是否需要展示  洗消信息条件
    //第六个参数：点检计划
    //第七个参数：维修合同id
    public void getParameterData(){
        if(parameter != null && parameter != ''){
            List<String> parameterList = parameter.split(',,');
            if(parameterList != null && parameterList.size() == 7){
                produceText = parameterList[0];//生成类型
                //控制结果是否展示
                if('1'.equals(produceText)){//空白单据
                    resultFlag = false;
                }else if('2'.equals(produceText)){//合同全部
                    resultFlag = true;
                }else{
                    resultFlag = false;
                }
                //类型
                //设备 1、战略科室 2、装机地点 3和机身号 4
                assetType = parameterList[1];
                if(assetType != '' && assetType != null){
                    //如果为机身号，那么不需要分页和控制设备的科室不需要
                    if(!'4'.equals(assetType)){
                        //科室、战略科室和装机地点的具体内容
                        String assetStr = parameterList[2];
                        if(assetStr != '' && assetStr != null){
                            if(assetStr.indexOf(',') != -1){
                                assetList = assetStr.split(',');
                            }else{
                                assetList.add(assetStr);
                            }
                            pageCnt = assetList.size();
                        }
                        //是否分页
                        String isPagingStr = parameterList[3];
                        if(isPagingStr == 'true'){
                            isPaging = true;
                        }
                    }
                }
                //洗消信息
                String falgStr = parameterList[4];
                if(falgStr == 'true'){
                    activeOn = true;
                }
                //点检计划id
                String inspectupPlan = parameterList[5];
                if(inspectupPlan != null && inspectupPlan != ''){
                    if(inspectupPlan.indexOf(',') != -1){
                        inspectupPlanIdList = inspectupPlan.split(',');
                    }else{
                        inspectupPlanIdList.add(inspectupPlan);
                    }
                }
                maintenanceContractId = parameterList[6];//合同id
            }
        }
    }

    //查询合同单信息
    public String makeTextMaintenanceContractSQl(){
        String maintenanceContractSQL = 'SELECT ID,NAME,Hospital__c,Hospital__r.Name,Department__c,Department__r.Name,Maintenance_Contract_No__c '
                                    +' ,CleaningFluid__c,SterilizationMethod__c,Remarks__c,Disinfectant__c,UsedMachine__c,Used_ET__c,Mode__c'
                                    +' FROM Maintenance_Contract__c WHERE id = :maintenanceContractId ';
        return maintenanceContractSQL;
    }
    
    //获取点检计划
    public String makeTextInspectupPlanSQl(){
        String inspectupPlanSQl = 'select id,name,Chack_Plan_NO__c  from Inspectup_Plan__c  where Maintenance_Contract__c = :maintenanceContractId  and id in :inspectupPlanIdList ';
        return inspectupPlanSQl;
    }
    //获取点检报告书
    //根据检测日时从大到小排序,如果检测日相同，再根据申请日排序
    public String makeTextInspectionReportSQl(List<String> inspectupPlanId){
        String inspectionReportSQl = 'SELECT ID,NAME,Contract__c,Inspectup_Plan__c,Others__c,Contract__r.name,Inspection_Date__c,CleaningFluid__c,Mode__c,SterilizationMethod__c,Remarks__c,Disinfectant__c,UsedMachine__c,Used_ET__c '
                                + ' from Inspection_Report__c where Inspectup_Plan__c in :inspectupPlanId and Status__c = \'批准\' '
                                + ' order by Inspection_Date__c desc,Submit_date__c desc';
        return inspectionReportSQl;
    }

    //获取点检报告书明细
    public String makeTestInspectionItemSQl(List<String> inspectionReportId){
        // 230829 zzm 增加显示字段 Diagnosis__c 故障描述 start
        String inspectionItemSQl = 'select Diagnosis__c, id,name,ItemStatus__c,AssetId__c,AssetId__r.name,SerialNumber__c,Inspection_ReportId__c from Inspection_Item__c '
                                + ' where Inspection_ReportId__c in :inspectionReportId ';
        // 230829 zzm 增加显示字段 Diagnosis__c 故障描述 end

        return inspectionItemSQl;
    }

    //获取点检的设备
    //Check_object__c = true and
    public String makeTestMaintenanceContractAsset(){
        String maintenanceContractAssetSQl = 'select id,name,Asset__c,Asset__r.name,Asset__r.SerialNumber,Asset__r.Strategic_department_Class_Name__c,Asset__r.Acc_Department_Class_Name__c,Asset__r.Department_Name__c,Asset__r.Installation_Site__c '
                                        +' from Maintenance_Contract_Asset__c '
                                        +' where Maintenance_Contract__c = :maintenanceContractId and isdianjian__c != 0 ';
        //保有设备的筛选条件
        if(assetType != '' && assetType != null){
            //战略科室
            if('1'.equals(assetType)){
                if(assetList != null && assetList.size() > 0){
                    maintenanceContractAssetSQl += ' and Asset__r.Acc_Department_Class_Name__c in :assetList ';
                }
            }else if('2'.equals(assetType)){//科室
                if(assetList != null && assetList.size() > 0){
                    maintenanceContractAssetSQl += ' and Asset__r.Department_Name__c in :assetList ';
                }
            }else if('3'.equals(assetType)){//装机地点
                if(assetList != null && assetList.size() > 0){
                    maintenanceContractAssetSQl += ' and Asset__r.Installation_Site__c  in :assetList ';
                }
            }else if('4'.equals(assetType)){//机身号

            }

            //是否需要分页
            if(isPaging){
                if('1'.equals(assetType)){//战略科室分页
                    maintenanceContractAssetSQl += ' order by Asset__r.Acc_Department_Class_Name__c desc ';
                }else if('2'.equals(assetType)){//科室分页
                    maintenanceContractAssetSQl += ' order by Asset__r.Department_Name__c desc ';
                }else if('3'.equals(assetType)){//装机地点分页
                    maintenanceContractAssetSQl += ' order by Asset__r.Installation_Site__c desc ';
                }else{
                   maintenanceContractAssetSQl += ' order by Asset__r.Acc_Department_Class_Name__c desc,Asset__r.Department_Name__c desc '; 
                }
            }else{
                maintenanceContractAssetSQl += ' order by Asset__r.Acc_Department_Class_Name__c desc,Asset__r.Department_Name__c desc '; 
            }
        }else{
            maintenanceContractAssetSQl += ' order by Asset__r.Acc_Department_Class_Name__c desc,Asset__r.Department_Name__c desc '; 
        }
        return maintenanceContractAssetSQl;
    }
    // 230829 zzm 增加显示字段 Diagnosis__c 故障描述 start
    /**
       方法名: ConvertString
       功能说明: 字符串添加换行符
       参数说明： str（需添加换行字符串）num(每行字符数),issegmentation(是否分割字符串)
       返回值：换行后字符串
    **/
    public  String ConvertString(String str, Integer num, boolean issegmentation) {
        num=(num/11*7);
        List<String> proDecList = new List<String>();
        if (issegmentation) {
            proDecList = str.split('\\*');
        }else {
            proDecList.add(str);
        }
        system.debug('str');
        system.debug(str);
        system.debug(proDecList);
        String converStr = '';
        for (String proDec : proDecList) {
            String strword = proDec;
            Decimal leng = 0;
            String tmp = '';
            Integer j = 1;
            Integer k = 0;
            Decimal z = num;
            
            for (Integer i=0; i < strword.length(); i++) {
                // System.debug(LoggingLevel.INFO, '*** z: ' + z);
               
                if ((strword.charAt(i) >= 19968 && strword.charAt(i) <= 171941) 
                    || (strword.charAt(i) == 64) 
                    || (strword.charAt(i) == 12289)) {
                      leng = leng + 2;
                }
                else if (strword.charAt(i) == 109) {
                    leng = leng + 1.5;
                }
                else if ((strword.charAt(i) >= 60 && strword.charAt(i) <= 122 ) ){
                    leng = leng + 1.6;
                }
                else if ((strword.charAt(i) == 49) 
                    || (strword.charAt(i) == 105) 
                    || (strword.charAt(i) == 106) 
                    || (strword.charAt(i) == 108)  
                    || (strword.charAt(i) == 116)){
                    leng = leng + 0.6;
                }
                  else if ((strword.charAt(i) == 46) || (strword.charAt(i) == 58)){
                    leng = leng + 0.4;
                }
                else if (strword.charAt(i) >= 48 && strword.charAt(i) <= 57){
                    leng = leng + 1.1;
                }
                else if (strword.charAt(i) == 95){
                    leng = leng + 1;
                }
                else{
                    leng = leng + 1.1;
                }

                //如果数据大与给定的Number增加<br/>
                if (leng >= z){     
                    tmp = tmp + strword.mid(k,j) + '\n';
                    leng = 0;
                    j = 0;
                    k = i+1;
                }

                if (i == (strword.length() - 1)){     
                    if (issegmentation) {
                        tmp = tmp + strword.mid(k,j+1)+'<br/><br/>';
                    }else {
                        tmp = tmp + strword.mid(k,j+1);
                    }
                }

                j++;
                // System.debug(LoggingLevel.INFO, '*** tmp: ' + tmp);
            }
            converStr += tmp;
        }
        // System.debug(LoggingLevel.INFO, '*** : converStr' + converStr);
        return converStr;
    }
    // 230829 zzm 增加显示字段 Diagnosis__c 故障描述 end

    /**
     * 为了方便前段table获取值
     */
    class DataObject {
        public String deviceName{ get; private set; }//产品名
        public String serialNumber{ get; private set; }//机身号
        public String spotCheck1{ get; private set; }//点检1
        public String spocCheckResult1{get;set;}//结果1
        public String spotCheck2{ get; private set; }//点检2
        public String spocCheckResult2{get;set;}//结果2
        public String spotCheck3{ get; private set; }//点检3
        public String spocCheckResult3{get;set;}//结果3
        public String spotCheck4{ get; private set; }//点检4
        public String spocCheckResult4{get;set;}//结果4
        //230830 zzm 故障描述 start
        public String diagnosis{get;set;}//故障描述
        //230830 zzm 故障描述 end

        public DataObject(){
            deviceName = ' ';
            serialNumber = ' ';
        }
        //全部初始化一下，用于占位
        public DataObject(List<String> inspectupPlanIdList) {
            deviceName = ' ';
            serialNumber = ' ';
            if(inspectupPlanIdList != null && inspectupPlanIdList.size() > 0){
                //控制初始化几个点检计划
                if(inspectupPlanIdList.size() >= 1){
                    spotCheck1 = ' ';
                    spocCheckResult1 = ' ';
                }
               
                if(inspectupPlanIdList.size() >= 2){
                    spotCheck2 = ' ';
                    spocCheckResult2 = ' ';
                }
                if(inspectupPlanIdList.size() >= 3){
                    spotCheck3 = ' ';
                    spocCheckResult3 = ' ';
                }
                if(inspectupPlanIdList.size() == 4){
                    spotCheck4 = ' ';
                    spocCheckResult4 = ' ';
                }
            }
        }
    }

   
    
}