public with sharing class ChoiceAssetController {

    /*****************検索用******************/
    public String FuselageNumber {
        get;
        set;
    } // 机身号码
    public String AssetModel {
        get;
        set;
    } // 设备型号
    public String HospitalName {
        get;
        set;
    } // 医院名称
    public String RepairSubOrderId; // 报修子单Id
    public String dataType; //数据类型
    public String soql;
    public RepairSubOrder__c repairSubOrder; //报修子单

    public List < ChoiceAssetInfo > choiceAssetInfoRecordsview {
        get;
        set;
    }
    public String text1 { get; set; } // 对象
    public static List<SelectOption> textOpts { get; private set; }
    static {
        textOpts = new List<SelectOption>();
        textOpts.add(new SelectOption('Like', '-无-'));
        textOpts.add(new SelectOption('='  , '等于'));
        textOpts.add(new SelectOption('!='                , '不等于'));
        textOpts.add(new SelectOption('Like'        , '包含'));
        textOpts.add(new SelectOption('NOT Like', '不包含'));
    }
    public ChoiceAssetController(ApexPages.StandardController stdController) {

    }

    public ChoiceAssetController() {
        RepairSubOrderId = ApexPages.currentPage().getParameters().get('Id');
        dataType = ApexPages.currentPage().getParameters().get('Type');
        choiceAssetInfoRecordsview = new List < ChoiceAssetInfo > ();
    }

    // 画面初始化
    public void init() {
        if (String.isNotBlank(RepairSubOrderId)) {
            //获取报价子单的内容
            repairSubOrder = [
                SELECT Id, Name, RepairSubOrderNo__c, RepairOrderNo__c, Hospital__c, Hospital__r.Name,
                StrategicDepartment__c, Department__c, EquipmentCategory__c,
                RepairApplicant__c,RepairApplicantName__c, RepairApplicantTel__c, AssetType__c,
                RepairTime__c, FaultType__c, ProblemDescription__c, ResponseResultType__c,
                ReceiverType__c,  ApplicantType__c, Applicant__c, ApplicationTime__c,
                AssetModel__c, AssetCode__c, AirframeCodeEngineer__c, RepairSubOrderType__c, FaultTime__c, ReceiverTime__c,
                PlannedVisitDay__c,ActualVisitTimeSecond__c,
                ActualVisitTimeThird__c, ResponseResultDesc__c, ProcessResult__c, Status__c,
                Department__r.Name, Department__r.Id,ActualVisitDateThird__c,
                EndTimeFirst__c,RepairsReportDate__c,ActualVisitDateFirst__c,ActualVisitDateSecon__c,
                OwnerId,Owner.Name  
                FROM RepairSubOrder__c
                WHERE Id =: RepairSubOrderId
            ];
        }

        if (repairSubOrder != null) {
            FuselageNumber = repairSubOrder.AirframeCodeEngineer__c;
            AssetModel = null;
            HospitalName = null;
        }

        //1.只查找100条保有设备数据
        String fuselageNumberTrim = String.isNotBlank(FuselageNumber)?FuselageNumber.trim():'';
        String serialNumber = '%' + String.escapeSingleQuotes(fuselageNumberTrim.replaceAll('%', '\\%')) + '%';
        List < Asset > assetListed =    [SELECT Id,name,SerialNumber,InstallDate,Information_From__c,Asset_situation__c,
                                            Order_No__c,Account.Name,Status,Department_Class__c,Hospital__r.Owner.Name,
                                            Hospital__r.Owner.Phone,Installation_Site__c,CurrentContract__c,
                                            Product2.Asset_Model_No__c,Hospital__r.Name,Department_Class__r.Name ,
                                            Department_Class__r.Id,Ji_Zhong_Guan_Li_Ku_Cun__c
                                            ,Account.Parent.Parent.FSE_SP_Main_Leader__r.Work_Location__c
                                        FROM Asset where Id != null AND Repairing_Count__c >= 0 AND SerialNumber like :serialNumber LIMIT 100

                                        ];
        
        for (Asset ast: assetListed) {
            choiceAssetInfoRecordsview.add(new ChoiceAssetInfo(ast));
        }

    }

    // 检索
    public void searchAsset() {
        List < Asset > assetListed = new List < Asset > ();
        List < ChoiceAssetInfo > checkedRecords = new List < ChoiceAssetInfo > ();
        Map < Id, Asset > assetMap = new Map < Id, Asset > ();
        for (ChoiceAssetInfo info: choiceAssetInfoRecordsview) {
            if (info.check) {
                checkedRecords.add(info);
                assetMap.put(info.ast.Id, info.ast);
            }
        }
        choiceAssetInfoRecordsview = checkedRecords;
        soql = this.makeSoql();
        assetListed = Database.query(soql);
        for (Asset ast: assetListed) {
            if (!assetMap.containsKey(ast.Id)) {
                choiceAssetInfoRecordsview.add(new ChoiceAssetInfo(ast));
            }

        }

    }

    // 保存按钮
    public PageReference save() {
        if (String.isBlank(RepairSubOrderId)) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '报修子单Id 不能为空'));
            return null;
        }
        //00N10000002Dx1X
        system.debug('choiceAssetInfoRecordsview--->' + choiceAssetInfoRecordsview);
        Integer quantity = 0;
        Asset ast = new Asset();
        for (ChoiceAssetInfo info: choiceAssetInfoRecordsview) {

            if (info.check) {
                ast = info.ast;
                quantity += 1;
            }
        }
        if (quantity == 0) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '请选择一个保有设备'));
            return null;
        } else if (quantity > 1) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '只能选择一个保有设备'));
            return null;
        }

        return createData(ast);
    }

    public PageReference createData(Asset ast) {
        String url = '/';
        String joint_1 = '=';
        String joint_2 = '_lkid=';
        String joint_3 = '&CF';
        String joint_4 = '&';

        if ('Repair'.equals(dataType)) {
            String Delivered_Product_Id = '00N10000002Dx1X'; //设备型号 
            String Account_Id = '00N10000002Dx5n'; //科室
            String Repair_Detail_Id = '00N10000002Dx6I'; //问题内容描述
            String hospitalId = '00N10000002Dx66'; //医院
            String zhanlueKeshiId = '00N10000002Dx5t'; //战略科室
            String keshiId = '00N10000002Dx5n'; //科室
            String guzhang = '00N10000002Dx5y'; //故障发生日
            //add     wangweipeng        2022/01/26       start
            String guzhangxcx = '00N1m000006vXqw'; //1.故障发生日（小程序）
            //add     wangweipeng        2022/01/26       end
            String Repair_Source_Id = '00N10000002FH86';//新建修理来源
            String Incharge_Staff_Id = '00N10000002EMHw';//修理委托者(FSE)   

            //add     wangweipeng        2022/01/26       start
            String SalesOfficeCode_selection_Id = '00N10000006P6SM';//修理品返送地
            //add     wangweipeng        2022/01/26       end

            String RepairApplicant_Id = ''; //报修人
            String RepairApplicantPosition_Id = ''; //报修人岗位  
            String RepairApplicantHospital_Id = ''; //报修人医院  
            String RepairApplicantDepartment_Id = ''; //报修人科室
            String baoxiuzidan = ''; //报修子单 
            String faqiri = ''; //报修发起日
            String shouliri = ''; //工程师受理日
            String  PlannedVisitDay_Id= '';//计划上门日
            String  ActualVisitDateFirst_Id= '';//一次上门日
            String  ActualVisitDateSecond_Id= '';//二次上门日
            String  ActualVisitDateThird_Id= '';//三次上门日
            String  SubOrderCompleteDate_Id= '';//报修单处理完成日
            String  SubOrderCreatedDate_Id= '';//报修单申请修理日
            String  engineerSendDate_Id= '';//工程师修理品寄送日
            if (NFMUtil.isSandbox()) { //测试环境
                RepairApplicant_Id = '00N1m0000054ufW'; //报修人
                // RepairApplicantPosition_Id = '00N1m0000054ufV'; //报修人岗位  
                RepairApplicantHospital_Id = '00N1m0000054ufU'; //报修人医院  
                RepairApplicantDepartment_Id = '00N1m0000054ufT'; //报修人科室
                baoxiuzidan = '00N1m0000054ufZ'; //报修子单 
                faqiri = '00N1m0000054ufa'; //报修发起日
                shouliri = '00N1m0000054ufS'; //工程师受理日
                
                PlannedVisitDay_Id= '00N1m000005SRiF';//计划上门日
                ActualVisitDateFirst_Id= '00N1m000005SRiK';//一次上门日
                ActualVisitDateSecond_Id= '00N1m000005SRiP';//二次上门日
                ActualVisitDateThird_Id= '00N1m000005SRiU';//三次上门日
                SubOrderCompleteDate_Id= '00N1m000005SRmg';//报修单处理完成日
                SubOrderCreatedDate_Id= '00N1m000005SRmW';//报修单申请修理日
            } else { //正式环境
                RepairApplicant_Id = '00N10000009H1rQ'; //报修人
                // RepairApplicantPosition_Id = ''; //报修人岗位  
                RepairApplicantHospital_Id = '00N10000009H1rP'; //报修人医院  
                RepairApplicantDepartment_Id = '00N10000009H1rO'; //报修人科室
                baoxiuzidan = '00N10000009H1rR'; //报修子单

                faqiri = '00N10000009H1rS'; //报修发起日
                shouliri = '00N10000009H1rN'; //工程师受理日
                
                PlannedVisitDay_Id= '00N10000009H1rM';//计划上门日
                ActualVisitDateFirst_Id= '00N10000009H1r6';//一次上门日
                ActualVisitDateSecond_Id= '00N10000009H1r7';//二次上门日
                ActualVisitDateThird_Id= '00N10000009H1r8';//三次上门日
                SubOrderCompleteDate_Id= '00N10000009H1ri';//报修单处理完成日
                SubOrderCreatedDate_Id= '00N10000009H1rj';//报修单申请修理日
            }

            url += 'a0J/e?retURL=%2F';
            url += joint_3 + Delivered_Product_Id + joint_1 + ast.Name;
            url += joint_3 + Delivered_Product_Id + joint_2 + ast.Id;

            url += joint_3 + baoxiuzidan + joint_1 + repairSubOrder.Name;
            url += joint_3 + baoxiuzidan + joint_2 + repairSubOrder.Id;

            url += joint_3 + hospitalId + joint_1 + ast.Hospital__r.Name;
            url += joint_3 + hospitalId + joint_2 + ast.Hospital__r.Id;

            url += joint_4 + Repair_Source_Id + joint_1 + '从报修子单';
            if (String.isNotBlank(ast.Department_Class__c)) {

                url += joint_3 + zhanlueKeshiId + joint_1 + ast.Department_Class__r.Name;
                url += joint_3 + zhanlueKeshiId + joint_2 + ast.Department_Class__r.Id;
            }
            url += joint_3 + keshiId + joint_1 + ast.Account.Name;
            url += joint_3 + keshiId + joint_2 + ast.Account.Id;

            url += joint_4 + RepairApplicant_Id + joint_1 + repairSubOrder.RepairApplicantName__c;//报修人
            // url += joint_4 + RepairApplicantPosition_Id + joint_1 + '';//报修人岗位
            url += joint_4 + RepairApplicantHospital_Id + joint_1 + repairSubOrder.Hospital__r.Name;//报修人医院
            url += joint_4 + RepairApplicantDepartment_Id + joint_1 + repairSubOrder.Department__r.Name;//报修人科室

            if (repairSubOrder.ProblemDescription__c != null) {
                url += joint_4 + Repair_Detail_Id + joint_1 + repairSubOrder.ProblemDescription__c;
            }
            url += joint_4 + guzhang + joint_1 + NFMUtil.formatDateTime2StrSprit(repairSubOrder.FaultTime__c);
            //add         wangweipeng                 2022/02/11              start
            url += joint_4 + guzhangxcx + joint_1 + NFMUtil.formatDateTime2StrDateTime(repairSubOrder.FaultTime__c);
            //add         wangweipeng                 2022/02/11              end
            url += joint_4 + faqiri + joint_1 + NFMUtil.formatDateTime2StrSprit(repairSubOrder.RepairsReportDate__c);
            url += joint_4 +  PlannedVisitDay_Id + joint_1 + NFMUtil.formatDateTime2StrSprit(repairSubOrder.PlannedVisitDay__c);//计划上门日
            url += joint_4 +  ActualVisitDateFirst_Id+ joint_1 + NFMUtil.formatDateTime2StrSprit(repairSubOrder.ActualVisitDateFirst__c);//一次上门日
            url += joint_4 +  ActualVisitDateSecond_Id+ joint_1 + NFMUtil.formatDateTime2StrSprit(repairSubOrder.ActualVisitDateSecon__c);//二次上门日
            url += joint_4 +  ActualVisitDateThird_Id+ joint_1 + NFMUtil.formatDateTime2StrSprit(repairSubOrder.ActualVisitDateThird__c);//三次上门日
            url += joint_4 +  SubOrderCompleteDate_Id+ joint_1 + NFMUtil.formatDateTime2StrSprit(repairSubOrder.ApplicationTime__c);//报修单处理完成日
            url += joint_4 +  SubOrderCreatedDate_Id+ joint_1 + NFMUtil.formatDateTime2StrSprit(Date.today());//报修单申请修理日

            url += joint_4 + shouliri + joint_1 + NFMUtil.formatDateTime2StrSprit(repairSubOrder.ReceiverTime__c);

            //add     wangweipeng        2022/01/26       start
            url += joint_4 +  SalesOfficeCode_selection_Id+ joint_1 + ast.Account.Parent.Parent.FSE_SP_Main_Leader__r.Work_Location__c;//修理品返送地
            //add     wangweipeng        2022/01/26       end
            
            url += joint_3 + Incharge_Staff_Id + joint_1 + repairSubOrder.Owner.Name;
            url += joint_3 + Incharge_Staff_Id + joint_2 + repairSubOrder.OwnerId;
        } else if ('QIS'.equals(dataType)) {

            String Delivered_Product_Id = '00N10000002FHFK'; //设备型号 
            String hospitalId = '00N10000006P4qS'; //医院
            String zhanlueKeshiId = '00N10000006P4og'; //战略科室
            String keshiId = '00N10000002FHF7'; //科室
            String baoxiuzidan = ''; //报修子单

            String fuzeren = '00N10000002FHFI'; //院方负责人
            String lianxidianhua = '00N10000002FHEx'; //联系电话

            String Generation_Source_Id = '00N10000002FHF6';//QIS来源
            String Name_Id = 'Name';//QIS管理号码

            if (NFMUtil.isSandbox()) {
                baoxiuzidan = '00N1m000005STFv'; //报修子单
            } else {
                baoxiuzidan = '00N10000009H22X'; //报修子单
            }
            url += 'a0f/e?retURL=%2Fa0f%2Fo&RecordType=01210000000RLWc&ent=01I10000000T5b1';

            url += joint_3 + Delivered_Product_Id + joint_1 + ast.Name;
            url += joint_3 + Delivered_Product_Id + joint_2 + ast.Id;

            url += joint_3 + hospitalId + joint_1 + ast.Hospital__r.Name;
            url += joint_3 + hospitalId + joint_2 + ast.Hospital__r.Id;
            if (String.isNotBlank(ast.Department_Class__c)) {

                url += joint_3 + zhanlueKeshiId + joint_1 + ast.Department_Class__r.Name;
                url += joint_3 + zhanlueKeshiId + joint_2 + ast.Department_Class__r.Id;
            }
            url += joint_3 + keshiId + joint_1 + ast.Account.Name;
            url += joint_3 + keshiId + joint_2 + ast.Account.Id;

            url += joint_3 + baoxiuzidan + joint_1 + repairSubOrder.Name;
            url += joint_3 + baoxiuzidan + joint_2 + repairSubOrder.Id;

            url += joint_4 + fuzeren + joint_1 + ast.Hospital__r.Owner.Name;
            url += joint_4 + Name_Id + joint_1 + '*';
            url += joint_4 + Generation_Source_Id + joint_1 + '报修单';
            if (ast.Hospital__r.Owner.Phone != null) {
                url += joint_4 + lianxidianhua + joint_1 + ast.Hospital__r.Owner.Phone;
            }

        }

        System.debug('---------'+url);
        PageReference ref = new Pagereference(url);
        ref.setRedirect(true);
        return ref;
    }
    //SQL拼写
    private String makeSoql() {

        String start = '';
        String soql = 'select Id,name,SerialNumber,InstallDate,Information_From__c,Asset_situation__c,Order_No__c,Account.Name,Status,Department_Class__c, ';

        soql += 'Hospital__r.Owner.Name,Hospital__r.Owner.Phone,Installation_Site__c,CurrentContract__c,Product2.Asset_Model_No__c,Hospital__r.Name,Department_Class__r.Name ,Department_Class__r.Id,';
        soql += 'Ji_Zhong_Guan_Li_Ku_Cun__c,Account.Parent.Parent.FSE_SP_Main_Leader__r.Work_Location__c';
        soql += ' from Asset where Id != null AND Repairing_Count__c = 0 ';
        if (String.isNotBlank(FuselageNumber) || String.isNotBlank(AssetModel) || String.isNotBlank(HospitalName)) {
            soql += ' AND (';
            if (String.isNotBlank(FuselageNumber)) {
                String fuselageNumberTrim = FuselageNumber.trim();
                start = ' SerialNumber like \'%' + String.escapeSingleQuotes(fuselageNumberTrim.replaceAll('%', '\\%')) + '%\' ';
            }

            if (String.isNotBlank(HospitalName)) {
                String hospitalNameTrim = HospitalName.trim();
                if (String.isNotBlank(start)) {
                    start += ' AND ';
                }
                start += ' Hospital__r.Name like \'%' + String.escapeSingleQuotes(hospitalNameTrim.replaceAll('%', '\\%')) + '%\'';

            }

            if (String.isNotBlank(AssetModel)) {
                String assetModelTrim = AssetModel.trim();
                if (String.isNotBlank(start)) {
                    start += ' AND ';
                }
                start += ' Product2.Asset_Model_No__c like \'%' + String.escapeSingleQuotes(assetModelTrim.replaceAll('%', '\\%')) + '%\'';
            }

            soql += start + ')';
        }
        soql += ' limit 10';

        system.debug('soql---->' + soql);
        return soql;
    }

    class ChoiceAssetInfo {
        public Boolean check {
            get;
            set;
        }
        public Asset ast {
            get;
            set;
        }
        public Boolean canSelect {
            get;
            set;
        }
        public ChoiceAssetInfo(Asset e) {
            check = false;
            ast = e;
            canSelect = true;
        }
    }
}