public with sharing class BatchSelectRepairPageController {
    public RetrievalData RevalInfo { get; set; }
    public List<RepairData> RAInfoList { get; set; }
    public List<Repair__c> RepairList { get; set; }
    public List<String> repairIdList{ get; set; }
    public List<SelectOption> StatusItems1 { get; private set; }
    public List<SelectOption> StatusItems { get; private set; }
    public List<SelectOption> SiteRepairItems { get; private set; }
    public String pdfURL { get; private set; }
    public Integer RACount {
        get { return RAInfoList == null ? 0 : RAInfoList.size(); }
    }

    public BatchSelectRepairPageController() {
        StatusItems = new List<SelectOption>();
        StatusItems.add(new SelectOption('','--无--'));
        StatusItems.add(new SelectOption('00.申请完毕','00.申请完毕'));
        StatusItems.add(new SelectOption('01.分公司受理完毕','01.分公司受理完毕'));
        StatusItems.add(new SelectOption('02.RC受理完毕','02.RC受理完毕'));
        StatusItems.add(new SelectOption('03.报价检查结束','03.报价检查结束'));
        StatusItems.add(new SelectOption('04.报价跟进中','04.报价跟进中'));
        StatusItems.add(new SelectOption('05.报价同意完备','05.报价同意完备'));
        StatusItems.add(new SelectOption('06.零件齐备','06.零件齐备'));
        StatusItems.add(new SelectOption('07.修理開始','07.修理開始'));
        StatusItems.add(new SelectOption('08.修理预计完成','08.修理预计完成'));
        StatusItems.add(new SelectOption('09.修理完成','09.修理完成'));
        StatusItems.add(new SelectOption('10.最终检查完成','10.最终检查完成'));
        StatusItems.add(new SelectOption('11.RC修理品已返送','11.RC修理品已返送'));
        StatusItems.add(new SelectOption('12.发票已发送','12.发票已发送'));
        StatusItems.add(new SelectOption('13.已返送到用户','13.已返送到用户'));
        StatusItems.add(new SelectOption('14.收到验收单','14.收到验收单'));
        StatusItems.add(new SelectOption('15.验收单签收复核通过','15.验收单签收复核通过'));
        StatusItems.add(new SelectOption('16.部分付款','16.部分付款'));
        StatusItems.add(new SelectOption('16.完毕','16.完毕'));
        StatusItems.add(new SelectOption('17.付款完毕','17.付款完毕'));
        StatusItems.add(new SelectOption('00.取消','00.取消'));
        StatusItems.add(new SelectOption('00.删除','00.删除'));
        StatusItems.add(new SelectOption('00.关闭','00.关闭'));

        StatusItems1 = new List<SelectOption>();
        StatusItems1.add(new SelectOption('','--无--'));
        StatusItems1.add(new SelectOption('0.申请完毕','0.申请完毕'));
        StatusItems1.add(new SelectOption('2.维修报价阶段','2.维修报价阶段'));
        StatusItems1.add(new SelectOption('3.维修阶段','3.维修阶段'));
        StatusItems1.add(new SelectOption('4.修理品返送阶段','4.修理品返送阶段'));
        StatusItems1.add(new SelectOption('5.完毕','5.完毕'));
        StatusItems1.add(new SelectOption('0.删除','0.删除'));
        StatusItems1.add(new SelectOption('0.取消','0.取消'));
    
        SiteRepairItems = new List<SelectOption>();
        SiteRepairItems.add(new SelectOption('','--无--'));
        SiteRepairItems.add(new SelectOption('RC修理','RC修理'));
        SiteRepairItems.add(new SelectOption('直送SORC修理','直送SORC修理'));
        SiteRepairItems.add(new SelectOption('直送OGZ修理','直送OGZ修理'));
        SiteRepairItems.add(new SelectOption('办事处修理','办事处修理'));
        SiteRepairItems.add(new SelectOption('现场修理','现场修理'));

        
       
      
    }

    public void init(){
        RevalInfo = new RetrievalData();
    }

    // public List<SelectOption> getworkLocationSelect() {
    //     List<SelectOption> workLocationSelect = new List<SelectOption>();
    //     workLocationSelect.add(new SelectOption('','--无--'));
    //     workLocationSelect.add(new SelectOption('北京办事处','北京办事处'));
    //     workLocationSelect.add(new SelectOption('天津办事处','天津办事处'));
    //     workLocationSelect.add(new SelectOption('河北办事处','河北办事处'));
    //     workLocationSelect.add(new SelectOption('济南办事处','济南办事处'));
    //     workLocationSelect.add(new SelectOption('青岛办事处','青岛办事处'));
    //     workLocationSelect.add(new SelectOption('内蒙办事处','内蒙办事处'));
    //     workLocationSelect.add(new SelectOption('黑龙江办事处','黑龙江办事处'));
    //     workLocationSelect.add(new SelectOption('吉林办事处','吉林办事处'));
    //     workLocationSelect.add(new SelectOption('沈阳办事处','沈阳办事处'));
    //     workLocationSelect.add(new SelectOption('大连办事处','大连办事处'));
    //     workLocationSelect.add(new SelectOption('陕西办事处','陕西办事处'));
    //     workLocationSelect.add(new SelectOption('青海办事处','青海办事处'));
    //     workLocationSelect.add(new SelectOption('宁夏办事处','宁夏办事处'));
    //     workLocationSelect.add(new SelectOption('甘肃办事处','甘肃办事处'));
    //     workLocationSelect.add(new SelectOption('新疆办事处','新疆办事处'));
    //     workLocationSelect.add(new SelectOption('山西办事处','山西办事处'));
    //     workLocationSelect.add(new SelectOption('河南办事处','河南办事处'));
    //     workLocationSelect.add(new SelectOption('上海办事处','上海办事处'));
    //     workLocationSelect.add(new SelectOption('江苏办事处','江苏办事处'));
    //     workLocationSelect.add(new SelectOption('江西办事处','江西办事处'));
    //     workLocationSelect.add(new SelectOption('浙江办事处','浙江办事处'));
    //     workLocationSelect.add(new SelectOption('安徽办事处','安徽办事处'));
    //     workLocationSelect.add(new SelectOption('福建办事处','福建办事处'));
    //     workLocationSelect.add(new SelectOption('广东办事处','广东办事处'));
    //     workLocationSelect.add(new SelectOption('深圳办事处','深圳办事处'));
    //     workLocationSelect.add(new SelectOption('湖北办事处','湖北办事处'));
    //     workLocationSelect.add(new SelectOption('湖南办事处','湖南办事处'));
    //     workLocationSelect.add(new SelectOption('云南办事处','云南办事处'));
    //     workLocationSelect.add(new SelectOption('贵州办事处','贵州办事处'));
    //     workLocationSelect.add(new SelectOption('四川办事处','四川办事处'));
    //     workLocationSelect.add(new SelectOption('重庆办事处','重庆办事处'));
    //     workLocationSelect.add(new SelectOption('杭州办事处','杭州办事处'));
    //     workLocationSelect.add(new SelectOption('杭州共通办事处','杭州共通办事处'));
    //     workLocationSelect.add(new SelectOption('西安办事处','西安办事处'));
    //     workLocationSelect.add(new SelectOption('西安共通办事处','西安共通办事处'));
    //     workLocationSelect.add(new SelectOption('共通办事处','共通办事处'));
    //     workLocationSelect.add(new SelectOption('成都办事处','成都办事处'));
    //     workLocationSelect.add(new SelectOption('成都共通办事处','成都共通办事处'));
    //     workLocationSelect.add(new SelectOption('广州办事处','广州办事处'));
    //     return workLocationSelect;
    // }

    public PageReference RetrievalBtn() {
        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;
        }
        String sql = 'select Id, Name, SAP_Service_Repair_No__c, Status1__c, Status2__c, Delivered_Product__c, SerialNumber__c, ';
        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('sql1:' + sql);
        if(String.isNotBlank(sql)){
            RepairList = Database.query(sql);
        }
        if(RepairList.size() == 200){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '检索数据太多,请缩小检索范围！'));
        }
        if(RepairList.size() <= 0){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '没检索到任何修理'));
            return null;
        }
        for(Repair__c ra : RepairList){
            RepairData raData = new RepairData(ra);
            RAInfoList.add(raData);
        }
        return null;
    }

    public PageReference showPDF() {
        System.debug(LoggingLevel.INFO, '*** joinshoPDF: ');
        repairIdList = new List<String>();
        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 null;
        }
        for(RepairData rd : RAInfoList) {
            System.debug(LoggingLevel.INFO, '*** rd: ' + rd);
            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;
                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 null;
            } else{
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '多单打印最大数量为50,请选择少于50个修理！'));
                return null;
            }
        } else{
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '请至少选择一个修理'));
            return null;
        }
    }

    // 生成pdf添加到对应的修理中
    public static PageReference generateAttachment(List<Repair__c> repList){
        System.debug(LoggingLevel.INFO, '*** generateAttachment: ');
        // PageReference pdfPage;
        // List<Attachment> attachments = new List<Attachment>();
        // List<String> attachmentNameList = new List<String>();
        // List<Attachment> isGeneratedPDFList = new List<Attachment>();
        // //删除已存在的附件，生成新的附件
        // for(Repair__c re : repList){   
        //     attachmentNameList.add(re.name + '_' + 'MaintenanceCommission.pdf');
        // }
        // isGeneratedPDFList = [select id from Attachment where name IN:attachmentNameList];
        // System.debug(LoggingLevel.INFO, '*** isGeneratedPDFList: ' + isGeneratedPDFList);
        // if(isGeneratedPDFList.size() > 0){
        //     delete isGeneratedPDFList;
        // }
        BatchSelectRepairPDFDelete pdf = new BatchSelectRepairPDFDelete();
        pdf.deletePDF(repList);
        pdf.createPDF(repList);

        // for(Repair__c re : repList){       
        //     pdfPage = new PageReference('/apex/MaintenanceCommissionPDF?id=' + re.Id);
        //     Blob pdfBody;
        //     if(Test.isRunningTest()) { 
        //         pdfBody = blob.valueOf('Unit.Test');
        //     } else {
        //         pdfBody = pdfPage.getContentAsPDF();
        //     }
        //     Attachment attach = new Attachment();
        //     attach.Body = pdfBody;
        //     attach.Name = re.name + '_' + 'MaintenanceCommission.pdf';
        //     attach.ParentId = re.id;
        //     attachments.add(attach);
        // }
        // System.debug(LoggingLevel.INFO, '*** attachments: ' + attachments);
        // insert attachments;
        return null;
    }

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

    public class RetrievalData {
        public String Status1{ get; set; }
        public String Status2{ get; set; }
        public String RepairName{ get; set; }
        public String SAPRepairNo{ get; set; }
        public String SerialNumber{ get; set; }
        public String onSiteRepair{ get; set; }
        public String workLocationSelect{ get; set; }
        public String State_Hospital{ get; set; }
        public String HospitalName{ get; set; }
        public Repair__c repair{ get; set; }
        public RetrievalData(){
            repair = new Repair__c();
        }
    }

    public class RepairData {
        public Boolean IFCheck { get; set; }
        public Repair__c repair { get; set; }
        public RepairData(Repair__c RepairInfo){
            IFCheck = null;
            repair = RepairInfo;
        }
    }
}