public with sharing class LexSelectSubstituteControllerLWT {
    public LexSelectSubstituteControllerLWT() {
        
    }
        @AuraEnabled
    public static InitData initFromSelectSubstituteButton(String recordId){
        InitData res = new InitData();
        try{
            Rental_Apply_Equipment_Set__c report=[select
                Id,Rental_Apply__r.Status__c,Rental_Apply__r.Id
             from Rental_Apply_Equipment_Set__c
             where Id= :recordId];
            res.id=report.Id;
            res.RentalApplyId=report.Rental_Apply__r.Id;
            res.Status=report.Rental_Apply__r.Status__c;
        }catch(Exception e){
            System.debug(LoggingLevel.INFO,'Rental_Apply_Equipment_Set__c Cancel Error : ' + e);
        }
        return res;
    }


    @AuraEnabled
    public static List<String> getStatusList(){
        String statusSting = Label.StatusProcessState;
        List<String> status = statusSting.split(',');
        return status;
    }

    @AuraEnabled
    public static List<String> getUserIdByUserName(List<String> userNameList){
        try{
            List<User> userList=[select id,name from user where name in :userNameList];
            List<String> res=new List<String>();
            for (User u:userList ) {
                res.add(u.id);
            }
            return res;
        }catch(Exception e){
            System.debug(LoggingLevel.INFO,'Rental_Apply_Equipment_Set__c Cancel Error : ' + e);
        }
        return null;
    }

    @AuraEnabled
    public static Rental_Apply_Equipment_Set__c initFromCustomSubmitButton(String recordId){

        try{
            Rental_Apply_Equipment_Set__c report=[select
                Id,Request_extend_day__c
                ,Extend_request_reason__c
                ,Rental_End_Date__c,
                Rental_Apply__c
             from Rental_Apply_Equipment_Set__c
             where Id= :recordId];

             return report;
        }catch(Exception e){
            System.debug(LoggingLevel.INFO,'Rental_Apply_Equipment_Set__c Cancel Error : ' + e);
        }
        return null;
    }

    @AuraEnabled
    public static InitData initFromLoanerArrangedEmailLButton(String recordId){
        String statusSting = Label.StatusProcessState;
        List<String> status = statusSting.split(',');
        InitData res = new InitData();
        try{
            Rental_Apply_Equipment_Set__c report=[select
                Id,Rental_Apply__r.Status__c,Rental_Apply__c,Rental_Apply__r.Wei_Assigned_Cnt__c,
                Assigned_Not_Shipment__c,Rental_Apply__r.Bollow_Date__c
             from Rental_Apply_Equipment_Set__c
             where Id= :recordId];
            res.id=report.Id;
            res.RentalApplyC=report.Rental_Apply__c;
            res.Status=report.Rental_Apply__r.Status__c;
            res.WeiAssignedCntC=report.Rental_Apply__r.Wei_Assigned_Cnt__c;
            res.BollowDateC=report.Rental_Apply__r.Bollow_Date__c;
            res.AssignedNotShipmentC=report.Assigned_Not_Shipment__c;
            res.statusList = status;
        }catch(Exception e){
            System.debug(LoggingLevel.INFO,'Rental_Apply_Equipment_Set__c Cancel Error : ' + e);
        }
        return res;
    }

    @AuraEnabled
    public static InitData initClearReturnDeliverySlipButton(String recordId){
        InitData res = new InitData();
        try{
            Rental_Apply_Equipment_Set__c report=[select
                Id,Rental_Apply__r.Status__c,Rental_Apply__c,Rental_Apply__r.Wei_Assigned_Cnt__c,
                Assigned_Not_Shipment__c,Rental_Apply__r.Bollow_Date__c
             from Rental_Apply_Equipment_Set__c
             where Id= :recordId];
            res.id=report.Id;
            res.RentalApplyC=report.Rental_Apply__c;
            res.Status=report.Rental_Apply__r.Status__c;
            res.WeiAssignedCntC=report.Rental_Apply__r.Wei_Assigned_Cnt__c;
            res.BollowDateC=report.Rental_Apply__r.Bollow_Date__c;
            res.AssignedNotShipmentC=report.Assigned_Not_Shipment__c;
        }catch(Exception e){
            System.debug(LoggingLevel.INFO,'Rental_Apply_Equipment_Set__c Cancel Error : ' + e);
        }
        return res;
    }

    @AuraEnabled
    public static Rental_Apply_Equipment_Set__c selectRentalApplyEquipmentSetByID(String recordId){
        try{
            Rental_Apply_Equipment_Set__c report=[select 
             Cancel_Select__c,Irreplaceable_flag__c,RAES_Status__c,Shippment_loaner_time2__c,Request_shipping_day__c,Demo_purpose2__c 
             from Rental_Apply_Equipment_Set__c 
             where Id=:recordId];
            return report;
        }catch(Exception e){
            System.debug(LoggingLevel.INFO,'Rental_Apply_Equipment_Set__c Cancel Error : ' + e);
        }
        return null;
    }

    @AuraEnabled
    public static list<Rental_Apply_Equipment_Set_Detail__c> selectRentalApplyEquipmentSetByRACID(String recordId){
        try{
            list<Rental_Apply_Equipment_Set_Detail__c> report=[select Allow_Adjust_Queue_Flag__c 
            from Rental_Apply_Equipment_Set_Detail__c 
            where Rental_Apply__c = :recordId ];
            return report;
        }catch(Exception e){
            System.debug(LoggingLevel.INFO,'Rental_Apply_Equipment_Set__c Cancel Error : ' + e);
        }
        return null;
    }


    @AuraEnabled
    public static list<Rental_Apply__c> selectRentalApplyCByName(String recordId){
        try{
            list<Rental_Apply__c> report=[select 
            Id,Campaign__c,Repair__c,Status__c,Bollow_Date__c, Demo_purpose1__c,Contract_pdf_updated__c,Repair_Final_Inspection_Date_F__c,RC_return_to_office__c,Wei_Assigned_Cnt__c 
            from Rental_Apply__c 
            where id=:recordId ];
            return report;
        }catch(Exception e){
            System.debug(LoggingLevel.INFO,'Rental_Apply_Equipment_Set__c Cancel Error : ' + e);
        }
        return null;
    }
    @AuraEnabled
    public static list<Campaign> selectCampaignById(String recordId){
        try{
            list<Campaign> report=[select
              Status, Rental_Apply_Flag__c,IF_Approved__c,Meeting_Approved_No__c,Approved_Status__c
              from Campaign
              where id =:recordId ];
            return report;
        }catch(Exception e){
            System.debug(LoggingLevel.INFO,'Rental_Apply_Equipment_Set__c Cancel Error : ' + e);
        }
        return null;
    }
    @AuraEnabled
    public static String getSessionId(){
        return UserInfo.getSessionId();
    }


    @AuraEnabled
    public static list<Rental_Apply_Equipment_Set__c> selectRaesById1(String recordId1){
        try{
            list<Rental_Apply_Equipment_Set__c> report=[select Id 
            from Rental_Apply_Equipment_Set__c 
            where Rental_Apply__c = :recordId1 
            and Shippment_loaner_time2__c != null 
            and RAES_Status__c != '已分配' 
            and RAES_Status__c != '取消分配'
            ];
            return report;
        }catch(Exception e){
            System.debug(LoggingLevel.INFO,'selectRaesById1 Error : ' + e);
        }
        return null;
    }
    @AuraEnabled
    public static list<Rental_Apply_Equipment_Set__c> selectRaesById2(String recordId2){
        try{
            list<Rental_Apply_Equipment_Set__c> report=[select Id
             from Rental_Apply_Equipment_Set__c
              where Rental_Apply__c = :recordId2
              and RAES_Status__c != '已分配'
              and RAES_Status__c != '取消分配'
           ];
            return report;
        }catch(Exception e){
            System.debug(LoggingLevel.INFO,'selectRaesById1 Error : ' + e);
        }
        return null;
    }

    @AuraEnabled
    public static list<Rental_Apply__c> selectRacById(String recordId){
        try{
            list<Rental_Apply__c> report=[SELECT 
            Id, JingliApprovalManager__c, SalesManager__c
            , BuchangApprovalManager__c
            , BuchangApprovalManagerSales__c
            , ZongjianApprovalManager__c 
            FROM Rental_Apply__c 
            WHERE Id = :recordId
            ];
            return report;
        }catch(Exception e){
            System.debug(LoggingLevel.INFO,'Rental_Apply_Equipment_Set__c Cancel Error : ' + e);
        }
        return null;
    }

    @AuraEnabled
    public static UpdateResult updateRaesc(        
        String recordId,
        String JingliApprovalManagerc,
        String SalesManagerc,
        String BuchangApprovalManagerc,
        String BuchangApprovalManagerSalesc,
        String ZongjianApprovalManagerc,
        String ExtendStatusc
    ) {
        UpdateResult result = new UpdateResult();
        result.recordId = recordId;
        try{
            // 更新记录并获取结果
            if(recordId==null) return null;
            Rental_Apply_Equipment_Set__c rac = new Rental_Apply_Equipment_Set__c( id=recordId);

            if(JingliApprovalManagerc!=null&& JingliApprovalManagerc != ''){
                rac.JingliApprovalManager__c=JingliApprovalManagerc;
            }
            if(SalesManagerc!=null&&SalesManagerc!=''){
                rac.SalesManager__c=SalesManagerc;
            }
            if(BuchangApprovalManagerc!=null&&BuchangApprovalManagerc!=''){
                rac.BuchangApprovalManager__c=BuchangApprovalManagerc;
            }
            if(BuchangApprovalManagerSalesc!=null&&BuchangApprovalManagerSalesc!=''){
                rac.BuchangApprovalManagerSales__c=BuchangApprovalManagerSalesc;
            }

            if(ZongjianApprovalManagerc!=null&&ZongjianApprovalManagerc!=''){
                rac.ZongjianApprovalManager__c=ZongjianApprovalManagerc;
            }
            if(ExtendStatusc!=null&&ExtendStatusc!=''){
                rac.Extend_Status__c=ExtendStatusc;
            }
            if(rac.id==null)return null;
            update rac;
            result.success = true;
            result.errors = new List<String>();
            return result;
        }catch(Exception e){
            result.success = false;
            result.errors = new List<String>();
            result.errors.add(e.getMessage());
            System.debug(LoggingLevel.INFO,'Rental_Apply__c update Error : ' + e);
        }
        return result;
    }

    @AuraEnabled
    public static UpdateResult updateRaescList(        
        list<Rental_Apply_Equipment_Set_Detail__c> updateList
    ) {
        UpdateResult result = new UpdateResult();
        try{
            for(Rental_Apply_Equipment_Set_Detail__c item : updateList) {
                item.Return_DeliverySlip__c = null;
                item.Asset_return_time__c = null;
            }
            update updateList;
            result.success = true;
            result.errors = new List<String>();
            return result;
        }catch(Exception e){
            result.success = false;
            result.errors = new List<String>();
            result.errors.add(e.getMessage());
            System.debug(LoggingLevel.INFO,'Rental_Apply__c update Error : ' + e);
        }
        return result;
    }

    @AuraEnabled
    public static list<Rental_Apply_Equipment_Set_Detail__c> selectRaesdcId(String recordId){
        try{
            list<Rental_Apply_Equipment_Set_Detail__c> report=[Select 
            Id 
            From Rental_Apply_Equipment_Set_Detail__c 
            Where Return_DeliverySlip__c != null 
            AND Check_lost_Item_F__c = null 
            AND Rental_Apply_Equipment_Set__c = :recordId AND Cancel_Select__c = false
            ];
            return report;
        }catch(Exception e){
            System.debug(LoggingLevel.INFO,'Rental_Apply_Equipment_Set__c Cancel Error : ' + e);
        }
        return null;
    }   

    @AuraEnabled
    public static String approvalCheck(String rentalApplyId) {
        // check结果
        String returnStr = '';
        
        //1388 yc 20211021 跨区域分配不能出库  start
        String rasdid = '';
        system.debug(rentalApplyId+'==');
        if(String.isNotBlank(rentalApplyId) && rentalApplyId.indexOf(';') >= 0){//说明是从一览上触发的
           rasdid = rentalApplyId.subString(rentalApplyId.indexOf(';') + 1);
           rentalApplyId = rentalApplyId.subString(0, rentalApplyId.indexOf(';'));
        }
        //1388 yc 20211021 跨区域分配不能出库  end
        //备品借出申请
        Rental_Apply__c[] rentalApply = [select Id,repair__r.Repair_Final_Inspection_Date__c,Bollow_Date__c,repair__r.Return_Without_Repair_Date__c,
                                        CreatedDate,Rental_Apply_Equipment_Set_Cnt__c,Prepare_Day__c,Cross_Region_Assign__c,
                                        demo_purpose2__c,Follow_UP_Opp__r.Shipping_Finished_Day_Func__c,next_action__c,QIS_number__r.ReplaceDeliveryDate__c
                                        from Rental_Apply__c 
                                        where Id = :rentalApplyId];
        if (rentalApply.size() == 0) {
            returnStr = '没有备品借出申请，请确认。';
            return returnStr;
        }
        Rental_Apply__c ra = rentalApply[0];
        if (ra.Rental_Apply_Equipment_Set_Cnt__c <= 0) {
            returnStr = '没有借出备品set一览，请确认。';
            return returnStr;
        }
        //1822 yc 20211111 start
        if(ra.demo_purpose2__c=='已购待货' && ra.Follow_UP_Opp__r.Shipping_Finished_Day_Func__c!= null){
            returnStr = '已购待货目的，新品已有发货日，不可出库指示';
            return returnStr;
        }
        if(ra.demo_purpose2__c=='索赔QIS' && ra.next_action__c=='无偿更换' && ra.QIS_number__r.ReplaceDeliveryDate__c!= null){
            returnStr = '索赔QIS目的，QIS已有新品发货日，不可出库指示';
            return returnStr;
       }
        //1822 yc 20211111 end

//*************************Insert 20160826 SWAG-AD59Z6 趙徳芳 Start*************************//
        if(Ra.repair__r.Repair_Final_Inspection_Date__c != null) {
            return '修理最终检测日不为空，不能做出库指示';
        }
        if(Ra.repair__c!=null&&Ra.repair__r.Return_Without_Repair_Date__c != null) {
            return '未修理归还日不为空，不能做出库指示';
        }
//*************************Insert 20160826 SWAG-AD59Z6 趙徳芳 End***************************//

        //1388 yc 20211021 跨区域分配不能出库 start
        if(String.isNotBlank(ra.Cross_Region_Assign__c)){
            String soql = 'select Id, Name,Rental_Apply__c,Internal_asset_location_before__c';
                   soql +=' from Rental_Apply_Equipment_Set_Detail__c';
                   soql +=' where Rental_Apply__c = \'' + ra.Id +'\'';
                   soql +=' and Internal_asset_location_before__c !=null and Internal_asset_location_before__c != \'' + ra.Cross_Region_Assign__c+ '\'';
            
            if(String.isNotBlank(rasdid)){
                   soql +=' and Rental_Apply_Equipment_Set__c = :rasdid';            
              }
            List<Rental_Apply_Equipment_Set_Detail__c> raesd = Database.query(soql);
            if(raesd.size()>0){
                returnStr = '分配的备品不是您所属备品中心的备品，不能做出库指示'; 
                return returnStr;
            }
            
        }
        //1388 yc 20211021 跨区域分配不能出库 end
        // 20220211 ljh add 备品FY23课题01 start
        // AggregateResult[] resultsRas = [SELECT Rental_Start_Date__c,count(Id) cnt
        //                              FROM Rental_Apply_Equipment_Set__c
        //                              WHERE Rental_Apply__c = :rentalApplyId 
        //                              AND Cancel_Select__c = false
        //                              group by Rental_Start_Date__c];
        // If(resultsRas.size() > 1){
        //  returnStr = '所有一览备品预计出货日应一致，不一致不能做出库指示'; 
        //     return returnStr;
        // }
        // 20220211 ljh add 备品FY23课题01 end

//bp2        // 备品借出历史取得
//        List<String> equipmentSetList = new List<String>();
//        Rental_Apply_Equipment_Set__c[] raes = [
//            select Id, Name, Equipment_Set__c, Equipment_Set__r.Name, Rental_Start_Date__c, Rental_End_Date__c, Rental_Apply__c 
//              from Rental_Apply_Equipment_Set__c 
//             where Rental_Apply__c = :rentalApplyId and Cancel_Select__c = false];
//        // 日历范围，最小的借出开始日到最大的借出终了日
//        Date startDate = Date.today();
//        Date endDate = Date.today();
//        for (Rental_Apply_Equipment_Set__c r : raes) {
//            equipmentSetList.add(r.Equipment_Set__c);
//            if (r.Rental_Start_Date__c != null && r.Rental_Start_Date__c < startDate) {
//                startDate = r.Rental_Start_Date__c;
//            }
//            if (r.Rental_End_Date__c != null && r.Rental_End_Date__c > endDate) {
//                endDate = r.Rental_End_Date__c;
//            }
//        }
//        Integer prepareDay = ra.Prepare_Day__c == null ? Integer.valueOf(System.Label.EquipmentRentalPrepare) : ra.Prepare_Day__c.intValue();
//        Date minDate = getWD_addday(startDate, -1 * prepareDay);
//        Date maxDate = getWD_addday(endDate, prepareDay);
//        // 其他备品借出申请历史
//        Rental_Apply_Equipment_Set__c[] others = [
//                    select Id, Name, Rental_Start_Date__c, Rental_End_Date__c, Equipment_Set__c, Rental_Apply__r.Status__c ,Rental_Apply__r.Prepare_Day__c 
//                      from Rental_Apply_Equipment_Set__c
//                     where Rental_Apply__c != :rentalApplyId
//                       and Equipment_Set__c in :equipmentSetList
//                       and Request_Status__c != '取消'
//                       and Request_Status__c != '删除'
//                       and Cancel_Select__c = false
//                       and ((Rental_Start_Date__c >= :minDate and Rental_Start_Date__c <= :maxDate)
//                            or (Rental_End_Date__c >= :minDate and Rental_End_Date__c <= :maxDate)
//                            or (Rental_Start_Date__c <= :startDate and Rental_End_Date__c >= :endDate))];
        
//        Map<String, List<Rental_Apply_Equipment_Set__c>> othersMap = new Map<String,List<Rental_Apply_Equipment_Set__c>>();
//        for (Rental_Apply_Equipment_Set__c other : others) {
//            if (othersMap.containsKey(other.Equipment_Set__c)) {
//                othersMap.get(other.Equipment_Set__c).add(other);
//            } else {
//                List<Rental_Apply_Equipment_Set__c> l = new List<Rental_Apply_Equipment_Set__c>();
//                l.add(other);
//                othersMap.put(other.Equipment_Set__c, l);
//            }
//        }
        
//        for (Rental_Apply_Equipment_Set__c r : raes) {
            
//            List<Rental_Apply_Equipment_Set__c> other = othersMap.get(r.Equipment_Set__c);
            
//            Map<Date, Map<String, String>> dateMap= new Map<Date, Map<String, String>>();
//            if (other != null) {
//                Date sdate = startDate;
//                Date edate = endDate;
//                for (Rental_Apply_Equipment_Set__c o : other) {
//                    if (o.Rental_Start_Date__c != null && (sdate == null || o.Rental_Start_Date__c < sdate)) {
//                        sdate = o.Rental_Start_Date__c;
//                    }
//                    if (o.Rental_End_Date__c != null && (edate == null || o.Rental_End_Date__c > edate)) {
//                        edate = o.Rental_End_Date__c;
//                    }
//                }
//                if (sdate != null && edate != null) {
//                    RentalApplyWebService raws = new RentalApplyWebService();
//                    dateMap = raws.getDateMap(sdate, edate, prepareDay);
//                }
//            }
            
//            if (r.Rental_Start_Date__c == null && r.Rental_End_Date__c == null) {
//                // 清空该借出历史的出库和回收时间
//            } else if (other == null || other.size() == 0) {
//                // 与其他借出历史没有冲突
//            } else {
//                Date fromDate = r.Rental_Start_Date__c;
//                Date toDate = r.Rental_End_Date__c;
//                for (Rental_Apply_Equipment_Set__c o : other) {
//                    if (o.Rental_Apply__r.Status__c != '草案中' && o.Rental_Apply__r.Status__c != '申请中' && o.Rental_Apply__r.Status__c != null) {
//                        Date startD = o.Rental_Start_Date__c;
//                        Date endD = o.Rental_End_Date__c;
//                        Integer prepare = prepareDay; //>= o.Rental_Apply__r.Prepare_Day__c || o.Rental_Apply__r.Prepare_Day__c == null ? prepareDay : o.Rental_Apply__r.Prepare_Day__c.intValue();
//                        if ((dateMap.containsKey(fromDate) && Date.valueOf(dateMap.get(fromDate).get('Next')) > startD && dateMap.containsKey(endD) && fromDate < Date.valueOf(dateMap.get(endD).get('Next'))) ||
//                            (dateMap.containsKey(toDate) && Date.valueOf(dateMap.get(toDate).get('Next')) > startD && dateMap.containsKey(endD) && toDate < Date.valueOf(dateMap.get(endD).get('Next'))) ||
//                            (dateMap.containsKey(fromDate) && Date.valueOf(dateMap.get(fromDate).get('Next')) <= startD && dateMap.containsKey(endD) && toDate >= Date.valueOf(dateMap.get(endD).get('Next')))) {
//                            returnStr = '备品' + r.Equipment_Set__r.Name + '的借出日与备品借出历史' + o.Name + '有冲突，请确认。';
//                            return returnStr;
//                        }
//                    }
//                }
//            }
//        }
        return '1';
    }
    
    @AuraEnabled
    public static String setShipment_requests(String raid, String raesid) {
      Savepoint sp = Database.setSavepoint();

      try {
        //一览情况下检索一览对应的申请书Id，soql子查询不能和主查询是同一个表，单独检索一次
        if (String.isBlank(raid)) {
            List<Rental_Apply_Equipment_Set__c> raList = [select Id, Rental_Apply__c from Rental_Apply_Equipment_Set__c where id = :raesid];
            if (raList.size() > 0) {
                raid = raList[0].Rental_Apply__c;
            } else {
                //应该不会到这里
                return '没有可以出库指示的一览';
            }
        }
        String soql = 'SELECT Id'
                + ' FROM Rental_Apply_Equipment_Set__c '
                + ' WHERE Shippment_loaner_time2__c <> null '
                + ' AND Rental_Apply__c = :raid '
                + ' ORDER BY Id' ;
        List<Rental_Apply_Equipment_Set__c> shippedRaesList = Database.query(soql);
        String raesStrShipped = '';
        for (Rental_Apply_Equipment_Set__c raes : shippedRaesList) {
            raesStrShipped += raes.Id;
        }

        //Srring soql = "SELECT Id FROM Rental_Apply_Equipment_Set_Detail__c WHERE Rental_Apply__c = '{!Rental_Apply__c.Id}' AND Cancel_Select__c = false AND Rental_Num__c > 0 AND Rental_Apply_Equipment_Set__r.Wei_Assigned_Cnt__c = 0 AND Rental_Apply_Equipment_Set__r.Yi_Assigned_Cnt__c > 0 AND Shipment_request__c  = false";
        soql = 'SELECT Id, Rental_Apply__c, Rental_Apply_Equipment_Set__c'
                + ' FROM Rental_Apply_Equipment_Set_Detail__c '
                + ' WHERE ' + (String.isNotBlank(raesid) ? 'Rental_Apply_Equipment_Set__c = :raesid ' : 'Rental_Apply__c = :raid ')
                + ' AND Cancel_Select__c = false '
                + ' AND Rental_Num__c > 0 '
                + ' AND Rental_Apply_Equipment_Set__r.Wei_Assigned_Cnt__c = 0 '
                + ' AND Rental_Apply_Equipment_Set__r.Yi_Assigned_Cnt__c > 0 '
                + ' AND Shipment_request__c  = false'
                + ' ORDER BY Rental_Apply_Equipment_Set__c, Id';
        List<Rental_Apply_Equipment_Set_Detail__c> raesds = Database.query(soql);

        Map<Id, List<String>> rental_Asset_SerialNumberMap = new Map<Id, List<String>>();

        if (raesds.size() < 1) {
            return '没有可以出库指示的一览';
        } else {
            Set<Id> raesSet = new Set<Id>();
            String raesStrRequest = '';
            for (Rental_Apply_Equipment_Set_Detail__c raesd : raesds) {
                if (false == raesSet.contains(raesd.Rental_Apply_Equipment_Set__c)) {
                    raesSet.add(raesd.Rental_Apply_Equipment_Set__c);
                    raesStrRequest += raesd.Rental_Apply_Equipment_Set__c;
                }
                raesd.Shipment_request_time2__c = Datetime.now();
                raesd.Shipment_request__c = true;
            }
            // 出库后, 再次做出库指示的一览, 一定要个出过库的一览一样
            if (false == String.isBlank(raesStrShipped) && raesStrRequest != raesStrShipped) {
                return '不能做出库指示，需要分单后再操作';
            }
        }

        // add lc 20220927 SFDC-CJ48VE 备品预计出库日逻辑调整 start
        List<Rental_Apply_Equipment_Set__c> RAESRecords = [
                SELECT Id,Rental_Start_Date__c 
                FROM Rental_Apply_Equipment_Set__c 
                WHERE Rental_Apply__c = :raid
                AND Cancel_Select__c = False];

        for (Integer i = 0; i < RAESRecords.size(); i++) {
            // 备品预计出库日不一致，不可出库指示
            if (RAESRecords[i].Rental_Start_Date__c != RAESRecords[0].Rental_Start_Date__c) {
                return '备品预计出货日不一致，不可出库指示';
            }
        }
        // add lc 20220927 SFDC-CJ48VE 备品预计出库日逻辑调整 end

        Rental_Apply__c ra = new Rental_Apply__c(Id = raesds[0].Rental_Apply__c, Status__c = '已出库指示');
        update ra;
        Database.SaveResult[] results = Database.update(raesds);
        Database.SaveResult dmlResult = results[0];
        if (dmlResult.isSuccess()) {
            //明细更新成功后才更新一览的Rental_Asset_SerialNumber__c
            soql = 'SELECT Id, SerialNumber_text__c, Rental_Apply_Equipment_Set__c '
                    +'FROM Rental_Apply_Equipment_Set_Detail__c '
                    +'WHERE Rental_Apply__c = \'' + raesds[0].Rental_Apply__c + '\''
                    +'AND Shipment_request_time2__c != null '
                    +'AND Shipment_request__c = true '
                    +'AND SerialNumber_text__c != null '
                    +'ORDER BY Rental_Apply_Equipment_Set__c ';


            List<Rental_Apply_Equipment_Set_Detail__c> raesdSerialNumbers = Database.query(soql);

            for (Rental_Apply_Equipment_Set_Detail__c raesd : raesdSerialNumbers) {

                if (!rental_Asset_SerialNumberMap.containsKey(raesd.Rental_Apply_Equipment_Set__c)) {
                    // Asset__r.SerialNumber + ','
                    rental_Asset_SerialNumberMap.put(raesd.Rental_Apply_Equipment_Set__c, new List<String>());
                }
                rental_Asset_SerialNumberMap.get(raesd.Rental_Apply_Equipment_Set__c).add(raesd.SerialNumber_text__c);
            }

            List<Rental_Apply_Equipment_Set__c> raess = new List<Rental_Apply_Equipment_Set__c>();
            for (Id key : rental_Asset_SerialNumberMap.keySet()) {
                raess.add(new Rental_Apply_Equipment_Set__c(Id = key,
                        Rental_Asset_SerialNumber__c = ',' + String.join(rental_Asset_SerialNumberMap.get(key), ',') + ','));
            }
            if (!raess.isEmpty()) {
                update raess;
            }

            return '状态更新到已出库指示';
        } else {
            Database.rollback(sp);
            Database.Error emsg = dmlResult.getErrors()[0];
            return 'failed to update:' + emsg.getFields() +  ' ' + emsg.getMessage();
        }
      } catch (Exception ex) {
        Database.rollback(sp);
        // return ex.getMessage();
        return ex.getDmlMessage(0);// 2023-10-19 WYL
      }
    }
    
    @AuraEnabled
    public static String postponeCheck(String endDate, Integer i) {
        Date d=Date.valueOf(endDate);
        // return 'OK1';S
        Date selectDate;
        if (d == Date.valueOf('4000-12-31')) {
            selectDate=d;
        } else if (i >= 0) {
            List<OlympusCalendar__c> workday = [
                    select Id, Date__c, IsWorkDay__c 
                      from OlympusCalendar__c 
                     where Date__c >= :d 
                       and IsWorkDay__c = 1
                     order by Date__c
                     limit :(i+1)];
            selectDate = workday[i].Date__c;
            return 'OK1';
            // if (Date.today() > selectDate) {
            //     return System.Label.EquipmentRentalPostponeOverDeadline;
            // }
        } else {
            i = Math.abs(i);
            List<OlympusCalendar__c> workday = [
                    select Id, Date__c, IsWorkDay__c 
                      from OlympusCalendar__c 
                     where Date__c <= :d 
                       and IsWorkDay__c = 1
                     order by Date__c desc
                     limit :(i+1)];
            selectDate = workday[i].Date__c;
        }

        if (Date.today() > selectDate) {
            return System.Label.EquipmentRentalPostponeOverDeadline;
        }
        return 'OK';

        // Date before5day = getWD_addday(date.parse(endDate), d);
        // return 'OK2';
        // if (Date.today() > before5day) {
        //     return System.Label.EquipmentRentalPostponeOverDeadline;
        // }
        // return 'OK';
    }

    // public static Date getWD_addday(Date d, Integer i) {
        
    // }

    @AuraEnabled
    public static String submitApprovalRequest(String recordId) {
        try{
           Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();
           req.setObjectId(recordId);
           Approval.ProcessResult result = Approval.process(req);
           if(result.getErrors()!=null&&result.getErrors().size()>0)return result.getErrors().get(0).getMessage();
        }catch(Exception e){
            System.debug(' submitApprovalRequest  error: '+e.getMessage());
            // return e.getMessage();
            return e.getDmlMessage(0);// 2023-10-19 WYL
        }
        return null;
    }
    @AuraEnabled
    public static String getUserinfo() {
        String username = UserInfo.getName();
        return username;
    }

    @AuraEnabled
    public static ID getUserid() {
        ID userid = UserInfo.getUserId();
        return userid;
    }
    @AuraEnabled
    public static ID getUserPid() {
        ID userid = UserInfo.getProfileId();
        return userid;
    }
    public class UpdateResult {
        @AuraEnabled public String recordId {get;set;}
        @AuraEnabled public Boolean success {get;set;}
        @AuraEnabled public List<String> errors {get;set;}
    }
    public class InitData{
        @AuraEnabled
        public String id;
        @AuraEnabled
        public String RentalApplyId;
        @AuraEnabled
        public String Status;
        @AuraEnabled
        public String RentalApplyC;
        @AuraEnabled
        public Decimal WeiAssignedCntC;
        @AuraEnabled
        public Date BollowDateC;
        @AuraEnabled
        public Decimal AssignedNotShipmentC;
        @AuraEnabled
        public List<String> statusList;
    }
}