/**
 * 2023-04-07  
 * 批量选择修理LWC处理
 */
public with sharing class lexBatchSelectRepairLWCController {

    public static List<Repair__c> RepairList;
    public static List<RepairData> RAInfoList;
    public static List<String> repairIdList;
    // public static String pdfURL;

    //查询Repair数据
    @AuraEnabled
    public static ReturnData search(String json) {

        //2023/04/07 LWC
        ReturnData returnData = new ReturnData();
        RetrievalData RevalInfo = (RetrievalData)System.JSON.deserialize(json,RetrievalData.class);
        System.debug(LoggingLevel.INFO, '*** RevalInfo: ' + RevalInfo);

        //pageController 逻辑
        RepairList = new List<Repair__c>();
        RAInfoList = new List<RepairData>();
        if(String.isBlank(RevalInfo.Status1) && String.isBlank(RevalInfo.Status2) && String.isBlank(RevalInfo.RepairName) && String.isBlank(RevalInfo.SAPRepairNo) 
            && String.isBlank(RevalInfo.SerialNumber) && String.isBlank(RevalInfo.repair.Incharge_Staff__c) && String.isBlank(RevalInfo.onSiteRepair)
            && String.isBlank(String.valueOf(RevalInfo.repair.Aware_date__c)) && String.isBlank(String.valueOf(RevalInfo.repair.Aware_date2__c)) && String.isBlank(RevalInfo.workLocationSelect)
            && String.isBlank(RevalInfo.State_Hospital)){
            // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '请至少添加一个检索条件!'));
            return null;
        }
        // 2023/04/10 add 型号，修理委托者 名称
        String sql = 'select Id, Name, SAP_Service_Repair_No__c, Status1__c, Status2__c, Delivered_Product__c, SerialNumber__c, Delivered_Product__r.Name,Incharge_Staff__r.Name,';
        sql += 'HP_Name__c, State_Hospital__c, Incharge_Staff__c, FSE_ApplyForRepair_Day__c, work_location_select__c, On_site_repair__c,';
        sql += 'Number_of_EffectiveContract__c, NewProductGuaranteeObject__c from Repair__c where Id != null ';
        if(String.isNotBlank(RevalInfo.Status2)){
            sql += ' and Status2__c = \'' + RevalInfo.Status2 + '\'';
        }
        if(String.isNotBlank(RevalInfo.Status1)){
            sql += ' and Status1__c = \'' + RevalInfo.Status1 + '\'';
        }
        if(String.isNotBlank(RevalInfo.HospitalName)){

            sql += ' and HP_Name__c like \'%' + RevalInfo.HospitalName.trim() + '%\'';
        }
        if(String.isNotBlank(RevalInfo.RepairName)){
            System.debug(LoggingLevel.INFO, '***RevalInfo.RepairName.contains(): ' + RevalInfo.RepairName.contains(' '));
            String splitStr = null;
            if(RevalInfo.RepairName.contains(' ')){
                splitStr = ' ';
            }else if(RevalInfo.RepairName.contains(',')){
                splitStr = ',';
            }
            if(splitStr != null && RevalInfo.RepairName.contains(splitStr)){
                sql += ' and (';
                list <String> nameList = RevalInfo.RepairName.split(splitStr);
                for(String name: nameList){
                   sql += 'Name like \'%' + name + '%\' or ';
                }
                sql = sql.removeEnd('or ');
                sql += ')';
            }else{
                sql += ' and Name like \'%' + RevalInfo.RepairName.trim() + '%\'';
            }
            System.debug(LoggingLevel.INFO, '*** sql: ' + sql);
        }
        if(String.isNotBlank(RevalInfo.SAPRepairNo)){
            System.debug(LoggingLevel.INFO, '***RevalInfo.SAPRepairNo.contains(): ' + RevalInfo.SAPRepairNo.contains(' '));
            String splitStr = null;
            if(RevalInfo.SAPRepairNo.contains(' ')){
                splitStr = ' ';
            }else if(RevalInfo.SAPRepairNo.contains(',')){
                splitStr = ',';
            }
            if(splitStr != null && RevalInfo.SAPRepairNo.contains(splitStr)){
                sql += ' and (';
                
                list <String> noList = RevalInfo.SAPRepairNo.split(splitStr);
                for(String no: noList){
                   sql += 'SAP_Service_Repair_No__c like \'%' + no + '%\' or ';
                }
                sql = sql.removeEnd('or ');
                sql += ')';
            }else{
                sql += ' and SAP_Service_Repair_No__c like \'%' + RevalInfo.SAPRepairNo.trim() + '%\'';
            }
            System.debug(LoggingLevel.INFO, '*** sql: ' + sql);
        }
        if(String.isNotBlank(RevalInfo.SerialNumber)){
            List<String> SerialNumberList = new List<String>();
            if(RevalInfo.SerialNumber.indexOf(',') != -1){
                SerialNumberList = RevalInfo.SerialNumber.split(',');
            }
            System.debug('SerialNumberList1:' + SerialNumberList);
            // 支持模糊查询多个，文本框输入用英文半角逗号分隔
            if(SerialNumberList.size() > 0){
                sql += ' and (SerialNumber__c like \'%';
                Integer i = 0;
                for(String SerialNumber : SerialNumberList){
                    if(i == 0){
                        sql += SerialNumber.trim() + '%\'';
                    }else{
                        sql += 'or SerialNumber__c like \'%' + SerialNumber.trim() + '%\'';
                    }
                    i++;
                }
                sql += ')';
            } else{
                sql += ' and SerialNumber__c like \'%' + RevalInfo.SerialNumber.trim() + '%\'';
            }
        }
        if(String.isNotBlank(RevalInfo.repair.Incharge_Staff__c)){
            sql += ' and Incharge_Staff__c = \'' + RevalInfo.repair.Incharge_Staff__c + '\'';
        }
        if(String.isNotBlank(String.valueof(RevalInfo.repair.Aware_date__c))&&String.isNotBlank(String.valueof(RevalInfo.repair.Aware_date2__c))){
            String day = String.valueof(RevalInfo.repair.Aware_date__c);
            String day2 = String.valueof(RevalInfo.repair.Aware_date2__c);
            day = day.substring(0,10);
            day2 = day2.substring(0,10);
            sql += ' and FSE_ApplyForRepair_Day__c >= ' + day + 'and FSE_ApplyForRepair_Day__c <=' +day2;
        }
        if(String.isNotBlank(RevalInfo.onSiteRepair)){
            sql += ' and On_site_repair__c = \'' + RevalInfo.onSiteRepair + '\'';
        }
        if(String.isNotBlank(RevalInfo.workLocationSelect)){
            List<String> workLocationSelectList = new List<String>();
            if(RevalInfo.workLocationSelect.indexOf(',') != -1){
                workLocationSelectList = RevalInfo.workLocationSelect.split(',');
            }
            System.debug('workLocationSelectList1:' + workLocationSelectList);
            if(workLocationSelectList.size() > 0){
                sql += ' and (work_location_select__c like \'%';
                Integer i = 0;
                for(String workLocationSelect : workLocationSelectList){
                    if(i == 0){
                        sql += workLocationSelect.trim() + '%\'';
                    }else{
                        sql += 'or work_location_select__c like \'%' + workLocationSelect.trim() + '%\'';
                    }
                    i++;
                }
                sql += ')';
            } else{
                sql += ' and work_location_select__c like \'%' + RevalInfo.workLocationSelect.trim() + '%\'';
            }
        }
        if(String.isNotBlank(RevalInfo.State_Hospital)){
            sql += ' and State_Hospital__c like \'%' + RevalInfo.State_Hospital.trim() + '%\'';
        }
        sql += 'and Status1__c not in(\'0.删除\',\'0.取消\') limit 200';
        System.debug('sql1LWC:' + sql);
        if(String.isNotBlank(sql)){
            RepairList = Database.query(sql);
        }
        if(RepairList.size() == 200){
            // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '检索数据太多,请缩小检索范围！'));
            //2023/04/07 returnData
            returnData.status = '检索数据太多,请缩小检索范围！';
        }
        if(RepairList.size() <= 0){
            // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '没检索到任何修理'));
            //2023/04/07 returnData
            returnData.status = '没检索到任何修理';
            return returnData;
        }
        for(Repair__c ra : RepairList){
            RepairData raData = new RepairData(ra);
            RAInfoList.add(raData);
        }
        // return RAInfoList;

        returnData.repairData = RAInfoList;
        System.debug(LoggingLevel.INFO, '*** returnData: ' + returnData);
        return returnData;
    }

    //打印PDF  
    @AuraEnabled
    public static String showPDF(String json) {
        System.debug(LoggingLevel.INFO, '*** joinshoPDF: ');
        List<Repair__c> RepairList = (List<Repair__c>)System.JSON.deserialize(json,List<Repair__c>.class);

        if(RepairList == null || RepairList.isEmpty()){
            return '请先检索修理';
        }
        repairIdList = new List<String>();
        for(Repair__c rd : RepairList) {
            System.debug(LoggingLevel.INFO, '*** rd: ' + rd);
                repairIdList.add(rd.Id);
        }
        // RepairList = new List<Repair__c>();
        String url = '=';
        /*System.debug('RAInfoList:' + RAInfoList);
        if(RAInfoList == null || RAInfoList.isEmpty()){
            // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '请先检索修理'));
            return '请先检索修理';
        }*/
        /*for(RepairData rd : RAInfoList) {
            System.debug(LoggingLevel.INFO, '*** rd: ' + rd);
            //选中的repair
            if(rd.IFCheck){
                repairIdList.add(rd.repair.Id);
                RepairList.add(rd.repair);
            }
        }*/
        System.debug(LoggingLevel.INFO, '***repairIdList : ' + repairIdList);
        System.debug(LoggingLevel.INFO, '***RepairList : ' + RepairList);
        if(repairIdList.size() > 0){
            if(repairIdList.size() <= 50){
                if(RepairList.size() > 0){
                    System.debug(LoggingLevel.INFO, '*** if size>0 generateAttachment: ');
                    generateAttachment(RepairList);
                }
                for(String Id : repairIdList){
                    url += Id + '=';
                }
                url = url.substring(0, url.lastIndexOf('='));
                // PageReference pageRef = new PageReference('/apex/MaintenanceCommissionPDF?id' + url);
                // pageRef.setRedirect(true);
                // return pageRef;
                String pdfURL = '';
                if(isSandbox()){
                    pdfURL = 'https://ocsm--stagefull--c.visualforce.com/apex/MaintenanceCommissionPDF?id' + url;
                } else{
                    pdfURL = 'https://ocsm.my.salesforce.com/apex/MaintenanceCommissionPDF?id' + url;
                }
                return pdfURL;
            } else{
                // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '多单打印最大数量为50,请选择少于50个修理！'));
                return '多单打印最大数量为50,请选择少于50个修理！';
            }
        } else{
            // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '请至少选择一个修理'));
            return '请至少选择一个修理';
        }
    }

    // 生成pdf添加到对应的修理中
    public static PageReference generateAttachment(List<Repair__c> repList){
        System.debug(LoggingLevel.INFO, '*** generateAttachment: ');
        BatchSelectRepairPDFDelete pdf = new BatchSelectRepairPDFDelete();
        pdf.deletePDF(repList);
        pdf.createPDF(repList);
        return null;
    }

    // 判断是否是测试环境
    public static Boolean isSandbox() {
        return [SELECT IsSandbox FROM Organization LIMIT 1].IsSandbox;
    }

    public class RetrievalData {
        @AuraEnabled
        public String Status1;
        @AuraEnabled
        public String Status2;
        @AuraEnabled
        public String RepairName;
        @AuraEnabled
        public String SAPRepairNo;
        @AuraEnabled
        public String SerialNumber;
        @AuraEnabled
        public String onSiteRepair;
        @AuraEnabled
        public String workLocationSelect;
        @AuraEnabled
        public String State_Hospital;
        @AuraEnabled
        public String HospitalName;
        @AuraEnabled
        public Repair__c repair;

        public RetrievalData(){
            repair = new Repair__c();
        }
    }

    public class RepairData {
        @AuraEnabled
        public Boolean IFCheck;
        @AuraEnabled
        public Repair__c repair;
        public RepairData(Repair__c RepairInfo){
            IFCheck = null;
            repair = RepairInfo;
        }
    }
    //2023/04/07 返回查询结果和状态
    public class ReturnData {
        @AuraEnabled
        public String status;
        @AuraEnabled
        public List<RepairData> repairData;
    }
}