global class RentalApplyWebService {
    // TODO please use public okStatus
    public final static Integer okStatus = 99;
    public final static String okStatus2 = '引当済';

//bp2
//    /**
//     * check meisai
//     * @param rentalApplyId            备品借出申请ID
//     * @param rentalApplys             备品借出申请
//     * @param rentalApplyEquipmentSets 备品申请借出历史(备品借出申请 和 备品Set 的Link表)
//     * @param equipmentSetIdList       Equipment_Set__c.id
//     * @param idmap                    Equipment_Set__c.Id => Rental_Apply_Equipment_Set__c.Id
//     * @return 成功: 1、or 错误内容
//     */
//    private static String privateCheck(String rentalApplyId,
//            Map<String, List<List<Rental_Apply__c>>> mRentalApplys,
//            Map<String, List<List<Rental_Apply_Equipment_Set__c>>> mRentalApplyEquipmentSets,
//            Map<String, List<List<Id>>> mEquipmentSetIdList,
//            Map<String, List<Map<Id, Id>>> mIdmap
//    ) {
//        List<Rental_Apply__c> rentalApplys = mRentalApplys.get('rentalApplys')[0];
//        List<Rental_Apply_Equipment_Set__c> rentalApplyEquipmentSets = mRentalApplyEquipmentSets.get('rentalApplyEquipmentSets')[0];
//        List<Id> equipmentSetIdList = mEquipmentSetIdList.get('equipmentSetIdList')[0];
//        Map<Id, Id> idmap = mIdmap.get('idmap')[0];

//        //返回结果,1:成功。
//        String checkRS = '1';
        
//        //备品借出申请
//        rentalApplys = [select Rental_Apply_Equipment_Set_Cnt__c from Rental_Apply__c where Id = :rentalApplyId];
//        if (rentalApplys.size() == 0) {
//            checkRS = '没有备品借出申请，请确认。';
//            return checkRS;
//        }
//        Rental_Apply__c rentalApply = rentalApplys[0];
//        if (rentalApply.Rental_Apply_Equipment_Set_Cnt__c <= 0) {
//            //返回结果,2:message-没有备品Set，请确认。
//            checkRS = '没有借出备品set一览，请确认。';
//            return checkRS;
//        }
        
//        //备品申请借出历史
//        equipmentSetIdList = new List<Id>();
//        rentalApplyEquipmentSets = [
//                select Equipment_Set__c,Equipment_Set__r.Active_judgement__c
//                  from Rental_Apply_Equipment_Set__c
//                 where Rental_Apply__c = :rentalApplyId and Cancel_Select__c = false];
//        for (Rental_Apply_Equipment_Set__c rentalApplyEquipmentSet : rentalApplyEquipmentSets) {
//            equipmentSetIdList.add(rentalApplyEquipmentSet.Equipment_Set__c);
//        }

//        // Equipment_Set_Detail__c，空更新 (TODO 今後batchになる！？)
//        List<Equipment_Set_Detail__c> updDetailList = [
//                select id
//                  from Equipment_Set_Detail__c
//                 where Equipment_Set__c in :equipmentSetIdList];
//        update updDetailList;

//        //备品申请借出历史、再取得
//        List<Rental_Apply_Equipment_Set__c> raesList = new List<Rental_Apply_Equipment_Set__c>();
//        equipmentSetIdList = new List<Id>();
        
//        rentalApplyEquipmentSets = [
//                select Id,Name,Equipment_Set__c,ES_Stock_Status__c,Loaner_name_text__c,Loaner_code_text__c,SerialNumber_text__c,
//                        Salesdepartment_text__c,Salesprovince_text__c,Equipment_Type_text__c,Equipment_Set_Borrowed__c,Product_Class_Bor__c,
//                        Equipment_Set__r.Name,Equipment_Set__r.ES_Status__c,Equipment_Set__r.Active_judgement2__c,
//                        Equipment_Set__r.Last_Reserve_Rental_Apply_Equipment_Set__c,Rental_Start_Date__c,
//                        Equipment_Set__r.Already_Stock_Out__c, Equipment_Set__r.Loaner_name__c,
//                        Equipment_Set__r.Loaner_code__c,Equipment_Set__r.Salesdepartment__c,
//                        Equipment_Set__r.SalesProvince__c,Equipment_Set__r.Equipment_Type__c,Equipment_Set__r.SerialNumber__c,
//                        Equipment_Set__r.Contents_number__c,Equipment_Set__r.Product_category__c
//                  from Rental_Apply_Equipment_Set__c
//                 where Rental_Apply__c = :rentalApplyId and Cancel_Select__c = false];
//        idmap = new Map<Id,Id>();    // Equipment_Set__c.Id => Rental_Apply_Equipment_Set__c.Id
        
//        for (Rental_Apply_Equipment_Set__c rentalApplyEquipmentSet : rentalApplyEquipmentSets) {
//            if (rentalApplyEquipmentSet.Equipment_Set__r.Last_Reserve_Rental_Apply_Equipment_Set__c != rentalApplyEquipmentSet.Id) {
//                raesList.add(rentalApplyEquipmentSet);
//                equipmentSetIdList.add(rentalApplyEquipmentSet.Equipment_Set__c);
//            }
//        }
        
//        for (Rental_Apply_Equipment_Set__c rentalApplyEquipmentSet : raesList) {
//            /*
//            if (rentalApplyEquipmentSet.Rental_Start_Date__c <= Date.today()) {
//                checkRS = '借出开始日必须大于今日。借出备品set一览：' + rentalApplyEquipmentSet.Name;
//                return checkRS;
//            }
//            */
//            /*
//            if (rentalApplyEquipmentSet.Equipment_Set__r.Active_judgement2__c != okStatus) {
//                //返回结果,1:message-请确认备品Set状态。
//                checkRS = '备品set ' + rentalApplyEquipmentSet.Equipment_Set__r.Name + ' 的' + Schema.SObjectType.Equipment_Set__c.fields.Asset_Set_status2__c.label + '不是 99.等待预约 ，现在是 ' + rentalApplyEquipmentSet.Equipment_Set__r.Asset_Set_status2__c + ' 请确认';
//                return checkRS;
//            }
//            */
//            //
////bp2            if (rentalApplyEquipmentSet.Equipment_Set__r.Contents_number__c == 0) {
////bp2                checkRS = '备品set ' + rentalApplyEquipmentSet.Equipment_Set__r.Name + ' 没有选择借出的明细，请确认';
////bp2                return checkRS;
////bp2            }
////bp2            if (rentalApplyEquipmentSet.Equipment_Set__r.ES_Status__c != okStatus2) {
////bp2                checkRS = '备品set ' + rentalApplyEquipmentSet.Equipment_Set__r.Name + ' 的' + Schema.SObjectType.Equipment_Set__c.fields.ES_Status__c.label + '不是 ' + okStatus2 + '，现在是 ' + rentalApplyEquipmentSet.Equipment_Set__r.ES_Status__c + ' 请确认';
////bp2                return checkRS;
////bp2            }
////bp2            if (rentalApplyEquipmentSet.Equipment_Set__r.Already_Stock_Out__c == true) {
////bp2                checkRS = '备品set ' + rentalApplyEquipmentSet.Equipment_Set__r.Name + ' 没有上架，请确认';
////bp2                return checkRS;
////bp2            }
////bp2            if (rentalApplyEquipmentSet.ES_Stock_Status__c == '不能出库') {
////bp2                checkRS = '备品set ' + rentalApplyEquipmentSet.Equipment_Set__r.Name + ' 在预约期间外不能出库，请确认';
////bp2                return checkRS;
////bp2            }
//            idmap.put(rentalApplyEquipmentSet.Equipment_Set__c, rentalApplyEquipmentSet.Id);
//        }
//        mRentalApplys.get('rentalApplys')[0] = rentalApplys;
//        mRentalApplyEquipmentSets.get('rentalApplyEquipmentSets')[0] = raesList;
//        mEquipmentSetIdList.get('equipmentSetIdList')[0] = equipmentSetIdList;
//        mIdmap.get('idmap')[0] = idmap;
//        return checkRS;
//    }

//bp2
//    /**
//     *@param  : String 备品借出申请ID
//     *@return : String (成功: 1、or 错误内容)
//     */
//    WebService static String reserveCheck(String rentalApplyId) {
//        //备品借出申请
//        List<Rental_Apply__c> rentalApplys = new List<Rental_Apply__c>();
//        //备品申请借出历史
//        List<Rental_Apply_Equipment_Set__c> rentalApplyEquipmentSets = new List<Rental_Apply_Equipment_Set__c>();
//        List<Id> equipmentSetIdList = new List<Id>();
//        Map<Id, Id> idmap = new Map<Id,Id>();    // Equipment_Set__c.Id => Rental_Apply_Equipment_Set__c.Id

//        Map<String, List<List<Rental_Apply__c>>> mRentalApplys =
//                new Map<String, List<List<Rental_Apply__c>>>{'rentalApplys' => new List<List<Rental_Apply__c>>{rentalApplys}};
//        Map<String, List<List<Rental_Apply_Equipment_Set__c>>> mRentalApplyEquipmentSets =
//                new Map<String, List<List<Rental_Apply_Equipment_Set__c>>>{'rentalApplyEquipmentSets' => new List<List<Rental_Apply_Equipment_Set__c>>{rentalApplyEquipmentSets}};
//        Map<String, List<List<Id>>> mEquipmentSetIdList =
//                new Map<String, List<List<Id>>>{'equipmentSetIdList' => new List<List<Id>>{equipmentSetIdList}};
//        Map<String, List<Map<Id, Id>>> mIdmap =
//                new Map<String, List<Map<Id, Id>>>{'idmap' => new List<Map<Id, Id>>{idmap}};

//        String rt1 = RentalApplyWebService.approvalCheck(rentalApplyId);
//        if (rt1 != '1') {
//            return rt1;
//        }
//        //返回结果,1:成功。
////        return RentalApplyWebService.privateCheck(rentalApplyId, mRentalApplys, mRentalApplyEquipmentSets, mEquipmentSetIdList, mIdmap);
//        String rt2 = RentalApplyWebService.privateCheck(rentalApplyId, mRentalApplys, mRentalApplyEquipmentSets, mEquipmentSetIdList, mIdmap);
//        if (rt2 != '1') {
//            return rt2;
//        }
//        return '1';
//    }

//bp2
//    /**
//     *@param  : String 备品借出申请ID
//     *@return : String (成功: 1、or 错误内容)
//     */
//    WebService static String reserve(String rentalApplyId) {
//        //备品借出申请
//        List<Rental_Apply__c> rentalApplys = new List<Rental_Apply__c>();
//        //备品申请借出历史
//        List<Rental_Apply_Equipment_Set__c> rentalApplyEquipmentSets = new List<Rental_Apply_Equipment_Set__c>();
//        List<Id> equipmentSetIdList = new List<Id>();
//        Map<Id, Id> idmap = new Map<Id,Id>();    // Equipment_Set__c.Id => Rental_Apply_Equipment_Set__c.Id

//        Map<String, List<List<Rental_Apply__c>>> mRentalApplys =
//                new Map<String, List<List<Rental_Apply__c>>>{'rentalApplys' => new List<List<Rental_Apply__c>>{rentalApplys}};
//        Map<String, List<List<Rental_Apply_Equipment_Set__c>>> mRentalApplyEquipmentSets =
//                new Map<String, List<List<Rental_Apply_Equipment_Set__c>>>{'rentalApplyEquipmentSets' => new List<List<Rental_Apply_Equipment_Set__c>>{rentalApplyEquipmentSets}};
//        Map<String, List<List<Id>>> mEquipmentSetIdList =
//                new Map<String, List<List<Id>>>{'equipmentSetIdList' => new List<List<Id>>{equipmentSetIdList}};
//        Map<String, List<Map<Id, Id>>> mIdmap =
//                new Map<String, List<Map<Id, Id>>>{'idmap' => new List<Map<Id, Id>>{idmap}};

//        //返回结果,1:成功。
//        String checkRS = RentalApplyWebService.privateCheck(rentalApplyId, mRentalApplys, mRentalApplyEquipmentSets, mEquipmentSetIdList, mIdmap);
//        if (checkRS != '1') return checkRS;
//        rentalApplys = mRentalApplys.get('rentalApplys')[0];
//        rentalApplyEquipmentSets = mRentalApplyEquipmentSets.get('rentalApplyEquipmentSets')[0];
//        equipmentSetIdList = mEquipmentSetIdList.get('equipmentSetIdList')[0];
//        idmap = mIdmap.get('idmap')[0];

//        Rental_Apply__c rentalApply = rentalApplys[0];

//        //备品Set
//        List<Equipment_Set__c> equipmentSetUpdateList = new List<Equipment_Set__c>();
//        //备品Set明细
//        List<Equipment_Set_Detail__c> equipmentSetDetailList = new List<Equipment_Set_Detail__c>();
//        List<Equipment_Set_Detail__c> equipmentSetDetailList2 = new List<Equipment_Set_Detail__c>();
//        //备品申请借出明细历史
//        List<Rental_Apply_Equipment_Set_Detail__c> rentalApplyEquipmentSetDetailList = new List<Rental_Apply_Equipment_Set_Detail__c>();
//        for (Rental_Apply_Equipment_Set__c rentalApplyEquipmentSet : rentalApplyEquipmentSets) {
//            // 已做出库指示flag⇒前回の申請はまだ終わってない⇒出库しない
//            if (rentalApplyEquipmentSet.Equipment_Set__r.Already_Stock_Out__c == false) {
//                //更新备品Set
//                Equipment_Set__c equipmentSet = new Equipment_Set__c(
//                    Id = rentalApplyEquipmentSet.Equipment_Set__c,
//                    Last_Reserve_Rental_Apply_Equipment_Set__c = rentalApplyEquipmentSet.Id,
//                    Pre_Reserve_Rental_Apply_Equipment_Set__c = rentalApplyEquipmentSet.Equipment_Set__r.Last_Reserve_Rental_Apply_Equipment_Set__c,
//                    StockDown__c = false,
//                    StockDown_time__c = null,
//                    Shipment_request_time__c = System.now(),            //出库指示时间
//                    Shippment_loaner_time__c = null,            //备品中心出库时间
//                    Forecast_arrival_day__c = null,             //预计到货日
//                    //Loaner_received_day__c = null,              //现场签收日
//                    Return_wh_chenk_staff__c = null,
//                    Request_asset_extend_time__c = null,        //延期申请时间
//                    asset_extend_approval_time__c = null,       //延期申请批准时间
//                    //Asset_return_day__c = null,                 //物流提货日
//                    Received_loaner_time__c = null,             //备品中心回收时间
//                    delivery_company__c = null,
//                    Fedex_number__c = null,
//                    Distributor_method__c = null,
//                    Return_to_wh_staff__c = null,
//                    Return_delivery_company__c = null,
//                    Return_Fedex_number__c = null,
//                    Return_Distributor_method__c = null,
//                    Received_confirmation_staff__c = null,
//                    Customer_install_explanation_sign__c = null, //是否回收CDS确认单
//                    Send_to_return_email__c = false, //发送回收结果反馈邮件
//                    Return_comment_anoucment__c = null, //发送回收结果反馈内容(NG理由和欠品情况)
////bp2                    CDS_complete__c = false,
//                    Arrival_in_wh__c = false,
//                    Arrival_wh_time2__c = null,
//                    Already_Stock_Out__c = true,

//                    Repair_Sum_Update__c = 0
//                );
//                //更新备品Set
//                equipmentSetUpdateList.add(equipmentSet);
//            }
//        }

//        //借出设备机身号码
//        Map<String, String> assetSerialNumberMap = new Map<String, String>();
//        //备品Set明细
//        Equipment_Set_Detail__c[] equipmentSetDetails = [select Equipment_Set__c,Asset__c,Asset__r.SerialNumber,
//                                            Check_lost_Item__c,Pre_disinfection__c,Water_leacage_check__c,
//                                            Inspection_result_after__c,Arrival_in_wh__c,
//                                            Lost_item_check_staff__c,CDS_staff__c,Inspection_staff_After__c,
//                                            Return_wh_chenk_staff__c,Pre_inspection_time__c,Lost_item_check_time__c,
//                                            After_Inspection_time__c,Arrival_wh_time__c,
//                                            Inspection_result__c,Inspection_staff__c,Last_Reserve_RAES_Detail__c,
//                                            Equipment_Set__r.Already_Stock_Out__c
////bp2            , CDS_complete__c, CDS_complete_time__c
//                                            from Equipment_Set_Detail__c
//                                            where Equipment_Set__c in :equipmentSetIdList and Select_rental__c = true];
        
//        for (Equipment_Set_Detail__c equipmentSetDetail : equipmentSetDetails) {
//            // 已做出库指示flag⇒前回の申請はまだ終わってない⇒出库しない
//            if (equipmentSetDetail.Equipment_Set__r.Already_Stock_Out__c == false) {
//                //插入备品申请借出明细历史
//                Rental_Apply_Equipment_Set_Detail__c rentalApplyEquipmentSetDetail = new Rental_Apply_Equipment_Set_Detail__c();
//                rentalApplyEquipmentSetDetail.Rental_Apply__c = rentalApply.Id;//备品借出申请
//                rentalApplyEquipmentSetDetail.Rental_Apply_Equipment_Set__c = idmap.get(equipmentSetDetail.Equipment_Set__c);//备品Set借出历史
//                rentalApplyEquipmentSetDetail.Equipment_Set__c = equipmentSetDetail.Equipment_Set__c;//备品Set
//                rentalApplyEquipmentSetDetail.Asset__c = equipmentSetDetail.Asset__c;//保有设备
//                //插入备品申请借出明细历史
//                rentalApplyEquipmentSetDetailList.add(rentalApplyEquipmentSetDetail);
                
//                //更新备品Set明细
//                equipmentSetDetail.Check_lost_Item__c = null;//欠品确认结果
//                equipmentSetDetail.Lost_item_giveup__c = false;
//                equipmentSetDetail.Pre_disinfection__c = null;//清洗前
//                equipmentSetDetail.Water_leacage_check__c = null;//测漏检查结果
//                equipmentSetDetail.Inspection_result_after__c = null;//回收后-检测结果
//                equipmentSetDetail.Arrival_in_wh__c = false;//回库确认
//                equipmentSetDetail.Lost_item_check_staff__c = null;//欠品确认者
//                equipmentSetDetail.CDS_staff__c = null;//消毒人员
//                equipmentSetDetail.Inspection_staff_After__c = null;//回收后-检测人员
//                equipmentSetDetail.Return_wh_chenk_staff__c = null;//回库确认者
//                equipmentSetDetail.Inspection_result__c = null;//发货前-检测结果
//                equipmentSetDetail.Inspection_staff__c = null;//发货前-检测人员
                
//                equipmentSetDetail.Pre_inspection_time__c = null;//备品Set用,发货前-检测合格时间
//                equipmentSetDetail.Lost_item_check_time__c = null;//备品Set用,欠品确认时间
////bp2                equipmentSetDetail.CDS_complete_time__c = null;//备品Set用,CDS完毕时间
//                equipmentSetDetail.After_Inspection_time__c = null;//备品Set用,回收后-检测完毕时间
//                equipmentSetDetail.Arrival_wh_time__c = null;//备品Set用,回库确认完毕时间

//                equipmentSetDetail.Inspection_result_after_ng__c = null;//回收后-检测NG区分
//                equipmentSetDetail.Inspection_result_ng__c = null;//发货前-检测NG区分
////bp2                equipmentSetDetail.CDS_complete__c = false;//CDS完毕

//                //更新备品Set明细
//                equipmentSetDetailList.add(equipmentSetDetail);
//                //借出设备机身号码
//                if (String.isNotBlank(equipmentSetDetail.Asset__r.SerialNumber)) {
//                    if (assetSerialNumberMap.containsKey(equipmentSetDetail.Equipment_Set__c) == false) {
//                        assetSerialNumberMap.put(equipmentSetDetail.Equipment_Set__c, ',' + equipmentSetDetail.Asset__r.SerialNumber + ',');
//                    } else {
//                        String tmp = assetSerialNumberMap.get(equipmentSetDetail.Equipment_Set__c);
//                        tmp += equipmentSetDetail.Asset__r.SerialNumber + ',';
//                        assetSerialNumberMap.put(equipmentSetDetail.Equipment_Set__c, tmp);
//                    }
//                }
//            }
//        }

//        // TODO liang １つsqlにまとめてください
//        Equipment_Set_Detail__c[] equipmentSetDetails2 = [select Id, Last_Reserve_RAES_Detail__c
////bp2                ,CDS_complete__c
//                                            from Equipment_Set_Detail__c
//                                            where Equipment_Set__c in :equipmentSetIdList and Select_rental__c = false];
//        for (Equipment_Set_Detail__c equipmentSetDetail : equipmentSetDetails2) {
//            equipmentSetDetail.Pre_Reserve_RAES_Detail__c = equipmentSetDetail.Last_Reserve_RAES_Detail__c;
//            equipmentSetDetail.Last_Reserve_RAES_Detail__c = null;
////bp2            equipmentSetDetail.CDS_complete__c = false;//CDS完毕
//            equipmentSetDetailList2.add(equipmentSetDetail);
//        }
        
//        //更新借出设备机身号码
//        List<Rental_Apply_Equipment_Set__c> rentalApplyEquipmentSetUpdateList = new List<Rental_Apply_Equipment_Set__c>();
//        for (Rental_Apply_Equipment_Set__c rentalApplyEquipmentSet : rentalApplyEquipmentSets) {
//            if (assetSerialNumberMap.containsKey(rentalApplyEquipmentSet.Equipment_Set__c)) {
//                rentalApplyEquipmentSet.Rental_Asset_SerialNumber__c = assetSerialNumberMap.get(rentalApplyEquipmentSet.Equipment_Set__c);
//              // xiongyl-start
//            }           
//             rentalApplyEquipmentSet.Loaner_name_text__c =rentalApplyEquipmentSet.Equipment_Set__r.Loaner_name__c; //备品名称
//             rentalApplyEquipmentSet.Loaner_code_text__c = rentalApplyEquipmentSet.Equipment_Set__r.Loaner_code__c; //備品型番
//             rentalApplyEquipmentSet.Salesdepartment_text__c = rentalApplyEquipmentSet.Equipment_Set__r.Salesdepartment__c; // 所在地区(本部)                
//             rentalApplyEquipmentSet.Salesprovince_text__c = rentalApplyEquipmentSet.Equipment_Set__r.SalesProvince__c; //所在地区(省)
//             rentalApplyEquipmentSet.Equipment_Type_text__c = rentalApplyEquipmentSet.Equipment_Set__r.Equipment_Type__c; //分类 
//             rentalApplyEquipmentSet.Equipment_Set_Borrowed__c = rentalApplyEquipmentSet.Equipment_Set__r.Name;//备品set
//             rentalApplyEquipmentSet.Product_Class_Bor__c = rentalApplyEquipmentSet.Equipment_Set__r.Product_category__c;
//             rentalApplyEquipmentSet.SerialNumber_text__c = rentalApplyEquipmentSet.Equipment_Set__r.SerialNumber__c;
//             rentalApplyEquipmentSetUpdateList.add(rentalApplyEquipmentSet);
//             // xiongyl-end
//        }

//        Savepoint sp = Database.setSavepoint();
//        try {
//            if (equipmentSetUpdateList.size() > 0) {
//                update equipmentSetUpdateList;
//            }
//            if (rentalApplyEquipmentSetDetailList.size() > 0) {
//                insert rentalApplyEquipmentSetDetailList;
//            }
//            if (equipmentSetDetailList.size() > 0) {
//                for (Integer i=0; i<equipmentSetDetailList.size(); i++) {
//                    equipmentSetDetailList[i].Pre_Reserve_RAES_Detail__c = equipmentSetDetailList[i].Last_Reserve_RAES_Detail__c;
//                    equipmentSetDetailList[i].Last_Reserve_RAES_Detail__c = rentalApplyEquipmentSetDetailList[i].Id;
//                }
//                update equipmentSetDetailList;
//            }
//            if (equipmentSetDetailList2.size() > 0) {
//                update equipmentSetDetailList2;
//            }
//            if (rentalApplyEquipmentSetUpdateList.size() > 0) {
//                update rentalApplyEquipmentSetUpdateList;
//            }
//            eSetRefreshStatus(equipmentSetIdList);
//        } catch (System.Exception e) {
//            Database.rollback(sp);
//            return e.getMessage();
//        }
//        //返回结果
//        return checkRS;
//    }
    
    // 备品借出时间check
    @AuraEnabled
    WebService 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(';'));
        }
        system.debug(rentalApplyId+'==aaa'); 
        //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];
        system.debug(rentalApplyId+'==aaa'+rentalApply.size());                                
        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';
    }

    // 延期审批Check
    @AuraEnabled
    WebService static String extension_approval_processCheck(String rentalApplyId) {
        try {
            List<Rental_Apply__c> raList = [SELECT Id,Name
                       , Demo_purpose1__c
                       , Demo_purpose2__c
                       , Loaner_received_ng_num__c
                       , ExtensionApprovalTime_Initial__c
                       , ExtensionApplicationTime_Final__c
                       , ExtensionApprovalTime_Final__c
                       , NewRepair__c
                       , NewRepair__r.Agreed_Date__c
                       , NewRepair__r.Status__c
                       , NewRepair__r.ReRepairObject_F__c
                       , NewRepair__r.Repair_Shipped_Date__c
                       , AgreementBorrowingExtensionDate__c
                       , next_action__c
                       , RC_Ordered_Date__c
                       , Bollow_Date_Add_10_WD__c
                       , Root_Rental_Apply__c
                       , Assign_Person__c
                       , Return_dadeline_final__c
                       , RA_Status__c
                       , ExtensionApplicationTime_Initial__c
                       , RecordType.DeveloperName
                       , RecordType.id
                       , ExtensionStatus__c
                    FROM Rental_Apply__c
                    WHERE Id = :rentalApplyId];
            if (raList.size() == 0) {
                return '没有备品借出申请，请确认。';
            }
            //add       wangweipeng            2021/11/26                   start
            /*List<Rental_Apply_Equipment_Set__c> raesList = RentalApplyTriggerHandler.getCan_Extend_RequestList(raList[0],'1');
            return '1';*/
            String ErrorMessageStr = unifyGetRentalApply(raList[0]);
            //add       wangweipeng            2021/11/26                   end
            return ErrorMessageStr;
        }
        catch(Exception e) {
            return e.getMessage();
        }
        
    }

    //add       wangweipeng            2021/11/26                   start
    /**
     * @param  rentalApplyId 备品id
     * @return               备品配套数据
     *
     * 延期整体逻辑：
     *     1：试用目的2不为：有询价和无询价，做特殊处理
     *     2：其他情况：逻辑不变
     *   上面第一个条件满足：
     *       1：从原单点击延期申请按钮，没有分割单
     *       2：从原单点击延期申请按钮，有分割单
     *       3：从单点击延期申请按钮
     *
     *      第一种情况：按照原来的逻辑走，不需要做特殊处理
     *      第二种情况：
     *          （1）：记录类型为：备品中心，判断分配人是否为空，办事处分配人不可能为空
     *          （2）：获取原单和原单下所有的分单，因为批量延期不光查看自己申请单情况，如果是主单进来的，还需要查看当前单子，和他下面的所有从单
     *          （2）：走一个方法，这是一个延期通用的方法，用于判断此次延期的申请单是否有可以延期的一览，会在下面具体介绍
     *          （3）：走上面通用的方法，没有获取到可以延期的一览，那么做提示，不能延期
     *          （4）：跳转页面为：此次为批量延期自定义开发的页面
     *      第三种情况：
     *          （1）：如果是从单延期，那么需要查看此单，此单的原单，此单原单下所有的从单是否满足延期条件
     *          （2）：以上的单子必须满足：已出库的--已回收（不含）之间状态，且最新预定归还日≥ 今天。
     *          （3）：走一个方法，这是一个延期通用的方法，用于判断此次延期的申请单是否有可以延期的一览，会在下面具体介绍
     *          （4）：由于通用的方法会返回所有申请单可延期的一览，所以需要判断此单是否有可以延期的一览
     *          （5）：由于通用的方法会跳过 ok并且回寄时间不为空的一览，所以此时判断这个条件，满足就不能延期
     *          （6）：跳转页面为原来延期开发的自定义页面
     *
     *     通用是否可以延期的方法：（试用（有询价）、试用（无询价））
     *         （1）：此方法参数为list，如果超过1条数据，默认为走批量延期的条件
     *         （2）：申请单：如果size大于1，跳过一些验证：未完成到货确认不验证和延期批准时间(最初)不能延期
     *         （3）：一览：如果size大于1，ok并且回寄时间不为空的一览不验证
     *          
     */
    public static String unifyGetRentalApply(Rental_Apply__c rentalApply){
        Rental_Apply__c rac = rentalApply;
        //如果申请单的 使用目2为 有询价或无询价的,那么需要特殊处理一下
        if(rac.Demo_purpose1__c == '产品试用' && (rac.demo_purpose2__c == '试用（无询价）' || rac.demo_purpose2__c == '试用（有询价）')){
            if(rac.ExtensionStatus__c == '已批准'){
                return '产品试用的申请不能提交第二次延期申请。';
            }else{
                return muchRentalApply(rac);
            }
        }else{
            //办事处目前只能延期有询价或无询价
            if(rac.RecordType.DeveloperName == 'AgencyRequest'){
                return '办事处申请单，非试用（无询价）、 试用（有询价）不可延期。';
            }else{
                List<Rental_Apply_Equipment_Set__c> raesList = RentalApplyTriggerHandler.getCan_Extend_RequestList(new List<Rental_Apply__c>{rac});
                return '1';
            }
        }
    }

    /**
     * 
     * @param  rac [延期入口]
     * @return     [description]
     *      
     * 逻辑解释：
     *     原单（没有从单）：走原来的逻辑
     *     从单：判断此从单的原单、原单下所有的从单是否满足第一条，并且当前从单必须有一条满足第二条才能延期
     *     原单（有从单）：判断此申请单和原单下所有的从单是否满足第一条，并且这些申请单最少有一个申请单满足第二个条件，才能延期
     */
    public static String muchRentalApply(Rental_Apply__c rac){
        //获取所有的申请单
        List<Rental_Apply__c> rentalApplyData =  getAllRentalApply(rac);
        if(rentalApplyData != null && rentalApplyData.size() > 0){
            //如果只查到一条数据，那么证明他是原单，并且没有分割单，那么就走原来延期的逻辑
            if(rentalApplyData.size() == 1){
                List<Rental_Apply_Equipment_Set__c> raesList = RentalApplyTriggerHandler.getCan_Extend_RequestList(rentalApplyData);
                return '1';
            }else{
                //如果为多条，证明他有从单或当前要延期的单子是从单，那么就需要做特殊处理
                List<Rental_Apply__c> racList = new List<Rental_Apply__c>();
                //判断他是原单还是从单
                System.debug('--345----------'+rac.Root_Rental_Apply__c);
                if(String.isNotBlank(rac.Root_Rental_Apply__c)){
                    //可延期的申请单应满足：已出库的--已回收（不含）之间状态，且最新预定归还日≥ 今天。
                    //当前日期
                    Date today = Date.today();
                    //预定归还日不能为空
                    if(rac.Return_dadeline_final__c != null){
                        //最新预定归还日≥ 今天。
                        if(rac.Return_dadeline_final__c >= today){
                            //可延期的申请单应满足：已出库的--已回收（不含）之间状态
                            if(rac.RA_Status__c == '申请者已收货' || rac.RA_Status__c == '医院已装机确认' || rac.RA_Status__c == '已出库')
                            {
                                //能走到这里，证明延期入口的申请单不是已经延过的，所有现在判断其他的申请单是否已经延期，如果延过，那么不需要验证
                                //if(rac.ExtensionApplicationTime_Initial__c == null){
                                    racList = rentalApplyData;
                                //}
                            }else{
                                if(rac.RA_Status__c != '取消' && rac.RA_Status__c != '删除'){
                                    return '申请单：'+rac.Name+'的状态为【'+rac.RA_Status__c+'】 不可以进行延期。';
                                }
                            }
                        }else{
                            return '申请单：'+rac.Name+'的最新预定归还日小于当前时间，不可以进行延期。';   
                        }
                    }else{
                        return '申请单：'+rac.Name+' 的预定归还日不能为空。';
                    }
                }else{
                    //备品中心
                    if(rac.RecordType.DeveloperName == 'StandardRequest'){
                        //a. 原单上分配人=空，点击原单上的【延期申请】按钮时，提示【原单未分配或已取消，请在分单上操作延期】
                        //注：原单未分配已取消或未分配时，原单分配人为空
                        if(String.isBlank(rac.Assign_Person__c)){
                            return '原单未分配或已取消，请在分单上操作延期。';
                        }
                    }
                    //如果是原单，直接判断是否满足第一和第二条，第三条不需要现在判断
                    racList = rentalApplyData;
                }
                if(racList != null && racList.size() > 0){
                    System.debug('-----------543---'+racList);
                    //此方法主要验证第一和第二个条件
                    List<Rental_Apply_Equipment_Set__c> raesList = RentalApplyTriggerHandler.getCan_Extend_RequestList(racList);
                    if(raesList.size() == 0){
                       return '无任何申请单满足。';
                    }else{
                        //如果从单为延期入口，会判断他的原单和此原单下所有从单满足延期条件
                        //如果满足条件，那么判断当前从单是否满足延期条件，如果是其他申请单满足，那么不能延期，
                        //如果此申请单有一个配套满足，那么可以延期，走单独延期逻辑（原来延期逻辑）
                        if(String.isNotBlank(rac.Root_Rental_Apply__c)){
                            Integer indexI = 0;
                            String racIds = rac.Id;
                            racIds = racIds.substring(0,15);
                            //循环判断此单是否有可以延期的配套吗？
                            for(Rental_Apply_Equipment_Set__c raesc : raesList){
                                String raescId = raesc.Rental_Apply__c;
                                raescId = raescId.substring(0,15);
                                if(racIds.equals(raescId)){
                                    indexI++;
                                }
                            }
                            if(indexI > 0) {
                                //如果从单为延期入口，他会走通用的批量延期验证，所以需要验证以下的条件，如果满足就不然延期
                                //判断是此申请单是否存在 ok并且回寄时间不为空的一览
                                List<Rental_Apply_Equipment_Set__c> raescc = getAllRentalApplyEs(rac);
                                if(raescc != null && raescc.size() > 0){
                                    for(Rental_Apply_Equipment_Set__c rr : raescc){
                                        if ((rr.Received_Confirm__c == 'OK' || rr.Received_Confirm__c == '默认签收-OK') && rr.Asset_return_time__c != null) {
                                            return '此单不满足延期条件01。';
                                        }
                                    }
                                    return '1';
                                }
                            }else{
                                return '此单不满足延期条件02。';
                            }
                        }else{
                            return '2';
                        }
                    }
                }
            }
        }
        return null;
    }

    /**
     * 根据传过来的备品id获取所有的从单和原单
     * @param  rea 延期的入口申请单
     * @return               返回所有的原单和从单
     * 参数有可能是原单id或从单id
     */
    public static List<Rental_Apply__c> getAllRentalApply(Rental_Apply__c rea){
        List<Rental_Apply__c> allRentalApply = [SELECT id,
                                                        Name,
                                                        RA_Status__c,
                                                        Request_return_day__c,
                                                        demo_purpose1__c,demo_purpose2__c,
                                                        ExtensionApprovalTime_Final__c,
                                                        RC_Ordered_Date__c,
                                                        Bollow_Date_Add_10_WD__c,
                                                        Loaner_received_ng_num__c,
                                                        ExtensionApprovalTime_Initial__c,
                                                        next_action__c,
                                                        NewRepair__c,
                                                        NewRepair__r.Agreed_Date__c,
                                                        NewRepair__r.Status__c,
                                                        NewRepair__r.ReRepairObject_F__c,
                                                        NewRepair__r.Repair_Shipped_Date__c,
                                                        AgreementBorrowingExtensionDate__c,
                                                        Return_dadeline_final__c,
                                                        ExtensionApplicationTime_Initial__c,
                                                        Root_Rental_Apply__c,
                                                        ExtensionStatus__c
                                                    FROM Rental_Apply__c 
                                                    WHERE id = :rea.Id 
                                                        OR id = :rea.Root_Rental_Apply__c 
                                                        OR (Root_Rental_Apply__c = :rea.Id AND Root_Rental_Apply__c != NULL)
                                                        OR (Root_Rental_Apply__c = :rea.Root_Rental_Apply__c AND Root_Rental_Apply__c != NULL) 
                                                        limit 1000];
        return allRentalApply;
    }

    /**
     * [getAllRentalApplyEs 获取一览]
     * @param  rea [description]
     * @return     [description]
     *
     * 只有从单为延期入口的时候，才会去查询一览
     */
    public static List<Rental_Apply_Equipment_Set__c> getAllRentalApplyEs(Rental_Apply__c rea){
        List<Rental_Apply_Equipment_Set__c> raes = [SELECT Id,name
                                                                , Rental_Apply__c
                                                                , Rental_Apply__r.Repair__r.Agreed_Date__c
                                                                , Rental_Apply__r.Repair__r.Repair_Estimated_date_formula__c
                                                                , Rental_Apply__r.NewRepair__c
                                                                , Rental_Apply__r.NewRepair__r.Agreed_Date__c
                                                                , Rental_Apply__r.NewRepair__r.Status__c
                                                                , Rental_Apply__r.NewRepair__r.ReRepairObject_F__c
                                                                , Rental_Apply__r.NewRepair__r.Repair_Shipped_Date__c
                                                                , Rental_Apply__r.QISRepair__r.Repair_Shipped_Date__c
                                                                , Rental_Apply__r.RC_return_to_office__c
                                                                , Rental_Apply__r.AgreementBorrowingExtensionDate__c
                                                                , Rental_Apply__r.ExtensionApprovalTime_Initial__c
                                                                , Rental_Apply__r.ExtensionApplicationTime_Final__c
                                                                , Rental_Apply__r.RcUnexpectExpiryDelay__c
                                                                , Final_reply_day__c
                                                                , Asset_return_time__c
                                                                , Bollow_Date__c
                                                                , demo_purpose2__c
                                                                , demo_purpose1__c
                                                                , Request_demo_time__c
                                                                , Loaner_received_time__c
                                                                , Received_Confirm__c
                                                                , Loaner_received_day2__c
                                                                , RcUnexpectExpiryDelay__c
                                                             FROM Rental_Apply_Equipment_Set__c
                                                            WHERE Rental_Apply__c = :rea.Id 
                                                              AND Cancel_Reason__c = null // 取消重新分配的话需要做为NG重新分配的情况所以不能用Cancel_Select__c
                                                             ];
        return raes;
    }

    //add       wangweipeng            2021/11/26                   start
    
//bp2
//    // 备品借出时间check
//    WebService static String approvalCheck2(String raesId) {
//        // check结果
//        String returnStr = '';
        
//        // 备品借出历史取得
//        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, Rental_Apply__r.Prepare_Day__c 
//              from Rental_Apply_Equipment_Set__c 
//             where Id = :raesId and Cancel_Select__c = false];
        
//        Rental_Apply_Equipment_Set__c r = raes[0];
//        // 日历范围，最小的借出开始日到最大的借出终了日
//        Date startDate = r.Rental_Start_Date__c;
//        Date endDate = r.Rental_End_Date__c;
//        Integer prepareDay = r.Rental_Apply__r.Prepare_Day__c == null ? Integer.valueOf(System.Label.EquipmentRentalPrepare) : r.Rental_Apply__r.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 Id != :raesId
//                       and Equipment_Set__c = :r.Equipment_Set__c
//                       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);
//            }
//        }
        
//        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();
//                    Date minD = startD.addDays(-1 * prepare);
//                    Date maxD = endD.addDays(prepare);
//                    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';
//    }

//bp2
//    WebService static String reserve2(String raesId) {
//        String checkRS = '1';
//        Rental_Apply_Equipment_Set__c raes = [
//                select Id,Name,Rental_Apply__c,Rental_Start_Date__c,ES_Stock_Status__c,
//                       Equipment_Set__c,
//                       Equipment_Set__r.Name,
//                       Equipment_Set__r.Active_judgement2__c,
//                       Equipment_Set__r.Last_Reserve_Rental_Apply_Equipment_Set__c,
//                       Equipment_Set__r.Pre_Reserve_Rental_Apply_Equipment_Set__c
//                  from Rental_Apply_Equipment_Set__c where Id = :raesId and Cancel_Select__c = false
//        ];
//        if (raes.Equipment_Set__r.Last_Reserve_Rental_Apply_Equipment_Set__c == raes.Id) {
//            checkRS = '该借出备品set一览已经做过出库指示:' + raes.Name;
//            return checkRS;
//        }
//        if (raes.ES_Stock_Status__c == '不能出库') {
//             checkRS = '备品set ' + raes.Equipment_Set__r.Name + ' 在预约期间外不能出库，请确认';
//             return checkRS;
//        }
//        checkRS = RentalApplyWebService.approvalCheck2(raesId);
//        if (checkRS != '1') {
//            return checkRS;
//        }
//        /*
//        if (raes.Rental_Start_Date__c <= Date.today()) {
//            checkRS = '借出开始日必须大于今日。借出备品set一览：' + raes.Name;
//            return checkRS;
//        }
//        if (raes.Equipment_Set__r.Active_judgement2__c != okStatus) {
//            checkRS = '备品set ' + raes.Equipment_Set__r.Name + ' 的' + Schema.SObjectType.Equipment_Set__c.fields.Asset_Set_status2__c.label + '不是 99.等待预约 ，现在是 ' + raes.Equipment_Set__r.Asset_Set_status2__c + ' 请确认';
//            return checkRS;
//        }
//        */
//        //备品Set明细
//        List<Equipment_Set_Detail__c> equipmentSetDetailList = new List<Equipment_Set_Detail__c>();
//        List<Equipment_Set_Detail__c> equipmentSetDetailList2 = new List<Equipment_Set_Detail__c>();
//        //备品申请借出明细历史
//        List<Rental_Apply_Equipment_Set_Detail__c> rentalApplyEquipmentSetDetailList = new List<Rental_Apply_Equipment_Set_Detail__c>();
//        //更新备品Set
//        Equipment_Set__c equipmentSet = new Equipment_Set__c(
//            Id = raes.Equipment_Set__c,
//            Last_Reserve_Rental_Apply_Equipment_Set__c = raes.Id,
//            Pre_Reserve_Rental_Apply_Equipment_Set__c = raes.Equipment_Set__r.Last_Reserve_Rental_Apply_Equipment_Set__c == null ? raes.Equipment_Set__r.Pre_Reserve_Rental_Apply_Equipment_Set__c : raes.Equipment_Set__r.Last_Reserve_Rental_Apply_Equipment_Set__c,
//            StockDown__c = false,
//            StockDown_time__c = null,
//            Shipment_request_time__c = System.now(),            //出库指示时间
//            Shippment_loaner_time__c = null,            //备品中心出库时间
//            Forecast_arrival_day__c = null,             //预计到货日
//            //Loaner_received_day__c = null,              //现场签收日
//            Request_asset_extend_time__c = null,        //延期申请时间
//            asset_extend_approval_time__c = null,       //延期申请批准时间
//            //Asset_return_day__c = null,                 //物流提货日
//            Received_loaner_time__c = null,             //备品中心回收时间
//            delivery_company__c = null,
//            Fedex_number__c = null,
//            Distributor_method__c = null,
//            Return_to_wh_staff__c = null,
//            Return_delivery_company__c = null,
//            Return_Fedex_number__c = null,
//            Return_Distributor_method__c = null,
//            Received_confirmation_staff__c = null,
//            Customer_install_explanation_sign__c = null, //是否回收CDS确认单
//            Send_to_return_email__c = false, //发送回收结果反馈邮件
//            Return_comment_anoucment__c = null, //发送回收结果反馈内容(NG理由和欠品情况)
////bp2            CDS_complete__c = false,
//            Arrival_in_wh__c = false,
//            Arrival_wh_time2__c = null,

//            Repair_Sum_Update__c = 0
//        );
        
//        //借出设备机身号码
//        String assetSerialNumber = '';
//        Boolean assetFirst = false;
//        //备品Set明细
//        Equipment_Set_Detail__c[] equipmentSetDetails = [select Equipment_Set__c,Asset__c,Asset__r.SerialNumber,
//                                            Check_lost_Item__c,Pre_disinfection__c,Water_leacage_check__c,
//                                            Inspection_result_after__c,Arrival_in_wh__c,
//                                            Lost_item_check_staff__c,CDS_staff__c,Inspection_staff_After__c,
//                                            Return_wh_chenk_staff__c,Pre_inspection_time__c,Lost_item_check_time__c,
//                                            After_Inspection_time__c,Arrival_wh_time__c,
//                                            Inspection_result__c,Inspection_staff__c,Last_Reserve_RAES_Detail__c
////bp2        CDS_complete_time__c,
//                                            from Equipment_Set_Detail__c
//                                            where Equipment_Set__c = :equipmentSet.Id and Select_rental__c = true];
        
//        for (Equipment_Set_Detail__c equipmentSetDetail : equipmentSetDetails) {
//            //插入备品申请借出明细历史
//            Rental_Apply_Equipment_Set_Detail__c rentalApplyEquipmentSetDetail = new Rental_Apply_Equipment_Set_Detail__c();
//            rentalApplyEquipmentSetDetail.Rental_Apply__c = raes.Rental_Apply__c;//备品借出申请
//            rentalApplyEquipmentSetDetail.Rental_Apply_Equipment_Set__c = raes.Id;//备品Set借出历史
//            rentalApplyEquipmentSetDetail.Equipment_Set__c = equipmentSetDetail.Equipment_Set__c;//备品Set
//            rentalApplyEquipmentSetDetail.Asset__c = equipmentSetDetail.Asset__c;//保有设备
//            //插入备品申请借出明细历史
//            rentalApplyEquipmentSetDetailList.add(rentalApplyEquipmentSetDetail);
            
//            //更新备品Set明细
//            equipmentSetDetail.Check_lost_Item__c = null;//欠品确认结果
//            equipmentSetDetail.Pre_disinfection__c = null;//清洗前
//            equipmentSetDetail.Water_leacage_check__c = null;//测漏检查结果
//            equipmentSetDetail.Inspection_result_after__c = null;//回收后-检测结果
//            equipmentSetDetail.Arrival_in_wh__c = false;//回库确认
//            equipmentSetDetail.Lost_item_check_staff__c = null;//欠品确认者
//            equipmentSetDetail.CDS_staff__c = null;//消毒人员
//            equipmentSetDetail.Inspection_staff_After__c = null;//回收后-检测人员
//            equipmentSetDetail.Return_wh_chenk_staff__c = null;//回库确认者
//            equipmentSetDetail.Inspection_result__c = null;//发货前-检测结果
//            equipmentSetDetail.Inspection_staff__c = null;//发货前-检测人员
            
//            equipmentSetDetail.Pre_inspection_time__c = null;//备品Set用,发货前-检测合格时间
//            equipmentSetDetail.Lost_item_check_time__c = null;//备品Set用,欠品确认时间
////bp2            equipmentSetDetail.CDS_complete_time__c = null;//备品Set用,CDS完毕时间
//            equipmentSetDetail.After_Inspection_time__c = null;//备品Set用,回收后-检测完毕时间
//            equipmentSetDetail.Arrival_wh_time__c = null;//备品Set用,回库确认完毕时间
//            //更新备品Set明细
//            equipmentSetDetailList.add(equipmentSetDetail);
//            //借出设备机身号码
//            if (String.isNotBlank(equipmentSetDetail.Asset__r.SerialNumber)) {
//                if (assetFirst == false) {
//                    assetSerialNumber += ',' + equipmentSetDetail.Asset__r.SerialNumber + ',';
//                    assetFirst = true;
//                } else {
//                    assetSerialNumber += equipmentSetDetail.Asset__r.SerialNumber + ',';
//                }
//            }
//        }
        
//        Equipment_Set_Detail__c[] equipmentSetDetails2 = [select Id, Last_Reserve_RAES_Detail__c
//                                            from Equipment_Set_Detail__c
//                                            where Equipment_Set__c = :equipmentSet.Id and Select_rental__c = false];
//        for (Equipment_Set_Detail__c equipmentSetDetail : equipmentSetDetails2) {
//            equipmentSetDetail.Pre_Reserve_RAES_Detail__c = equipmentSetDetail.Last_Reserve_RAES_Detail__c;
//            equipmentSetDetail.Last_Reserve_RAES_Detail__c = null;
//            equipmentSetDetailList2.add(equipmentSetDetail);
//        }
        
//        //更新借出设备机身号码
//        raes.Rental_Asset_SerialNumber__c = assetSerialNumber;
        
//        Savepoint sp = Database.setSavepoint();
//        try {
//            if (equipmentSet != null) {
//                update equipmentSet;
//            }
//            if (rentalApplyEquipmentSetDetailList.size() > 0) {
//                insert rentalApplyEquipmentSetDetailList;
//            }
//            if (equipmentSetDetailList.size() > 0) {
//                for (Integer i=0; i<equipmentSetDetailList.size(); i++) {
//                    equipmentSetDetailList[i].Pre_Reserve_RAES_Detail__c = equipmentSetDetailList[i].Last_Reserve_RAES_Detail__c;
//                    equipmentSetDetailList[i].Last_Reserve_RAES_Detail__c = rentalApplyEquipmentSetDetailList[i].Id;
//                }
//                update equipmentSetDetailList;
//            }
//            if (equipmentSetDetailList2.size() > 0) {
//                update equipmentSetDetailList2;
//            }
//            if (String.isNotBlank(assetSerialNumber)) {
//                update raes;
//            }
//            eSetRefreshStatus(equipmentSet.Id);
//        } catch (System.Exception e) {
//            Database.rollback(sp);
//            return e.getMessage();
//        }
//        //返回结果
//        return checkRS;
//    }

    // 借出备品配套一览状态即时更新
    WebService static String eSetRefreshStatus(String raeSetId) {
        return eSetRefreshStatus(new List<String> {raeSetId});
    }
    public static String eSetRefreshStatus(List<String> raeSetIds) {
        List<Rental_Apply_Equipment_Set__c> updateList1 = new List<Rental_Apply_Equipment_Set__c>();

        if (!raeSetIds.isEmpty()) {
            for (Rental_Apply_Equipment_Set__c raes: [
                    select Id,Repair_Status1__c,Repair_Status_Text__c,Final_reply_day__c,Final_reply_day_text__c,
                            Received_Confirm_NG_Not_Return__c,Received_Confirm_NG_Not_Return_Text__c,
                            Received_Confirm_Status_Text__c, Received_Confirm_Status_F__c
                              , NG_Final_reply_day_Text__c
                              , NG_Final_reply_day_F__c
                              , Yizhouweixiu_Final_reply_day_Text__c
                              , Yizhouweixiu_Final_reply_day_F__c
                              , Extend_Final_reply_day_Text__c
                              , Extend_Final_reply_day_F__c
                              , QIS_Final_reply_day_Text__c
                              , QIS_Final_reply_day_F__c
                              , Repair_cancel_Final_reply_day_Text__c
                              , Repair_cancel_Final_reply_day_F__c
                              , Return_to_office_Final_reply_day_Text__c
                              , Return_to_office_Final_reply_day_F__c
                              , Repair_delete_Final_reply_day_Text__c
                              , Repair_delete_Final_reply_day_F__c
                              , Yigoudaihuo_Final_reply_day_Text__c
                              , Yigoudaihuo_Final_reply_day_F__c
                              , Guzhangpaicha_Final_reply_day_Text__c
                              , Guzhangpaicha_Final_reply_day_F__c
                              , Repair_Agreed_Quotation_Text__c
                              , Repair_Agreed_Quotation_F__c
                              , Return_to_office_Final_reply_day_U_RC__c
                              , Return_to_office_Final_reply_day_U_RC_F__c
                              , Extend_Date__c
                              , Extend_Date_F__c
                              , Received_NG_ReAssign_Text__c
                              , Received_NG_ReAssign__c
                        //【FY23大及巨大课题】长假备品借用延期开发 2022/12/27 start xxf
                              , Final_reply_day_Holiday_backup__c
                              , NG_Final_reply_day_F_Holiday_backup__c
                              , NG_Final_reply_day_Text_Holiday_backup__c
                              , Yizhouweixiu_Final_reply_day_F_Holiday__c
                              , Yizhouweixiu_Final_reply_day_TextHoliday__c
                              , Extend_Final_reply_day_F_Holiday_backup__c
                              , Extend_Final_reply_day_Text_Holiday_back__c
                              , QIS_Final_reply_day_F_Holiday_backup__c
                              , QIS_Final_reply_day_Text_Holiday_backup__c
                              , Repair_cancel_Final_reply_day_F_Holiday__c
                              , Repair_cancel_Final_reply_day_Text_Holid__c
                              , Return_to_office_Final_reply_day_F_Ho__c
                              , Return_to_office_Final_reply_day_Text_Ho__c
                              , Repair_delete_Final_reply_day_F_Holiday__c
                              , Repair_delete_Final_reply_day_Text_Ho__c
                              , Yigoudaihuo_Final_reply_day_F_Holiday__c
                              , Yigoudaihuo_Final_reply_day_Text_Holiday__c
                              , FGuzhangpaicha_Final_reply_day_F_Holiday__c
                              , Guzhangpaicha_Final_reply_day_Text_Holid__c
                              , Return_to_office_Final_reply_day_U_RC_Ho__c
                              , Return_to_office_Final_reply_day_U_RC_FH__c
                        //【FY23大及巨大课题】长假备品借用延期开发 2022/12/27 end xxf
                      from Rental_Apply_Equipment_Set__c
                     where Id IN :raeSetIds
            ]) {
                Rental_Apply_Equipment_Set__c upd = UpdateRentalApplyEquipmentSetBatch.setRAES(raes);
                if (upd != null) {
                    updateList1.add(upd);
                }
            }
        }
//bp2
//        List<Equipment_Set_Detail__c> esdList = [
//                select Id,Asset_condition__c,Asset_condition_Text__c,
//                       Serial_Lot__c,Serial_Lot_text__c,
//                       Asset__r.Loaner_accsessary__c, Loaner_accsessary_text__c,
//                       Active_judgement__c,Active_judgement_select__c,Active_judgement_text__c,
//                       Last_Reserve_RAES_Detail_RAES_F__c,Last_Reserve_RAES_Detail_RAES_Id__c,
//                       Equipment_Set_Last_Reserve_RAES_F__c,Equipment_Set_Last_Reserve_RAES_Id__c
//                  from Equipment_Set_Detail__c 
//                 where Equipment_Set__c IN :eSetIds];
//        List<Equipment_Set_Detail__c> updateList2 = UpdateRentalApplyEquipmentSetBatch.setESD(esdList);

        Savepoint sp = Database.setSavepoint();
        try {
            if (!updateList1.isEmpty()) update updateList1;
//bp2            if (updateList2.size() > 0) update updateList2;
            return '1';
        } catch (System.Exception e) {
            Database.rollback(sp);
            return e.getMessage();
        }
        return '1';
    }

//bp2    //数出一共有多少个备品Set，出库指示，全部发货会用到
//    Webservice static Integer CntEquipmentSet(String Raid){
//        List<Rental_Apply_Equipment_Set__c> Raesc = [Select Equipment_Set__c from Rental_Apply_Equipment_Set__c where Rental_Apply__c=:Raid and Cancel_Select__c = false];
//        return Raesc.size();
//    }
    // 分配验证
    @AuraEnabled
    Webservice static String AssignBtn(String Rid){

        List<String> statusList = System.Label.StatusProcessState.split(',');

        List<Rental_Apply__c> raList = [select demo_purpose2__c,next_action__c,QIS_number__r.ReplaceDeliveryDate__c,Follow_UP_Opp__r.Shipping_Finished_Day_Func__c,repair__r.Repair_Final_Inspection_Date__c,repair__r.Return_Without_Repair_Date__c,Campaign__c,Campaign__r.Status,Repair__r.Repair_Shipped_Date__c,Campaign__r.IF_Approved__c,Campaign__r.Meeting_Approved_No__c,Campaign__r.Approved_Status__c   from Rental_Apply__c where id = :Rid];
        // 20210803 ljh  SFDC-C5HDC7 add 查询添加 Campaign__c,Campaign__r.Status,Repair__r.Repair_Shipped_Date__c 
        if(raList.size()>0){
            Rental_Apply__c Ra = raList[0];
            // 20210803 ljh  SFDC-C5HDC7 update  判断增加 Ra.repair__c != null && start
            // if(Ra.repair__r.Repair_Final_Inspection_Date__c!=null){
            //     return '修理最终检测日不为空，不能分配';
            // }else if(Ra.repair__r.Return_Without_Repair_Date__c !=null){
            //     return '未修理归还日不为空，不能分配';
            if(Ra.Campaign__c != null && Ra.Campaign__r.Status == '取消'){
                return '学会取消，不可分配';
            }else if(Ra.repair__c != null && (Ra.repair__r.Repair_Final_Inspection_Date__c!=null || Ra.Repair__r.Repair_Shipped_Date__c != null)){
                return '修理有最终检测日或修理品返送日，不可分配';
            }else if(Ra.repair__c != null && Ra.repair__r.Return_Without_Repair_Date__c !=null){
                return '未修理归还日不为空，不能分配';
            // 20210803 ljh  SFDC-C5HDC7 add end   
            }//1822 yc 20211021 start
            else if(Ra.demo_purpose2__c=='已购待货' && Ra.Follow_UP_Opp__r.Shipping_Finished_Day_Func__c!= null){
                return '已购待货目的，新品已有发货日，不可分配';
           }else if(Ra.demo_purpose2__c=='索赔QIS' && Ra.next_action__c=='无偿更换' && Ra.QIS_number__r.ReplaceDeliveryDate__c!= null){
                return '索赔QIS目的，QIS已有新品发货日，不可分配';
           }//1822 yc 20211108 end
           else if(Ra.Campaign__r.IF_Approved__c && Ra.Campaign__r.Meeting_Approved_No__c == null){
                return '已申请决裁但决裁编码为空';
           }//20220301 sx obpm修改
           else if(Ra.Campaign__r.IF_Approved__c && Ra.Campaign__r.Meeting_Approved_No__c != null && statusList.contains(Ra.Campaign__r.Approved_Status__c)){
                return '已申请决裁但决裁状态不符合条件';
           }//20220315 sx obpm备品决裁状态相关修改
           else{
                return 'Fin';
            } 
        }else{
            return '该借出申请不存在';
        }
    }

//bp2
//    // 补充附属品
//    WebService static String fillOtherDetail(String eSetId) {
//        // 不打勾的不要补充，所以看 Active_judgement_select__c
//        List<Equipment_Set_Detail__c> sesd = [select Id from Equipment_Set_Detail__c where Equipment_Set__c = :eSetId and Asset__r.Loaner_accsessary__c = false and Active_judgement_select__c != :okStatus];
//        if (sesd.size() > 0) {
//            // 要等主机回来了才能补
//            return '请确认备品中主机状态';
//        }
        
//        List<Equipment_Set_Detail__c> oesd = [select Id, Last_Reserve_RAES_Detail__c from Equipment_Set_Detail__c where Equipment_Set__c = :eSetId and Asset__r.Loaner_accsessary__c = true and Equipment_Set__r.ES_Status__c not in ('引当可','引当済') and Select_rental__c = true];
//        // 因为有参照备品set的字段，所以为了达到状态变成99的目的，在这里做了入库的操作，而不是全清空。
//        for (Equipment_Set_Detail__c esd : oesd) {
//            if (esd.Last_Reserve_RAES_Detail__c != null) {
//                esd.Pre_Reserve_RAES_Detail__c = esd.Last_Reserve_RAES_Detail__c;
//                esd.Last_Reserve_RAES_Detail__c = null;
//            }

//            esd.Inspection_result_ng__c = null;
//            esd.Pre_inspection_time__c = null;
//            esd.Inspection_staff__c = null;
//            esd.Inspection_result__c = 'OK';

//            esd.Check_lost_Item__c = 'OK';
//            esd.Lost_item_check_time__c = null;
//            esd.Lost_item_check_staff__c = null;
//            esd.Lost_item_giveup__c = false;

//            esd.Inspection_result_after_ng__c = null;
//            esd.After_Inspection_time__c = null;
//            esd.Inspection_staff_After__c = null;
//            esd.Inspection_result_after__c = 'OK';

//            esd.Arrival_in_wh__c = true;
//            esd.Arrival_wh_time__c = null;
//            esd.Return_wh_chenk_staff__c = null;

//            esd.Pre_disinfection__c = null;
//            esd.Water_leacage_check__c = null;
////bp2            esd.CDS_staff__c = null;
////bp2            esd.CDS_complete_time__c = null;
//        }

//        Savepoint sp = Database.setSavepoint();
//        try {
//            update oesd;
//            return '1';
//        } catch (System.Exception e) {
//            Database.rollback(sp);
//            return e.getMessage();
//        }
//        return '1';
//    }
    @AuraEnabled
    Webservice static String postponeCheck(String endDate, Integer d) {
        Date before5day = getWD_addday(date.parse(endDate), d);
        if (Date.today() > before5day) {
            return System.Label.EquipmentRentalPostponeOverDeadline;
        }
        return 'OK';
    }
    
    // TODO please use public
    public static Date getWD_now(Date d) {
        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 1];
        Date selectDate = workday[0].Date__c;
        return selectDate;
    }

    // TODO please use public
    public static Date getWD_addday(Date d, Integer i) {
        if (d == Date.valueOf('4000-12-31')) {
            return d;
        }
        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)];
            Date selectDate = workday[i].Date__c;
            return selectDate;
        } 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)];
            Date selectDate = workday[i].Date__c;
            return selectDate;
        }
    }
    
    // pd:0代表当天,1代表第二天
    public Map<Date, Map<String, String>> getDateMap(Date sd, Date ed, Integer pd) {
        Map<Date, Map<String, String>> returnMap = new Map<Date, Map<String, String>>();
        List<OlympusCalendar__c> workdayList = [
                select Id, Date__c, IsWorkDay__c 
                  from OlympusCalendar__c 
                 where Date__c >= :sd
                   and Date__c <= :ed.addDays(15 + pd)                  // +15 的目的是、为了取得ed の 下一个工作日
                 order by Date__c];
        for (Integer i = 0; i < workdayList.size(); i++) {
            OlympusCalendar__c wd = workdayList[i];
            if (wd.Date__c > ed) break;
            Integer nextWordDays = 0;
            Map<String, String> valueMap = new Map<String, String>();
            valueMap.put('WorkDay', String.valueOf(wd.IsWorkDay__c));
            Integer maxJ = 15 + i + pd;
            if (maxJ > workdayList.size()) maxJ = workdayList.size();
            for (Integer j = i; j < maxJ; j++) {
                OlympusCalendar__c oc = workdayList[j];
                if (oc.IsWorkDay__c == 1) {
                    nextWordDays++;
                    if (nextWordDays == pd + 1) {
                        valueMap.put('Next', String.valueOf(oc.Date__c));
                        break;
                    }
                }
            }
            
            returnMap.put(wd.Date__c, valueMap);
        }
        return returnMap;
    }

//bp2
//// TODO katsu select in for, why?、getBetweenWD をなくす方向、Countだけなら、getOlympusWorkDayCount のメソッドがあります。
//    //工作日
//    WebService static String getBetweenWD(String sd, String ed) {
//        String betweenWD = '0';
//        if (sd != '' && ed != '') {
//            Date sdate = Date.valueof(sd.replace('/','-'));
//            Date edate = Date.valueof(ed.replace('/','-'));
//            List<OlympusCalendar__c> workdayList = [
//                    select Id, Date__c, IsWorkDay__c 
//                      from OlympusCalendar__c 
//                    where Date__c >= :sdate
//                       and Date__c <= :edate
//                       and IsWorkDay__c = 1
//                     order by Date__c];
//            betweenWD = String.valueOf(workdayList.size());
//        }
//        return betweenWD;
//    }
//bp2 OLY_OCM-113
    ////自然日
    //Webservice static String getBetweenNaturalDay(String sd, String ed){
    //    String betweenND = '0';
    //    if(sd != '' && ed != ''){
    //        Date sdate = Date.valueof(sd.replace('/','-'));
    //        Date edate = Date.valueof(ed.replace('/','-'));
    //        Integer days = sdate.daysBetween(edate);

    //        betweenND = String.valueOf(days);
    //    }
    //    return betweenND;
    //}
    //WebService static String sendAll(String raid) {
    //    return '1';
    //}

////bp2 OLY_OCM-81
//*************************Create 20160825 SWAG-AD59Z6 趙徳芳 Start*************************//
//    //全部发货
//    WebService static String DeliverAll(String raid){
//        List<Rental_Apply__c> raList = [select id,repair__r.Repair_Final_Inspection_Date__c,Bollow_Date__c,repair__r.Return_Without_Repair_Date__c, delivery_company__c, Return_to_wh_staff__c, Distributor_method__c, Tracking_Number__c,
//                                               Shippment_loaner_time__c,Status__c,All_Delivery_Flag_c__c
//                                          from Rental_Apply__c
//                                         where id = :raid];
//        Rental_Apply__c Ra = new Rental_Apply__c();
//        System.debug(raList);
//        if(raList.size()>0){
//            Ra = raList[0];
//            if(Ra.delivery_company__c == null||
//                Ra.Return_to_wh_staff__c == null ||
//                 Ra.Distributor_method__c == null ||
//                  Ra.Tracking_Number__c == null){
//                return '请补全发货物流信息';
//            }else if(Ra.Status__c !='出库指示完了'){
//                return '请先做出库指示后，再进行出库';
//            }
//            //else if(Ra.repair__c.Repair_Final_Inspection_Date__c<Ra.Bollow_Date__c){
//            //  return '修理最终检测日早于发货日，不能发货';
//            //}
//            else if(Ra.repair__c!=null&&Ra.repair__r.Repair_Final_Inspection_Date__c!=null){
//                return '修理最终检测日不为空，不能发货';
//            }else if(Ra.repair__c!=null&&Ra.repair__r.Return_Without_Repair_Date__c!=null){
//                return '未修理归还日不为空，不能发货';
//            }else{
//                List<Rental_Apply_Equipment_Set__c> DeliveryGoodDetail = new List<Rental_Apply_Equipment_Set__c>();
//                DeliveryGoodDetail = [select id,name,Equipment_Set__c from Rental_Apply_Equipment_Set__c where Shippment_loaner_time__c =null and Rental_Apply__c =:raid and  Cancel_Select__c = false];
//                if(DeliveryGoodDetail.size()>0){
//                    List<Rental_Apply_Equipment_Set__c> ExistSet  = new List<Rental_Apply_Equipment_Set__c>();
//                    ExistSet = [select id,name,Equipment_Set__c from Rental_Apply_Equipment_Set__c where Rental_Apply__c =:raid and Cancel_Select__c = false];
//                    List<String> sqlLine = new List<String>();
//                    for(Rental_Apply_Equipment_Set__c RAESC : DeliveryGoodDetail){
//                        sqlLine.add(RAESC.Equipment_Set__c);
//                    }
//                    List<Equipment_Set__c> ResultSet = new List<Equipment_Set__c>();
//                    ResultSet = [select id,Pre_inspection_time__c,Shippment_loaner_time__c from Equipment_Set__c where id in:sqlLine];
//                    System.debug(ResultSet);
//                    Integer Ncnt =0;
//                    for(Equipment_Set__c ESC : ResultSet){
//                        if(ESC.Shippment_loaner_time__c!=null){
//                            Ncnt=Ncnt+1;
//                        }
//                    }
//                    Savepoint sp = Database.setSavepoint();
//                    List<Equipment_Set__c> UpsertEsc = new List<Equipment_Set__c>();
//                    if(Ncnt==0){
//                        for(Equipment_Set__c ESC : ResultSet){
//                            Equipment_Set__c EscEle =  new Equipment_Set__c();
//                            EscEle.id=ESC.id;
//                            EscEle.delivery_company__c  = Ra.delivery_company__c;
//                            EscEle.Return_to_wh_staff__c  = Ra.Return_to_wh_staff__c;
//                            EscEle.Distributor_method__c  = Ra.Distributor_method__c;
//                            EscEle.Fedex_number__c  = Ra.Tracking_Number__c;
//                            EscEle.StockDown__c  = true;
//                            UpsertEsc.add(EscEle);
//                        }
//                        if(UpsertEsc.size()>0){
//                            Ra.All_Delivery_Flag_c__c = true;
//                            try{
//                                update Ra;    
//                                update UpsertEsc;
//                                return 'Fin';
//                            }catch (System.Exception e){
//                                Database.rollback(sp);
//                                return e.getMessage();
//                            }
//                        }else{
//                            return '所选备品Set，已全部出库，无法再次出库';
//                        }               
//                    }else{
//                        return '备品已出库';
//                    }
//                }else{
//                    return '本借出申请无需要出库的备品';
//                }
//            }
//        }else{
//            return '无效的备品借出申请';
//        }
//    }

////bp2 OLY_OCM-81
////*************************Create 20160825 SWAG-AD59Z6 趙徳芳 End***************************//
//    WebService static String receiveAll(String raid) {
//        List<Rental_Apply__c> raList = [select id, Return_Track_Company__c, Return_Distrubutor_Method__c, Return_Trake_Staff__c, Return_Track_Number__c,
//                                               Shippment_loaner_time__c
//                                          from Rental_Apply__c
//                                         where id = :raid];
//        if (raList.size() == 0) {
//            return '无效的备品借出申请';
//        }
//        Rental_Apply__c ra = raList[0];
//        if (ra.Return_Track_Company__c == null ||
//            ra.Return_Distrubutor_Method__c == null ||
//            ra.Return_Trake_Staff__c == null ||
//            ra.Return_Track_Number__c == '' || ra.Return_Track_Number__c == null) {
//            return '请补全回库物流信息';
//        }
//        if (ra.Shippment_loaner_time__c == null) {
//            return '备品还没出库';
//        }
//        List<Rental_Apply_Equipment_Set__c> raesList = [select id, Equipment_Set__c from Rental_Apply_Equipment_Set__c where Shippment_loaner_time__c != null and Rental_Apply__c = :raid and Cancel_Select__c = false];
//        if (raesList.size() == 0) {
//            return '备品还没出库';
//        }
//        Map<id,id> RaesEsIdMap = new Map<Id,id>();
//        List<String> esidList = new List<String>();
//        for (Rental_Apply_Equipment_Set__c raes : raesList) {
//            esidList.add(raes.Equipment_Set__c);
//            RaesEsIdMap.put(raes.Equipment_Set__c, raes.Id);
//        }
//        List<Equipment_Set__c> esList = [select id,Return_Fedex_number__c,Last_Reserve_Rental_Apply_Equipment_Set__c from Equipment_Set__c where id in :esidList];
//        List<Equipment_Set__c> updList = new List<Equipment_Set__c>();
//        for (Equipment_Set__c es : esList) {
//            if ((es.Return_Fedex_number__c == null || es.Return_Fedex_number__c == '') && es.Last_Reserve_Rental_Apply_Equipment_Set__c == RaesEsIdMap.get(es.Id)) {
//                Equipment_Set__c tmp = new Equipment_Set__c(
//                    id = es.id,
//                    Return_delivery_company__c = ra.Return_Track_Company__c,
//                    Received_confirmation_staff__c = ra.Return_Trake_Staff__c,
//                    Return_Distributor_method__c = ra.Return_Distrubutor_Method__c,
//                    Return_Fedex_number__c = ra.Return_Track_Number__c
//                );
//                updList.add(tmp);
//            }
//        }
//        if (updList.size() == 0) {
//            return '备品已经全部回库';
//        } else {
//            try {
//                update updList;
//            } catch (Exception ex) {
//                return ex.getMessage();
//            }
//        }
//        return '1';
//    }

    WebService static String RentalApplyCancel(String raid, Boolean autoCancel) {
        List<Rental_Apply__c> raList = [select id, Shipment_request_Cnt__c, Status__c, RA_Status__c, Shippment_loaner_cnt__c, Loaner_cancel_request__c, Arrival_wh_cnt__c,
                Cancel_Reason__c
                from Rental_Apply__c
                where id = :raid];
        List<Rental_Apply_Equipment_Set__c> raesList = [select id, StockDown_time__c
//bp2        , Equipment_Set__c
                                                          from Rental_Apply_Equipment_Set__c
                                                         where Rental_Apply__c = :raid
                                                           and Cancel_Select__c = false];

        List<Rental_Apply_Equipment_Set__c> updList = new List<Rental_Apply_Equipment_Set__c>();
        // List<Rental_Apply_Equipment_Set_Detail__c> delList = new List<Rental_Apply_Equipment_Set_Detail__c>();
        Set<Id> esIdSet = new Set<Id>();

        if (raList.size() <= 0) {
            return '备品申请书不存在。';
        }
        Rental_Apply__c ra = raList[0];
        if (ra.Status__c == '取消') {
            return '备品申请书已经取消。';
        }
        if (ra.Status__c == '删除') {
            return '备品申请书已经删除。';
        }
        if (ra.RA_Status__c == FixtureUtil.raStatusMap.get(FixtureUtil.RaStatus.Yi_Chu_Ku.ordinal()) || ra.Arrival_wh_cnt__c > 0) {
            return '备品已经出库，不能取消。';
        }
        
        User loginUser = [Select Id, Name, ProfileId From User where Id = :Userinfo.getUserId()];
        if(loginUser.ProfileId != System.Label.ProfileId_SystemAdmin && loginUser.ProfileId != System.Label.ProfileId_EquipmentCenter && !System.Label.ProfileId_EquCenCheckAndDepot.contains(loginUser.ProfileId)  && !System.Label.ProfileId_EquCenAdmin.contains(loginUser.ProfileId) && loginUser.ProfileId != System.Label.ProfileId_IThelp && ra.Shipment_request_Cnt__c > 0
        ){
            return '不能取消申请，请联系备品中心窗口取消。';
        }


        if (autoCancel == false && String.isBlank(ra.Cancel_Reason__c)) {
            return '必须输入取消理由。';
        }
        ra.Status__c = '取消';
        if (autoCancel) {
            ra.Cancel_Reason__c = '被动取消';
        }
        // Map<Id, Asset> assetMap = new Map<Id, Asset>();
        // for (Rental_Apply_Equipment_Set__c raes : raesList) {
        //     // if (raes.StockDown_time__c != null) {
        //         raes.Cancel_Select__c = true;
        //         raes.Cancel_Reason__c = ra.Loaner_cancel_request__c;
        //         if (autoCancel) {
        //             raes.Cancel_Reason__c = '被动取消';
        //         }
        //         updList.add(raes);
//bp2                esIdSet.add(raes.Equipment_Set__c);
            // } else {
                // delList.add(raes);
//bp2                esIdSet.add(raes.Equipment_Set__c);
            // }
            // Asset ass = new Asset(Id = raes.Asset__c, Last_Reserve_RAES_Detail__c = null);
            // assetMap.put(raes.Asset__c, ass);
        // }

        Savepoint sp = Database.setSavepoint();
        try {
            Set<Id> assetIdSet = new Set<Id>();
            for (Rental_Apply_Equipment_Set_Detail__c raesd : [SELECT Id, Asset__c
                                                                 FROM Rental_Apply_Equipment_Set_Detail__c
                                                                WHERE Rental_Apply__c = :raid
                                                                  FOR UPDATE]
            ) {
                if (String.isNotBlank(raesd.Asset__c)) {
                    assetIdSet.add(raesd.Asset__c);
                }
            }
            if (assetIdSet.size() > 0) {
                List<Asset> assetList = [SELECT Id FROM Asset WHERE Id = :assetIdSet FOR UPDATE];
            }
            update ra;
            //if (updList.size() > 0) update updList;
            // if (!assetMap.isEmpty()) update assetMap.values();
//bp2            ControllerUtil.setEquipmentSetProvisionFlg(esIdSet);
        } catch (Exception ex) {
            return ex.getMessage();
            Database.rollback(sp);
        }

        return '1';
    }

    // 一覧単位
    @AuraEnabled
    WebService static String setRaesShipment_request(String raesid) {
      return setShipment_requests(null, raesid);
    }

    // 申請書単位
    @AuraEnabled
    WebService static String setShipment_request(String raid) {
      return setShipment_requests(raid, null);
    }

    //出库指示按钮js一次最多更新200条，所以改在WebService做出库指示
    @AuraEnabled
    WebService 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();
      }
    }

    /**
     * 注残申请备品的管控
     */
    @AuraEnabled
     WebService static String RentalApplyCheckForSAoneEle(String SaID) {
        Statu_Achievements__c Sac = [select id,
            SalesChannel__c,
            Opportunity__r.Sales_Root__c,
            Status_1__c,
            Status_2_Formula__c,
            Opp_Number__c,
            ContractNO__c,
            FirstApproveDate__c,
            CreatedDate,
            X30_Deposit_Day__c,
            Deposit_In_Full_Day__c,
            DeliveryDate__c,
            Backorder_complete_day__c,
            DeliveryStatus__c
        from Statu_Achievements__c where id = :SaID];
        if(Sac.Opportunity__r.Sales_Root__c == '販売店'){
            if(Sac.Opp_Number__c.contains('GI')||Sac.Opp_Number__c.contains('BF')||Sac.Opp_Number__c.contains('ET') ){
                //modify by lyh 20220606 start 已购待货逻辑调整 
                //客户GIR订单，注残状态2是“12付全款-14已发货“这个区间且发货状态为”未交付、和部分交付“时，自付款日起第31天未生成”客户订单最终发货日“时，方可以提交”已购待货“目的的备品申请
                //if(Sac.Status_1__c == '注残' && (Sac.Status_2_Formula__c == '12 已订货・付全款'||Sac.Status_2_Formula__c == '13 待发货')){
                //    if((Date.today().addDays(-30)>Sac.Deposit_In_Full_Day__c)&&Sac.DeliveryDate__c == null){
                if((Sac.Status_2_Formula__c == '12 已订货・付全款' || Sac.Status_2_Formula__c == '13 待发货' || Sac.Status_2_Formula__c == '14 已发货')
                    && (Sac.DeliveryStatus__c == '未交付' || Sac.DeliveryStatus__c == '部分交付')) {
                    if((Date.today().addDays(-30) > Sac.Deposit_In_Full_Day__c) && Sac.Backorder_complete_day__c == null) {
                //modify by lyh 20220606 end 已购待货逻辑调整
                        return 'Fin';
                    } else {
                        return '经销商内科订单不在申请期内，不能申请备品';
                    }
                }else{
                    return '经销商内科订单状态不符合备品申请资格，不能申请备品';
                }
            }else if(Sac.Opp_Number__c.contains('SP')){
                //modify by lyh 20220606 start 已购待货逻辑调整 
                //客户SP订单，注残状态2是“11付定金-14已发货“这个区间且发货状态为”未交付、和部分交付“时，自付款日起第61天未生成”客户订单最终发货日“时，方可以提交”已购待货“目的的备品申请
                //if(Sac.Status_1__c == '注残' && (Sac.Status_2_Formula__c == '11 已订货・付订金'||Sac.Status_2_Formula__c == '12 已订货・付全款'||Sac.Status_2_Formula__c == '13 待发货')){
                //    if((Date.today().addDays(-60)>Sac.X30_Deposit_Day__c )&&Sac.DeliveryDate__c == null){
                if((Sac.Status_2_Formula__c == '11 已订货・付订金'||Sac.Status_2_Formula__c == '12 已订货・付全款'||Sac.Status_2_Formula__c == '13 待发货'||Sac.Status_2_Formula__c=='14 已发货')
                    && (Sac.DeliveryStatus__c == '未交付' || Sac.DeliveryStatus__c == '部分交付')) {
                    if((Date.today().addDays(-60) > Sac.X30_Deposit_Day__c ) && Sac.Backorder_complete_day__c == null){
                //modify by lyh 20220606 end 已购待货逻辑调整
                        return 'Fin';
                    }else{
                        return '经销商SP订单不在申请期内，不能申请备品';
                    }
                }else{
                    return '经销商SP订单状态不符合备品申请资格，不能申请备品';
                }
            }else{
                return '注残销售渠道类别不在可申请备品范围内';
            }
        }else if(Sac.Opportunity__r.Sales_Root__c == 'OCM直接販売'){
            if(Sac.Opp_Number__c.contains('GI')||Sac.Opp_Number__c.contains('BF')||Sac.Opp_Number__c.contains('ET')){
                //modify by lyh 20220606 start 已购待货逻辑调整 
                //注残状态2是“9已录订单未付款-14已发货“这个区间且发货状态为”未交付、和部分交付“且“销售渠道为直销时”，GIR订单自订单录入日起第31天/未生成”客户订单最终发货日“时，方可以提交”已购待货“目的的备品申请
                //if(Sac.Status_1__c == '注残' && (Sac.Status_2_Formula__c == '09 已录入订单未付款'||Sac.Status_2_Formula__c == '10 库存已预留・未付款'||Sac.Status_2_Formula__c == '11 已订货・付订金'||Sac.Status_2_Formula__c == '12 已订货・付全款'||Sac.Status_2_Formula__c == '13 待发货')){
                //    if((Date.today().addDays(-30)>Sac.FirstApproveDate__c )&&Sac.DeliveryDate__c == null){
                if((Sac.Status_2_Formula__c == '09 已录入订单未付款'||Sac.Status_2_Formula__c == '10 库存已预留・未付款'||Sac.Status_2_Formula__c == '11 已订货・付订金'||Sac.Status_2_Formula__c == '12 已订货・付全款'||Sac.Status_2_Formula__c == '13 待发货'||Sac.Status_2_Formula__c=='14 已发货')
                    && (Sac.DeliveryStatus__c == '未交付' || Sac.DeliveryStatus__c == '部分交付')){
                    if((Date.today().addDays(-30) > Sac.FirstApproveDate__c ) && Sac.Backorder_complete_day__c == null) {
                //modify by lyh 20220606 end 已购待货逻辑调整
                        return 'Fin';
                    }else{
                        return 'OCM直销内科订单不在申请期内，不能申请备品';
                    }
                }else{
                    return 'OCM直销内科订单状态不符合备品申请资格，不能申请备品';
                }
            }else if(Sac.Opp_Number__c.contains('SP')){
                    //modify by lyh 20220606 start 已购待货逻辑调整 
                    //注残状态2是“9已录订单未付款-14已发货“这个区间且发货状态为”未交付、和部分交付“且“销售渠道为直销时”，SP订单61天未生成”客户订单最终发货日“时，方可以提交”已购待货“目的的备品申请
                    //if(Sac.Status_1__c == '注残' && (Sac.Status_2_Formula__c == '09 已录入订单未付款'||Sac.Status_2_Formula__c == '10 库存已预留・未付款'||Sac.Status_2_Formula__c == '11 已订货・付订金'||Sac.Status_2_Formula__c == '12 已订货・付全款'||Sac.Status_2_Formula__c == '13 待发货')){
                    //    if((Date.today().addDays(-60)>Sac.FirstApproveDate__c )&&Sac.DeliveryDate__c == null){
                    if((Sac.Status_2_Formula__c == '09 已录入订单未付款'||Sac.Status_2_Formula__c == '10 库存已预留・未付款'||Sac.Status_2_Formula__c == '11 已订货・付订金'||Sac.Status_2_Formula__c == '12 已订货・付全款'||Sac.Status_2_Formula__c == '13 待发货'||Sac.Status_2_Formula__c=='14 已发货')
                        && (Sac.DeliveryStatus__c == '未交付' || Sac.DeliveryStatus__c == '部分交付')) {
                        if((Date.today().addDays(-60) > Sac.FirstApproveDate__c ) && Sac.Backorder_complete_day__c == null) {
                    //modify by lyh 20220606 end 已购待货逻辑调整   
                            return 'Fin';
                        }else{
                            return 'OCM直销SP订单不在申请期内，不能申请备品';
                        }
                    }else{
                        return 'OCM直销SP订单状态不符合备品申请资格，不能申请备品';
                    }
                }else{
                    return '注残销售渠道类别不在可申请备品范围内。';
                }
        }else{
            return '销售渠道未知，不能新建';
        }
     }


//bp2
    //public static String RentalApplyCheckForSA(String raid,String SaID) {
    //    List<String> ProList = new List<String>();
    //    if(raid!=null){
    //        Rental_Apply__c Ra = [select id,
    //            Product_category__c,
    //            ProductNameNum1__c,
    //            ProductNameNum10__c,
    //            ProductNameNum2__c,
    //            ProductNameNum3__c,
    //            ProductNameNum4__c,
    //            ProductNameNum5__c,
    //            ProductNameNum6__c,
    //            ProductNameNum7__c,
    //            ProductNameNum8__c,
    //            ProductNameNum9__c
    //        from
    //            Rental_Apply__c
    //        where 
    //            id=: Raid];
    //        ProList.add(Ra.ProductNameNum1__c);
    //         ProList.add(Ra.ProductNameNum2__c);
    //          ProList.add(Ra.ProductNameNum3__c);
    //           ProList.add(Ra.ProductNameNum4__c);
    //            ProList.add(Ra.ProductNameNum5__c);
    //             ProList.add(Ra.ProductNameNum6__c);
    //              ProList.add(Ra.ProductNameNum7__c);
    //               ProList.add(Ra.ProductNameNum8__c);
    //                ProList.add(Ra.ProductNameNum9__c);
    //                 ProList.add(Ra.ProductNameNum10__c);
    //    List<asset> ast = [select
    //                            id,
                                
    //                            Backorder__c 
    //                        from
    //                            asset
    //                        where
    //                            Backorder__c =:SaID];
    //    for(asset asl : ast){
    //        for(String proStr : ProList){
    //            if(asl.Id == proStr){
    //                return '产品已发货，不能申请备品';
    //            }
    //        }
    //    }
    //    }
        
    
    //    Statu_Achievements__c Sac = [select id,
    //        SalesChannel__c,
    //        Status_1__c,
    //        Status_2_Formula__c,
    //        Opp_Number__c,
    //        CreatedDate,
    //        FirstApproveDate__c,
    //        Opportunity__r.Sales_Root__c,
    //        X30_Deposit_Day__c,
    //        Deposit_In_Full_Day__c,
    //        DeliveryDate__c
    //    from Statu_Achievements__c where id = :SaID];
        
        
        
    //    if(Sac.Opportunity__r.Sales_Root__c == '販売店'){
    //        if(Sac.Opp_Number__c.contains('GI')||Sac.Opp_Number__c.contains('BF')||Sac.Opp_Number__c.contains('ET') ){
    //            if(Sac.Status_1__c == '注残' && (Sac.Status_2_Formula__c == '12 已订货・付全款'||Sac.Status_2_Formula__c == '13 待发货')){
    //                if((Date.today().addDays(-30)>Sac.Deposit_In_Full_Day__c)&&Sac.DeliveryDate__c == null){
    //                    return 'Fin';
    //                }else{
    //                    return '经销商内科订单不在申请期内，不能申请备品';
    //                }
    //            }else{
    //                return '经销商内科订单状态不符合备品申请资格，不能申请备品';
    //            }
    //        }else if(Sac.Opp_Number__c.contains('SP')){
    //            if(Sac.Status_1__c == '注残' && (Sac.Status_2_Formula__c == '11 已订货・付订金'||Sac.Status_2_Formula__c == '12 已订货・付全款'||Sac.Status_2_Formula__c == '13 待发货')){
    //                if((Date.today().addDays(-60)>Sac.X30_Deposit_Day__c )&&Sac.DeliveryDate__c == null){
    //                    return 'Fin';
    //                }else{
    //                    return '经销商SP订单不在申请期内，不能申请备品';
    //                }
    //            }else{
    //                return '经销商SP订单状态不符合备品申请资格，不能申请备品';
    //            }
    //        }else{
    //            return 'Denied';
    //        }
    //    }else if(Sac.Opportunity__r.Sales_Root__c == 'OCM直接販売'){
    //        if(Sac.Opp_Number__c.contains('GI')||Sac.Opp_Number__c.contains('BF')||Sac.Opp_Number__c.contains('ET')){
    //            if(Sac.Status_1__c == '注残' && (Sac.Status_2_Formula__c == '09 已录入订单未付款'||Sac.Status_2_Formula__c == '10 库存已预留・未付款'||Sac.Status_2_Formula__c == '11 已订货・付订金'||Sac.Status_2_Formula__c == '12 已订货・付全款'||Sac.Status_2_Formula__c == '13 待发货')){
    //                if((Date.today().addDays(-30)>Sac.FirstApproveDate__c )&&Sac.DeliveryDate__c == null){
    //                    return 'Fin';
    //                }else{
    //                    return 'OCM直销内科不在申请期内，不能申请备品';
    //                }
    //            }else{
    //                 return 'OCM直销内科订单状态不符合备品申请资格，不能申请备品';
    //            }
    //        }else if(Sac.Opp_Number__c.contains('SP')){
    //            if(Sac.Status_1__c == '注残' && (Sac.Status_2_Formula__c == '09 已录入订单未付款'||Sac.Status_2_Formula__c == '10 库存已预留・未付款'||Sac.Status_2_Formula__c == '11 已订货・付订金'||Sac.Status_2_Formula__c == '12 已订货・付全款'||Sac.Status_2_Formula__c == '13 待发货')){
    //                if((Date.today().addDays(-60)>Sac.FirstApproveDate__c )&&Sac.DeliveryDate__c == null){
    //                    return 'Fin';
    //                }else{
    //                    return '直销SP订单不在申请期内，不能申请备品';
    //                }
    //            }else{
    //                 return 'OCM直销SP订单状态不符合备品申请资格，不能申请备品';
    //            }
    //        }else{
    //            return 'Fin';
    //        }
    //    }else{
    //        return '销售渠道未知，不能新建';
    //    }
    //}

// bp2
    ///**
    //备品是否可以继续操作的管控
    //*/
    //public static String rentalContiuneCheck(List<Rental_Apply__c> newList,Map<Id, Rental_Apply__c> oldMap){
    //    List<String> RaidList = new List<String>();
    //    for(Rental_Apply__c ra : newList){
    //        RaidList.add(ra.id);
    //    }
    //    List<Rental_Apply__c> RaTarList = [select Campaign__c,Repair__c,
    //                                            Campaign__r.Status,Repair__r.Repair_Final_Inspection_Date__c,Repair__r.Repair_Shipped_Date__c
    //                                        from Rental_Apply__c 
    //                                        where id=:RaidList];
    //    for(Rental_Apply__c RaTar : RaTarList){
    //    String RsStr = '';
    //        if( RaTar.Campaign__r.Status == '取消'||
    //                RaTar.Campaign__r.Status == '取消申请中'||
    //                    RaTar.Campaign__r.Status == '已提交报告'||
    //                        RaTar.Campaign__r.Status == '已结束'){
    //            RsStr = RentalApplyWebService.rentalContiuneinfoCheck(newList,oldMap);
    //            if(RsStr == 'Denied'){
    //                return '学会已结束，申请单不能继续操作了';
    //            }else{
    //                return 'Fin';
    //            }
                
    //        }else if(   RaTar.Repair__r.Repair_Final_Inspection_Date__c!=null){
    //            RsStr = RentalApplyWebService.rentalContiuneinfoCheck(newList,oldMap);
    //            if(RsStr == 'Denied'){
    //                return '存在修理最终检测日，申请单不能继续了';
    //            }else{
    //                return 'Fin';
    //            }
    //        }else if(   RaTar.Repair__r.Repair_Shipped_Date__c!=null){
    //            RsStr = RentalApplyWebService.rentalContiuneinfoCheck(newList,oldMap);
    //            if(RsStr == 'Denied'){
    //                return '存在RC修理返送日，申请单不能继续了';
    //            }else{
    //                return 'Fin';
    //            }
    //        }else{
    //            return 'Fin';
    //        }
    //    }
    //    return 'Fin';
    //}
//bp2
//    public static String rentalContiuneinfoCheck(List<Rental_Apply__c> newList,Map<Id, Rental_Apply__c> oldMap){
//        for(Rental_Apply__c Rac : newList){
//        if(
//    //bp2  Trigger.oldMap.get(Rac.Id).get('HP_received_ng_num__c') != Rac.HP_received_ng_num__c ||
//            Trigger.oldMap.get(Rac.Id).get('StockDown_ng_num__c') != Rac.StockDown_ng_num__c ||
//             Trigger.oldMap.get(Rac.Id).get('Asset_return_time__c') != Rac.Asset_return_time__c ||
//              Trigger.oldMap.get(Rac.Id).get('Count_Extend__c') != Rac.Count_Extend__c ||
//                Trigger.oldMap.get(Rac.Id).get('Max_Extend_workday__c') != Rac.Max_Extend_workday__c ||
//    //bp2        Trigger.oldMap.get(Rac.Id).get('Lost_item_ng_num__c') != Rac.Lost_item_ng_num__c ||
//                  Trigger.oldMap.get(Rac.Id).get('Lost_item_finish__c') != Rac.Lost_item_finish__c ||
//                   Trigger.oldMap.get(Rac.Id).get('Last_Assigned_Date__c') != Rac.Last_Assigned_Date__c ||
//                    Trigger.oldMap.get(Rac.Id).get('Return_dadeline_final__c') != Rac.Return_dadeline_final__c ||
//                     Trigger.oldMap.get(Rac.Id).get('Rental_Apply_Equipment_Set_Cnt__c') != Rac.Rental_Apply_Equipment_Set_Cnt__c ||
//                      Trigger.oldMap.get(Rac.Id).get('Pre_inspection_ng_num__c') != Rac.Pre_inspection_ng_num__c ||
//                       Trigger.oldMap.get(Rac.Id).get('Shippment_ng_num__c') != Rac.Shippment_ng_num__c ||
//                        Trigger.oldMap.get(Rac.Id).get('ShelfUp_ng_num__c') != Rac.ShelfUp_ng_num__c ||
//                         Trigger.oldMap.get(Rac.Id).get('Loaner_received_ng_num__c') != Rac.Loaner_received_ng_num__c ||
//                          Trigger.oldMap.get(Rac.Id).get('Arrival_wh_cnt__c') != Rac.Arrival_wh_cnt__c ||
//                           Trigger.oldMap.get(Rac.Id).get('Shippment_loaner_cnt__c') != Rac.Shippment_loaner_cnt__c ||
//                            Trigger.oldMap.get(Rac.Id).get('Shipment_requested_cnt__c') != Rac.Shipment_requested_cnt__c ||
//                             Trigger.oldMap.get(Rac.Id).get('Pre_inspection_ng_cnt2__c') != Rac.Pre_inspection_ng_cnt2__c ||
//                              Trigger.oldMap.get(Rac.Id).get('Pre_inspection_ng_cnt__c') != Rac.Pre_inspection_ng_cnt__c ||
//                               Trigger.oldMap.get(Rac.Id).get('Shippment_loaner_time__c') != Rac.Shippment_loaner_time__c ||
//                                Trigger.oldMap.get(Rac.Id).get('Asset_loaner_closed_date__c') != Rac.Asset_loaner_closed_date__c ||
//                                 Trigger.oldMap.get(Rac.Id).get('Asset_loaner_start_date__c') != Rac.Asset_loaner_start_date__c ||
//                                  Trigger.oldMap.get(Rac.Id).get('Disposal_num__c') != Rac.Disposal_num__c ||
//                                   Trigger.oldMap.get(Rac.Id).get('Asset_return_ng_num__c') != Rac.Asset_return_ng_num__c ||
//                                    Trigger.oldMap.get(Rac.Id).get('Received_Confirm_NG_amount__c') != Rac.Received_Confirm_NG_amount__c ||
//                                     Trigger.oldMap.get(Rac.Id).get('Received_Confirm_NG_Not_Return__c') != Rac.Received_Confirm_NG_Not_Return__c ||
////bp2                                 Trigger.oldMap.get(Rac.Id).get('Loaner_received_time__c') != Rac.Loaner_received_time__c ||
//                                       Trigger.oldMap.get(Rac.Id).get('Return_Track_Company__c') != Rac.Return_Track_Company__c ||
//                                        Trigger.oldMap.get(Rac.Id).get('Return_Distrubutor_Method__c') != Rac.Return_Distrubutor_Method__c ||
//                                         Trigger.oldMap.get(Rac.Id).get('Return_Trake_Staff__c') != Rac.Return_Trake_Staff__c ||
//                                          Trigger.oldMap.get(Rac.Id).get('Return_Track_Number__c') != Rac.Return_Track_Number__c ||
//                                          Trigger.oldMap.get(Rac.Id).get('HP_received_sign_day__c') != Rac.HP_received_sign_day__c ||
//                                         Trigger.oldMap.get(Rac.Id).get('HP_received_sign_rich__c') != Rac.HP_received_sign_rich__c ||
//                                        Trigger.oldMap.get(Rac.Id).get('HP_received_sign_text__c') != Rac.HP_received_sign_text__c ||
//                                       Trigger.oldMap.get(Rac.Id).get('HP_received_sign_NG__c') != Rac.HP_received_sign_NG__c ||
//                                      Trigger.oldMap.get(Rac.Id).get('HP_received_sign_NG_Reason__c') != Rac.HP_received_sign_NG_Reason__c ||
//                                     Trigger.oldMap.get(Rac.Id).get('AssetManageConfirm__c') != Rac.AssetManageConfirm__c ||
//                                    Trigger.oldMap.get(Rac.Id).get('Loaner_cancel_request__c') != Rac.Loaner_cancel_request__c ||
//                                   Trigger.oldMap.get(Rac.Id).get('Status__c') != Rac.Status__c 
//        ){
//        return 'Fin';
//    }
//}   
//    return 'Denied';
//    }
}