public with sharing class lexNewSparePartsLoanApplicationCtl {
    public lexNewSparePartsLoanApplicationCtl() {

    }

    //获取当前登录人的 id
    @AuraEnabled
    public static UserResult UserInfo_Owner() {
        UserResult result = new UserResult();
        ID myUserID = UserInfo.getUserId();
        try { 
            User tempUser =
                [select Id,Job_Category__c,isFormal_Stuff__c,FirstName,LastName,Province__c from user where id = : myUserID ];
            result.id = tempUser.Id;
            result.isFormalStuff = tempUser.isFormal_Stuff__c;
            result.firstName = tempUser.FirstName == null ? '' : tempUser.FirstName;
            result.lastName = tempUser.LastName == null ? '' : tempUser.LastName;
            result.userProvince = tempUser.Province__c;
            result.userJobCategory = tempUser.Job_Category__c;
        } catch (exception e) {
            
            result.result = e.getMessage();
        }
        return result;
    }

    @AuraEnabled
    public static InitData init(String recordId){
        InitData res = new initData();
        try {
            //2023 08 18 ZhangHeyang PIPL相关按钮修改 Start --- 新增查询字段Related_Opportunity1_ID__r.Name
            List<OPDPlan__c> repList = [select Id,HospitalID__c,RentalApplyId__c,Related_Opportunity1_ID__r.Id,Related_Opportunity1_ID__r.Name,Campaign__r.Id,Status__c,Rental_Apply_Flag__c,OPDType__c,CampaignStatus__c,CampaignRecodeTypeId__c,Internal_in_charge_province__c,StayOrNot__c,OriginalOpdPlanApplication__c,IF_Approved__c,Approved_No__c,Approved_No__r.Name,Approved_Status__c,Rental_Apply2__c,OriginalOpdPlan__c,CampaignName__c,Related_Opportunity1_ID__c,NoOpp_Reason__c,Account_Laboratory__c,OCM_category_Name__c,OCM_category_ID__c,HospitalName__c,Name,IsJump__c,JumpCause__c,originalOpdRentalApply__c,RentalApplyName__c from OPDPlan__c where Id =: recordId];
            //2023 08 18 ZhangHeyang PIPL相关按钮修改 End
            if(repList.size() > 0){
                OPDPlan__c rep = repList[0];
                res.opdPlanId = rep.Id;
                res.opdHospitalId = rep.HospitalID__c == null ? '' : rep.HospitalID__c;
                res.opdCampaignId = rep.Campaign__r.Id == null ? '' : rep.Campaign__r.Id;
                // res.opdCampaignId = rep.CampaignName__c == null ? '' : rep.CampaignName__c;
                res.opdOpportunityId = rep.Related_Opportunity1_ID__r.Id == null ? '' : rep.Related_Opportunity1_ID__r.Id;
                //2023 08 18 ZhangHeyang PIPL相关按钮修改 Start
                res.opdOpportunityName = rep.Related_Opportunity1_ID__r.Name == null ? '' : rep.Related_Opportunity1_ID__r.Name;
                //2023 08 18 ZhangHeyang PIPL相关按钮修改 End
                res.opdStatus = rep.Status__c == null ? '' : rep.Status__c;
                res.opdRentalApplyFlag = rep.Rental_Apply_Flag__c;
                res.opdType = rep.OPDType__c == null ? '' : rep.OPDType__c;
                res.opdCampaignStatus = rep.CampaignStatus__c == null ? '' : rep.CampaignStatus__c;
                res.opdCampaignRecodeTypeId = rep.CampaignRecodeTypeId__c == null ? '' : rep.CampaignRecodeTypeId__c;
                res.opdInternalinchargeprovince = rep.Internal_in_charge_province__c == null ? '' : rep.Internal_in_charge_province__c;
                res.opdStayOrNot = rep.StayOrNot__c == null ? '' : rep.StayOrNot__c;
                res.opdOriginalOpdPlanApplication = rep.OriginalOpdPlanApplication__c== null ? '' : rep.OriginalOpdPlanApplication__c;
                res.opdIFApproved = rep.IF_Approved__c;
                res.opdApprovedNo = rep.Approved_No__c == null ? '' : rep.Approved_No__r.Name;
                res.opdApprovedStatus = rep.Approved_Status__c == null ? '' : rep.Approved_Status__c;
                res.opdRentalApply2 = rep.Rental_Apply2__c == null ? '' : rep.Rental_Apply2__c;
                res.opdOriginalOpdPlan = rep.OriginalOpdPlan__c == null ? '' : rep.OriginalOpdPlan__c;
                res.opdCampaignName = rep.CampaignName__c == null ? '' : rep.CampaignName__c;
                res.opdRelatedOpportunity1ID = rep.Related_Opportunity1_ID__c == null ? '' : rep.Related_Opportunity1_ID__c;
                res.opdNoOppReason = rep.NoOpp_Reason__c == null ? '' : rep.NoOpp_Reason__c;
                res.opdAccountLaboratory = rep.Account_Laboratory__c == null ? '' : rep.Account_Laboratory__c;
                res.opdOCMcategoryName = rep.OCM_category_Name__c == null ? '' : rep.OCM_category_Name__c;
                res.opdOCMcategoryId = rep.OCM_category_ID__c == null ? '' : rep.OCM_category_ID__c;
                res.opdHospitalName = rep.HospitalName__c == null ? '' : rep.HospitalName__c;
                res.opdName = rep.Name == null ? '' : rep.Name;
                res.opdIsJump = rep.IsJump__c;
                res.opdJumpCause = rep.JumpCause__c == null ? '' : rep.JumpCause__c;
                res.opdoriginalOpdRentalApply = rep.originalOpdRentalApply__c == null ? '' : rep.originalOpdRentalApply__c;
                res.opdRentalApplyName = rep.RentalApplyId__c == null ? '' : rep.RentalApplyId__c;
                res.opdStatusProcessState = System.Label.StatusProcessState;
                res.opdCampaignTypeId = Schema.SObjectType.Campaign.getRecordTypeInfosByDeveloperName().get('Service_trainig').getRecordTypeId();
                return res;
            }
            return null;
        } catch (Exception e) {
            throw new AuraHandledException(e.getMessage());
        }
    }

    @AuraEnabled
    public static NewApply newApplyInit(String recordId) {
        NewApply newApp = new NewApply();
        List<String> opdIdList = new List<String>();
        String s='';
        try {
            List<OPDPlan__c> opdList = [SELECT Id,Name,OriginalOpdPlan__c FROM OPDPlan__c WHERE Id = :recordId];
            if (opdList.size() > 0) {
                for (OPDPlan__c opdId : opdList) {
                    opdIdList.add(opdId.OriginalOpdPlan__c);
                }

                String objectName = 'Rental_Apply__c'; // 要获取字段的对象名
                Map<String, Schema.SObjectType> globalDescribe = Schema.getGlobalDescribe();
                Schema.SObjectType objType = globalDescribe.get(objectName);
                if (objType != null) {
                    Schema.DescribeSObjectResult objDescribe = objType.getDescribe();
                    Map<String, Schema.SObjectField> fieldMap = objDescribe.fields.getMap();
                    s+='SELECT '; //跟进询价1的Name deloitte-zhj 20230921
                    // 现在，fieldMap中包含了对象的所有字段信息
                    for (String fieldName : fieldMap.keySet()) {
                        if(!fieldName.equals('id'))
                            s+=fieldName+',';
                    }

                    s=s.removeEnd(',');
                    s+=' FROM Rental_Apply__c where OPDPlan__c=\''+opdIdList[0]+'\'';
                    system.debug('SQL:'+s);
                    system.debug('SQL:'+s);
                    List<Rental_Apply__c> OPDPlans = Database.query(s);
                    s='';
                    if(OPDPlans.size()>0){
                        system.debug('in!');
                        for (String fieldName : fieldMap.keySet()) {
                            String formaF=fieldMap.get(fieldName).getDescribe().getName();
                            // || formaF != 'Name'
                            if(formaF != 'Id' || formaF != 'Status__c'){
                                if(formaF == 'Request_shipping_day__c' || formaF == 'Hope_Lonaer_date_Num__c'|| formaF == 'Old_Rental_Apply__c'|| formaF == 'Split_Apply_Reason__c'|| formaF == 'Cancel_Reason__c' || formaF == 'Loaner_cancel_reason__c' || formaF == 'Loaner_cancel_request__c'){
                                    s+=formaF+'=,';
                                }else{
                                    if(OPDPlans.get(0).get(fieldName)!=null&&!OPDPlans.get(0).get(fieldName).equals('null'))
                                        s+=formaF+'='+OPDPlans.get(0).get(fieldName)+',';
                                }
                                
                            }
                            
                            
                        }
                        s=s.removeEnd(',');
                    }
                }
                
                List<Rental_Apply__c> nObjList = [SELECT Id,Name,
                                                        Request_return_day__c, // 预定归还日
                                                        Request_shipping_day__c, // 希望到货日
                                                        Hope_Lonaer_date_Num__c, // 希望借用天数
                                                        Cancel_Reason__c, // 取消理由
                                                        Loaner_cancel_reason__c, // 备品申请取消理由
                                                        Loaner_cancel_request__c, // 备品申请取消理由备注
                                                        Request_demo_time__c, // 申请时间
                                                        Request_approval_time__c, // 批准时间(申请提交时间)
                                                        Application_accept_time__c, // 申请受理时间(回答时间)
                                                        Request_answer_time__c, // 备品首次分配时间
                                                        Response__c, // 应答沟通
                                                        Assign_Person__c, // 分配人
                                                        Old_Rental_Apply__c, // 旧借出申请
                                                        Loaner_medical_Staff__r.AWS_Data_Id__c, //deloitte-zhj 科室负责人的AWSID 20230916
                                                        AWS_Data_Id__c, //deloitte-zhj 备品借出申请的AWSID 20230916
                                                        Follow_UP_Opp__r.Name, //deloitte-zhj 跟进询价1 20230922
                                                        repair__r.Name //deloitte-zhj 修理 20230922
                                                        FROM Rental_Apply__c WHERE OPDPlan__c = :opdIdList[0]];
                if (nObjList.size() > 0) {
                    Rental_Apply__c nObj = nObjList[0];
                    newApp.id = nObj.Id;
                    newApp.requestShippingDay = nObj.Request_shipping_day__c;
                    newApp.requestReturnDay = nObj.Request_return_day__c;
                    newApp.hopeLonaerDateNum = nObj.Hope_Lonaer_date_Num__c;
                    newApp.cancelReason = nObj.Cancel_Reason__c;
                    newApp.loanerCancelReason = nObj.Loaner_cancel_reason__c;
                    newApp.loanerCancelRequest = nObj.Loaner_cancel_request__c;
                    newApp.requestDemoTime = nObj.Request_demo_time__c;
                    newApp.requestApprovalTime = nObj.Request_approval_time__c;
                    newApp.applicationAcceptTime = nObj.Application_accept_time__c;
                    newApp.requestAnswerTime = nObj.Request_answer_time__c;
                    newApp.response = nObj.Response__c;
                    newApp.assignPerson = nObj.Assign_Person__c;
                    newApp.oldRentalApply = nObj.Old_Rental_Apply__c;
                    newApp.opdCloneData = s;
                    //deloitte-zhj 20230916 start
                    newApp.loanerMedicalStaffAWSDataId = nObj.Loaner_medical_Staff__r.AWS_Data_Id__c;
                    newApp.rentalApplyAWSDataId = nObj.AWS_Data_Id__c;
                    newApp.Follow_UP_OppName = nObj.Follow_UP_Opp__r.Name;
                    newApp.RepairName = nObj.repair__r.Name;
                    //deloitte-zhj 20230916 end
                    return newApp;
                }
                return null;
            }
            return null;
        } catch (Exception e) {
            throw new AuraHandledException(e.getMessage());
        }
    }

    @AuraEnabled
    public static NewApply newApplyInitApp(String recordId) {
        NewApply newApp = new NewApply();
        List<String> opdIdList = new List<String>();
        String s='';
        try {
            List<OPDPlan__c> opdList = [SELECT Id,Name,OriginalOpdPlanApplication__c FROM OPDPlan__c WHERE Id = :recordId];
            if (opdList.size() > 0) {
                for (OPDPlan__c opdId : opdList) {
                    opdIdList.add(opdId.OriginalOpdPlanApplication__c);
                }

                String objectName = 'Rental_Apply__c'; // 要获取字段的对象名
                Map<String, Schema.SObjectType> globalDescribe = Schema.getGlobalDescribe();
                Schema.SObjectType objType = globalDescribe.get(objectName);
                if (objType != null) {
                    Schema.DescribeSObjectResult objDescribe = objType.getDescribe();
                    Map<String, Schema.SObjectField> fieldMap = objDescribe.fields.getMap();
                    s+='SELECT '; //跟进询价1的Name deloitte-zhj 20230921
                    // 现在，fieldMap中包含了对象的所有字段信息
                    for (String fieldName : fieldMap.keySet()) {
                        if(!fieldName.equals('id'))
                            s+=fieldName+',';
                    }

                    s=s.removeEnd(',');
                    s+=' FROM Rental_Apply__c where OPDPlan__c=\''+opdIdList[0]+'\'';
                    system.debug('SQL:'+s);
                    List<Rental_Apply__c> OPDPlans = Database.query(s);
                    s='';
                    if(OPDPlans.size()>0){
                        system.debug('in!');
                        for (String fieldName : fieldMap.keySet()) {
                            String formaF=fieldMap.get(fieldName).getDescribe().getName();
                            if(formaF != 'Id' || formaF != 'Name' || formaF != 'Status__c'){
                                if(OPDPlans.get(0).get(fieldName)!=null&&!OPDPlans.get(0).get(fieldName).equals('null')){
                                    // System.debug('FieldType:'+String.valueOf(fieldMap.get(fieldName).getDescribe().getType()));
                                    if(String.valueOf(fieldMap.get(fieldName).getDescribe().getType()) == 'DATETIME'){
                                        DateTime dt = (DateTime)OPDPlans.get(0).get(fieldName);
                                        s+=formaF+'='+dt.formatGMT('yyyy-MM-dd\'T\'HH:mm:ss\'Z\'')+',';
                                        // System.debug('FieldType1:'+dt.formatGMT('yyyy-MM-dd\'T\'HH:mm:ss\'Z\''));
                                    }else{
                                        // System.debug('FieldType2:'+OPDPlans.get(0).get(fieldName));
                                        s+=formaF+'='+OPDPlans.get(0).get(fieldName)+',';
                                    }
                                }
                            }
                            
                        }
                        s=s.removeEnd(',');
                    }
                }
                // System.debug('String of s:'+s);
                List<Rental_Apply__c> nObjList = [SELECT Id,Name,
                                                        Request_return_day__c, // 预定归还日
                                                        Request_shipping_day__c, // 希望到货日
                                                        Hope_Lonaer_date_Num__c, // 希望借用天数
                                                        Cancel_Reason__c, // 取消理由
                                                        Loaner_cancel_reason__c, // 备品申请取消理由
                                                        Loaner_cancel_request__c, // 备品申请取消理由备注
                                                        Request_demo_time__c, // 申请时间
                                                        Request_approval_time__c, // 批准时间(申请提交时间)
                                                        Application_accept_time__c, // 申请受理时间(回答时间)
                                                        Request_answer_time__c, // 备品首次分配时间
                                                        Response__c, // 应答沟通
                                                        Assign_Person__c, // 分配人
                                                        Old_Rental_Apply__c, // 旧借出申请
                                                        Loaner_medical_Staff__r.AWS_Data_Id__c, //deloitte-zhj 科室负责人的AWSID 20230916
                                                        AWS_Data_Id__c, //deloitte-zhj 备品借出申请的AWSID 20230916
                                                        Follow_UP_Opp__r.Name, //deloitte-zhj 跟进询价1 20230922
                                                        repair__r.Name //deloitte-zhj 修理 20230922
                                                        FROM Rental_Apply__c WHERE OPDPlan__c = :opdIdList[0]];
                if (nObjList.size() > 0) {
                    Rental_Apply__c nObj = nObjList[0];
                    newApp.id = nObj.Id;
                    newApp.requestShippingDay = nObj.Request_shipping_day__c;
                    newApp.requestReturnDay = nObj.Request_return_day__c;
                    newApp.hopeLonaerDateNum = nObj.Hope_Lonaer_date_Num__c;
                    newApp.cancelReason = nObj.Cancel_Reason__c;
                    newApp.loanerCancelReason = nObj.Loaner_cancel_reason__c;
                    newApp.loanerCancelRequest = nObj.Loaner_cancel_request__c;
                    newApp.requestDemoTime = nObj.Request_demo_time__c;
                    newApp.requestApprovalTime = nObj.Request_approval_time__c;
                    newApp.applicationAcceptTime = nObj.Application_accept_time__c;
                    newApp.requestAnswerTime = nObj.Request_answer_time__c;
                    newApp.response = nObj.Response__c;
                    newApp.assignPerson = nObj.Assign_Person__c;
                    newApp.oldRentalApply = nObj.Old_Rental_Apply__c;
                    newApp.opdCloneData = s;
                    //deloitte-zhj 20230916 start
                    newApp.loanerMedicalStaffAWSDataId = nObj.Loaner_medical_Staff__r.AWS_Data_Id__c;
                    newApp.rentalApplyAWSDataId = nObj.AWS_Data_Id__c;
                    newApp.Follow_UP_OppName = nObj.Follow_UP_Opp__r.Name;
                    newApp.RepairName = nObj.repair__r.Name;
                    //deloitte-zhj 20230916 end
                    return newApp;
                }
                return null;
            }
            return null;
        } catch (Exception e) {
            throw new AuraHandledException(e.getMessage());
        }
    }
    public class InitData{
        @AuraEnabled
        public String opdPlanId;
        @AuraEnabled
        public String opdCampaignId;
        @AuraEnabled
        public String opdOpportunityId;
        @AuraEnabled
        public String opdStatus;
        @AuraEnabled
        public Decimal opdRentalApplyFlag;
        @AuraEnabled
        public String opdType;
        @AuraEnabled
        public String opdCampaignStatus;
        @AuraEnabled
        public String opdCampaignRecodeTypeId;
        @AuraEnabled
        public String opdInternalinchargeprovince;
        @AuraEnabled
        public String opdStayOrNot;
        @AuraEnabled
        public String opdOriginalOpdPlanApplication;
        @AuraEnabled
        public Boolean opdIFApproved;
        @AuraEnabled
        public String opdApprovedNo;
        @AuraEnabled
        public String opdApprovedStatus;
        @AuraEnabled
        public String opdRentalApply2;
        @AuraEnabled
        public String opdOriginalOpdPlan;
        @AuraEnabled
        public String opdCampaignName;
        @AuraEnabled
        public String opdRelatedOpportunity1ID;
        @AuraEnabled
        public String opdNoOppReason;
        @AuraEnabled
        public String opdAccountLaboratory;
        @AuraEnabled
        public String opdOCMcategoryName;
        @AuraEnabled
        public String opdOCMcategoryId;
        @AuraEnabled
        public String opdHospitalName;
        @AuraEnabled
        public String opdHospitalId;
        @AuraEnabled
        public String opdName;
        @AuraEnabled
        public Boolean opdIsJump;
        @AuraEnabled
        public String opdJumpCause;
        @AuraEnabled
        public String opdoriginalOpdRentalApply;
        @AuraEnabled
        public String opdRentalApplyName;
        @AuraEnabled
        public String opdStatusProcessState;
        @AuraEnabled
        public String opdCampaignTypeId;
        //2023 08 18 ZhangHeyang PIPL相关按钮修改 Start
        @AuraEnabled
        public String opdOpportunityName;
        //2023 08 18 ZhangHeyang PIPL相关按钮修改 End
    }

    public class UserResult {
        @AuraEnabled
        public string result;
        public UserResult( ) {
            result = 'Success';
        }
        @AuraEnabled
        public string id;
        @AuraEnabled
        public Boolean isFormalStuff;
        @AuraEnabled
        public string firstName;
        @AuraEnabled
        public string lastName;
        @AuraEnabled
        public string userProvince;
        @AuraEnabled
        public string userJobCategory;
    }

    public class NewApply {
        @AuraEnabled
        public string id;
        @AuraEnabled
        public Date requestShippingDay;
        @AuraEnabled
        public Date requestReturnDay;
        @AuraEnabled
        public Decimal hopeLonaerDateNum;
        @AuraEnabled
        public string cancelReason;
        @AuraEnabled
        public string loanerCancelReason;
        @AuraEnabled
        public string loanerCancelRequest;
        @AuraEnabled
        public Datetime requestDemoTime;
        @AuraEnabled
        public Datetime requestApprovalTime;
        @AuraEnabled
        public Datetime applicationAcceptTime;
        @AuraEnabled
        public Datetime requestAnswerTime;
        @AuraEnabled
        public string response;
        @AuraEnabled
        public string assignPerson;
        @AuraEnabled
        public string oldRentalApply;
        @AuraEnabled
        public string Name;
        @AuraEnabled
        public string opdCloneData;
        @AuraEnabled
        public string loanerMedicalStaffAWSDataId; //deloitte-zhj 科室负责人的AWSID 20230916
        @AuraEnabled
        public string rentalApplyAWSDataId; //deloitte-zhj 备品借出申请的AWSID 20230916
        @AuraEnabled
        public string Follow_UP_OppName; //deloitte-zhj 跟进询价1 20230916
        @AuraEnabled
        public string RepairName; //deloitte-zhj 修理 20230916
    }
}