// RentalFixtureSetAssignAgencyCtrlTest
public with sharing class RentalFixtureSetAssignAgencyController {
    public List<EsdInfo> esdList { get; set; }
    public FixtureDeliverySlip__c slip { get; set; }
    public Boolean done_flg { get; set; }
    private String taId;
    public Boolean readOnly { get;  set; }
    public Rental_Apply__c parentObj { get; private set; }
    public String qrcode {get;set;}
    public Boolean slipEnabled {get;set;}
    public String cancelReason {get;set;}
    public String cancelReasonRemark {get;set;}
    private Boolean isSameCity ;
    public String stepName {get;set;}
    public Date masterDate {get;set;} // 主单的预计出货日
    public List<String> bieBeiPinFenLeiList; //别备品分类 //20210508 ljh add

    public RentalFixtureSetAssignAgencyController() {
        taId = ApexPages.currentPage().getParameters().get('pt_recid');
        stepName = '无';
    }
    public PageReference init() {

        done_flg = false;
        slipEnabled = false;
        isSameCity = false;
        bieBeiPinFenLeiList = new List<String>(); //20210508 ljh add
        if (taId != null) {
            readOnly = false;
            String rasql = 'SELECT Id'
                         + ', Name'
                         + ', Yi_loaner_arranged__c'
                         + ', demo_purpose2__c'
                         + ', Asset_loaner_start_day__c'
                         + ', Asset_loaner_closed_day__c'
                         + ', Hope_Lonaer_date_Num__c'
                         + ', Campaign_EndDate_F__c'
                         + ', requestNoJoinStr2__c'
                         + ', ToAgency__c'
                         + ', StockDown_ng_num__c'
                         + ', DeliverySlip__c'
                         + ', Status__c'
                         + ', Old_Rental_Apply__r.Asset_loaner_start_date__c'
                         + ', Delivery_Agency__c'
                         + ', SalesdeptSelect__c'
                         + ', OwnerId'
                         + ', Cancel_Reason__c'//20210707 SFDC-C448KZ you
                         + ', Loaner_cancel_reason__c'//20210707 SFDC-C448KZ you
                         + ', Loaner_cancel_request__c'//20210707 SFDC-C448KZ you
                         + ', Equipment_Type_F__c' //20210508 LJH ADD 1672
                         + ', Wei_Assigned_Cnt__c' // 20210624 ljh add SFDC-C448GR start
                         + ', Campaign__r.IF_Approved__c' // 20220315 ljh add
                         + ', Campaign__r.Meeting_Approved_No__r.Name' // 20220315 ljh add 
                         + ', Campaign__r.Approved_Status__c' // 20220315 ljh add 
                         + ' FROM Rental_Apply__c'
                         + ' WHERE Id=\'' + taId + '\'';
            List<Rental_Apply__c>  raList = (List<Rental_Apply__c>) Consum_ApplyUtil.withoutQueryList(rasql);
            if(raList.isEmpty()) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '借出申请不存在！'));
                return null;
            }
            parentObj = raList[0];
            List<User> owners = [SELECT OCM_man_province_Rental__c FROM User WHERE Id=:parentObj.OwnerId LIMIT 1];
            if(owners.isEmpty()) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '申请者不存在！'));
                return null;
            }
            else {
                isSameCity = owners[0].OCM_man_province_Rental__c == parentObj.ToAgency__c;
            }
            masterDate = parentObj.Old_Rental_Apply__r.Asset_loaner_start_date__c;

            //20210508 ljh add 1672 start
            if (bieBeiPinFenLeiList.size() == 0 && String.isNotBlank(parentObj.Equipment_Type_F__c)) {
                for (String et : parentObj.Equipment_Type_F__c.split(',')) {
                    bieBeiPinFenLeiList.add(et);
                }
            }
            //20210508 ljh add 1672 end

            esdList = new List<EsdInfo>();
            List<Rental_Apply_Equipment_Set_Detail__c> eList = getDetails();
            for (Rental_Apply_Equipment_Set_Detail__c esd : eList) {
                EsdInfo ei = new EsdInfo(esd);
                esdList.add(ei);
            }
            if (!esdList.isEmpty()) {
                if (parentObj.Yi_loaner_arranged__c > 0) {
                    readOnly = true;
                }
                // 20210624 ljh add SFDC-C448GR start
                // 全部下架且非同城时才可编辑
                // else if(parentObj.StockDown_ng_num__c == 0 && !isSameCity) {
                //     slipEnabled = true;
                // }
                // 全部分配且非同城时才可编辑
                else if(parentObj.Wei_Assigned_Cnt__c == 0 && !isSameCity) {
                    slipEnabled = true;
                }
                // 20210624 ljh add SFDC-C448GR end
            }
            else {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '没有借出明细！'));
                return null;
            }
        }
        if(parentObj == null) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '借出申请不存在！'));
            return null;
        }
        if(parentObj.DeliverySlip__c != null) {
            List<FixtureDeliverySlip__c> slipList = [
                SELECT Id
                     , DeliveryType__c
                     , Name
                     , Distributor_method__c
                     , DeliveryCompany__c
                     , Wh_Staff__c
                  FROM FixtureDeliverySlip__c
                 WHERE Id=:parentObj.DeliverySlip__c
                 LIMIT 1
            ];
            if(slipList.isEmpty()) {
                slip = new FixtureDeliverySlip__c();
                slip.DeliveryType__c = '发货';
                slip.Wh_Staff__c = Userinfo.getUserId();
            }
            else {
                slip = slipList[0];
            }
        }
        else {
            slip = new FixtureDeliverySlip__c();
            slip.DeliveryType__c = '发货';
            slip.Wh_Staff__c = Userinfo.getUserId();
        }
        return null;
    }
    // 检索运输单
    public void searchSlip() {
        done_flg = false;
        String qryString = 'select Combine_Pack__c, Name, Id, DeliveryCompany_SlipNo__c,DeliveryType__c,Distributor_method__c,DeliveryCompany__c,Wh_Staff__c '
                + 'from FixtureDeliverySlip__c '
                + 'where Name =\''+ slip.Name +'\' and DeliveryType__c = \'发货\'';
        if (String.isNotBlank(slip.Distributor_method__c)) {
            qryString += ' and Distributor_method__c = \''+ slip.Distributor_method__c +'\'';
        }
        if (String.isNotBlank(slip.DeliveryCompany__c)) {
            qryString += ' and DeliveryCompany__c = \''+ slip.DeliveryCompany__c +'\'';
        }
        List<FixtureDeliverySlip__c> slipList = Database.query(qryString);

        if (slipList.size() > 0) {
            if (slipList.size() > 1) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '当前条件检索到复数条运输单，请追加检索条件!'));
                return ;
            }
            slip = slipList[0];
        }
        return ;
    }
    //20210518 ljh add 1289 start
    private Map<Id, Rental_Apply_Equipment_Set__c> getReasMap(Boolean cancle) {
        List<Rental_Apply_Equipment_Set__c> raesList = getReas(cancle,null);
        Map<Id, Rental_Apply_Equipment_Set__c> raesMap = new Map<Id, Rental_Apply_Equipment_Set__c>();

        for(Rental_Apply_Equipment_Set__c raesd:raesList) {
            raesMap.put(raesd.Id, raesd);
        }
        return raesMap;
    }
    //获取一览 cancle false 所有 else 未取消  raesId null 申请属下的所有一览 else 指定一览
    private List<Rental_Apply_Equipment_Set__c> getReas(Boolean cancle,Id raesId) {
        String soql = 'Select Id, Loaner_centre_mail_address__c, Fixture_Set__c, Substitute_Select_Again__c,Cancel_Select__c,canDelete__c,Test_Day__c,';
        soql += 'Rental_Apply__c, Irreplaceable_flag__c, Same_Accessory_flag__c, Received_Confirm__c, IndexFromUniqueKey__c,Old_RetalFSetDetail_Cnt__c,';
        soql += 'Rental_Num__c, Groupby_SortInt__c, Canceled__c, Canceled_Id__c, RetalFSetDetail_Cnt__c, Old_Rental_Apply__c,Rental_Start_Date__c,Rental_End_Date__c';
        if(cancle){
            soql += ' ,Loaner_code_F__c';
        }
        if(raesId != null){
            soql += ' ,Rental_Apply__r.Status__c,RAES_Status__c,Shippment_loaner_time2__c';
        }
        soql += ' From Rental_Apply_Equipment_Set__c';
        if(raesId != null){
            soql += ' Where Id = \'' + raesId+'\'';
        }else{
            soql += ' Where Rental_Apply__c = \'' + taId+'\'';
        }
        
        if(!cancle){
            soql +='AND Cancel_Select__c = '+cancle;
        }
        soql +=' ORDER BY Name';
        List<Rental_Apply_Equipment_Set__c> raess = Database.query(soql);
        return raess;
    }
    private List<Rental_Apply_Equipment_Set_Detail__c> getDetails(List<Rental_Apply_Equipment_Set__c> delRaesId) {
        List<Rental_Apply_Equipment_Set_Detail__c> eList = [
                SELECT Id FROM Rental_Apply_Equipment_Set_Detail__c WHERE Rental_Apply_Equipment_Set__c in :delRaesId
              ORDER BY Rental_Apply_Equipment_Set__r.Name, Rental_Apply_Equipment_Set__c, Is_Body__c DESC, Name
        ];
        return eList;
    }
    //20210518 ljh add 1289 end
    private Map<Id, Rental_Apply_Equipment_Set_Detail__c> getDetailsMap() {
        List<Rental_Apply_Equipment_Set_Detail__c> raesdList = getDetails();
        Map<Id, Rental_Apply_Equipment_Set_Detail__c> raesdMap = new Map<Id, Rental_Apply_Equipment_Set_Detail__c>();

        for(Rental_Apply_Equipment_Set_Detail__c raesd:raesdList) {
            raesdMap.put(raesd.Id, raesd);
        }
        return raesdMap;
    }
    private List<Rental_Apply_Equipment_Set_Detail__c> getDetails() {
        List<Rental_Apply_Equipment_Set_Detail__c> eList = [
                SELECT Id
                     , AgencyTempCancel__c
                     , Asset__c
                     , Asset__r.Internal_asset_location__c
                     , Asset__r.Internal_Asset_number_key__c
                     , Asset__r.SerialNumber
                     , Asset__r.Equipment_Type__c //20210508 ljh add 1672
                     , Cancel_Select__c
                     , DeliverySlip__c
                     , Fixture_Model_No_text__c
                     , Fixture_Model_No__c
                     , Fixture_OneToOne_Link_Id__c
                     , Fixture_QRCode_F__c
                     , Fixture_Set_Detail__c
                     , Fixture_Set_Id__c
                     , FSD_Fixture_Model_No__c
                     , FSD_Id__c
                     , FSD_Is_OneToOne_F__c
                     , FSD_Is_Optional_F__c
                     , FSD_Name_CHN__c
                     , FSD_OneToOneAccessory_Cnt_F__c
                     , IndexFromUniqueKey__c
                     , IndexFromUniqueKey_Text__c
                     , Internal_asset_location__c
                     , Internal_asset_location_before__c
                     , Is_Body__c
                     , Product_category_text__c
                     , RAESD_Status__c
                     , Rental_Apply_Equipment_Set__c
                     , Rental_Apply_Equipment_Set__r.First_RAESD__r.Fixture_Model_No__c
                     , Rental_Apply_Equipment_Set__r.Rental_Start_Date__c //20210519 ljh add 1829 start
                     , Rental_Apply_Equipment_Set__r.Irreplaceable_flag__c //20210519 ljh add 1829 start
                     , Rental_Apply_Equipment_Set__r.canDelete__c //20210519 ljh add 1829 start
                     , Rental_Apply_Equipment_Set__r.Substitute_flag__c //20210526 ljh 1829 add
                     , Rental_Apply_Equipment_Set__r.RAES_Status__c
                     , Rental_Apply_Equipment_Set__r.Shippment_loaner_time2__c
                     , Rental_Apply__r.Status__c //20210519 ljh add 1829 end
                     , Rental_Apply__r.Request_approval_time__c //20220309 SFDC-CC6CLJ phase5上线课题131 提交申请到备品出库时长 
                     , Add_Request_approval_time__c //20220309 ljh SFDC-CC6CLJ phase5上线课题131 提交申请到备品出库时长 
                     , ApplyToShipmentWorkTime__c   //20220309 ljh SFDC-CC6CLJ phase5上线课题131 提交申请到备品出库时长 
                     , Rental_Num__c
                     , Rental_Start_Date__c
                     , Select_Time__c
                     , SerialNumber__c
                     , SerialNumber_F__c
                     , SerialNumber_text__c
                     , Shippment_loaner_time__c
                     , StockDown__c
                     , LastModifiedDate
                     , LastModifiedBy.Name
                     , AgencyAssignAdd__c
                     , Rental_Apply__c
                     , Equipment_Type__c //20210508 ljh add 1834
                  FROM Rental_Apply_Equipment_Set_Detail__c
                 WHERE Rental_Apply__c = :taId
                   AND Cancel_Select__c = False
              ORDER BY Rental_Apply_Equipment_Set__r.Name, Rental_Apply_Equipment_Set__c, Is_Body__c DESC, Name
        ];
        return eList;
    }
    // 一览取消
    public void cancelSet() {
        done_flg = false;
        Savepoint sp = Database.setSavepoint();
        try {
            //20210420 ljh update start
            // if(String.isBlank(cancelReason)|| String.isBlank(cancelReasonRemark)){
            //     ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '取消理由和备注不可为空！'));
            //     return;
            // }

            // if(String.isBlank(cancelReason)) {
            //     if(String.isBlank(cancelReasonRemark)){
            //         ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '取消理由和取消理由备注不可为空！'));
            //     }else{
            //         ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '取消理由不可为空！'));  
            //     } 
            //     return;
            // }else if(String.isBlank(cancelReasonRemark)){
            //     ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '取消理由备注不可为空！'));
            //     return;
            // }
            // //20210420 ljh update end
           
            Set<Id> raesIdSet = new Set<Id>();
            Set<Id> mainIdSet = new Set<Id>();
            for(EsdInfo esd: esdList) {
                if(esd.checked) {
                    raesIdSet.add(esd.rec.Rental_Apply_Equipment_Set__c);
                    if(esd.rec.Is_Body__c) {
                        mainIdSet.add(esd.rec.Asset__c);
                    }
                }
            }
            Map<Id, Rental_Apply_Equipment_Set__c> raesMap = new Map<Id, Rental_Apply_Equipment_Set__c>([
                SELECT Id
                     , Cancel_Select__c
                     , Yi_loaner_arranged__c
                FROM Rental_Apply_Equipment_Set__c
                WHERE Id=:raesIdSet
                AND Cancel_Select__c = false
                AND Yi_loaner_arranged__c = 0
                FOR UPDATE
            ]);

            List<Rental_Apply_Equipment_Set__c> updateRaesList = new List<Rental_Apply_Equipment_Set__c>();
            for(Id raesId: raesIdSet) {
                if(raesMap.containsKey(raesId)) {
                    updateRaesList.add(new Rental_Apply_Equipment_Set__c(Id=raesId
                        , Cancel_Select__c = true
                        // , Cancel_Reason__c = cancelReason  //20210707 SFDC-C448KZ you
                        // , Loaner_cancel_Remarks__c = cancelReasonRemark));
                        , Cancel_Reason__c = this.parentObj.Cancel_Reason__c==null ? '':this.parentObj.Cancel_Reason__c
                        , Loaner_cancel_reason__c = this.parentObj.Loaner_cancel_reason__c
                        , Loaner_cancel_Remarks__c = this.parentObj.Loaner_cancel_request__c==null? this.parentObj.Loaner_cancel_reason__c :this.parentObj.Loaner_cancel_request__c
                        ));
                }
                else {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, raesId + '一览不可取消'));
                    return;
                }
            }
            if(!updateRaesList.isEmpty()) {
                FixtureUtil.withoutUpdate(updateRaesList);
                List<Rental_Apply_Equipment_Set_Detail__c> raesdList = [
                    SELECT Id
                         , Asset__c
                    FROM Rental_Apply_Equipment_Set_Detail__c
                    WHERE Rental_Apply_Equipment_Set__c IN:raesMap.keySet()
                    AND StockDown__c = true
                    AND Cancel_Select__c = true
                    FOR UPDATE
                ];
                List<Fixture_OneToOne_Link__c> linkList = new List<Fixture_OneToOne_Link__c>([
                    SELECT Id FROM Fixture_OneToOne_Link__c WHERE Main_Asset__c IN:mainIdSet
                ]);
                for(Fixture_OneToOne_Link__c link:linkList) {
                    link.Select_Accessory_Asset_Cnt__c = 0;
                }
                // link里的已分配数清空   
                Oly_TriggerHandler.bypass(AssetHandlerCheck.class.getName());
                FixtureUtil.withoutUpdate(linkList);
                Oly_TriggerHandler.clearBypass(AssetHandlerCheck.class.getName());

                init();
                done_flg = true;
            }
            //Database.rollback(sp);
        }
        catch (Exception ex) {
            system.debug('=====' + ex.getMessage());
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage()));
            Database.rollback(sp);
        }
       // cancelReason = '';
       // cancelReasonRemark = '';
    }

    // 日期适用按钮
    public void applyDate() {
        done_flg = false;
        String strMessage = null;
        Boolean hasError = false;
        if (parentObj.Asset_loaner_start_day__c == null) {
            hasError = true;
            strMessage = '请输入[备品预计出货日]';
        }
        if (parentObj.Asset_loaner_start_day__c != null && parentObj.Asset_loaner_start_day__c < Date.today()) {
            hasError = true;
            strMessage = '[备品预计出货日]必须入力从今天开始起的日期 ';
        }
        if (hasError) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, strMessage));
            return;
        }
        else {
            // 给打勾明细所在的一览设备品预计出货日
            Set<Id> raesIdSet = new Set<Id>();
            Boolean hasChecked = false;
            for(EsdInfo esd: esdList) {
                if((esd.checked || raesIdSet.contains(esd.rec.Rental_Apply_Equipment_Set__c))) {
                    hasChecked = true;
                    //20210519 ljh update 1829 start
                    if(esd.tempDetailStatus == '取消' && !esd.rec.Is_Body__c) {
                    //if(esd.tempDetailStatus == '取消') {
                        esd.tempDate = null;
                    }
                    //20210519 ljh update 1829 start
                    //else if(esd.rec.Is_Body__c) {
                    else if(esd.rec.Is_Body__c && esd.tempOldRaesIdSub == null) {
                    //20210519 ljh update 1829 end
                        esd.rec.Rental_Apply_Equipment_Set__r.Rental_Start_Date__c = parentObj.Asset_loaner_start_day__c;
                        esd.tempDate = parentObj.Asset_loaner_start_day__c;
                        raesIdSet.add(esd.rec.Rental_Apply_Equipment_Set__c);
                    }
                    else {
                        esd.tempDate = parentObj.Asset_loaner_start_day__c;
                    }
                }
                //20210521 ljh add 1829 start
                if(esd.tempOldRaesIdSub != null && raesIdSet.contains(esd.tempOldRaesIdSub)){
                    if(esd.tempDetailStatus == '取消'){
                        esd.tempDate = null;
                    }
                    else {
                        esd.tempDate = parentObj.Asset_loaner_start_day__c;
                    }
                }
                //20210521 ljh add 1829 end 
            }
            if(!hasChecked) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '未选择适用的一览！'));
            }
        }
    }
    private Boolean isRaStatusOK() {

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

        //检查是否可以继续
        // 20210809  ljh SFDC-C5HDC7 update start
        List<Rental_Apply__c> RaTarList = [
            SELECT Campaign__c
                 , Repair__c
                 , Campaign__r.Status
                 , Campaign__r.IF_Approved__c
                 , Campaign__r.Meeting_Approved_No__c
                 , Campaign__r.Approved_Status__c    //20220315 sx obpm备品决裁状态相关修改
                 // ,repair__r.Return_Without_Repair_Date__c
                 , Return_Without_Repair_Date_F__c
                 // , Repair__r.Repair_Final_Inspection_Date__c
                 , Repair_Final_Inspection_Date_F__c
                 // , Repair__r.Repair_Shipped_Date__c
                 , RC_return_to_office__c 
                 , demo_purpose2__c //1822 yc 20211025 已购待货目的，新品已有发货日不能出库
                 , Follow_UP_Opp__r.Shipping_Finished_Day_Func__c //1822 yc 20211025 已购待货目的，新品已有发货日不能出库
                 , next_action__c //1822 yc 20211108
                 , QIS_number__r.ReplaceDeliveryDate__c //1822 yc 20211108
              FROM Rental_Apply__c
             WHERE id =:taId
        ];
        for (Rental_Apply__c RaTar : RaTarList) {
            // 20230215 ljh DB202301265636 学会取消申请也拦截 start
            // if( RaTar.Campaign__r.Status == '取消'){
            //     ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '学会已取消，不能继续操作了'));
            if( RaTar.Campaign__r.Status == '取消' || RaTar.Campaign__r.Status == '取消申请中' ){
                String tempS = '';
                if(RaTar.Campaign__r.Status == '取消'){
                    tempS = '已取消';
                }else{
                    tempS = '申请取消中';
                }
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '学会'+tempS+'，不能继续操作了'));
            // 20230215 ljh DB202301265636 学会取消申请也拦截 end
                return false;
            }
            // else if(RaTar.Repair__r.Repair_Final_Inspection_Date__c != null){
            else if(RaTar.repair__c!=null && RaTar.Repair_Final_Inspection_Date_F__c != null ){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '存在修理最终检测日，不能继续了'));
                return false;
            }
            // else if(RaTar.repair__r.Return_Without_Repair_Date__c != null && RaTar.repair__c!=null ){
            else if(RaTar.repair__c!=null && RaTar.Return_Without_Repair_Date_F__c != null){    
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '未修理归还日不为空，不能出库'));
                return false;
            }
            // else if(RaTar.Repair__r.Repair_Shipped_Date__c != null ){
            else if(RaTar.repair__c!=null && RaTar.RC_return_to_office__c != null){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '存在RC修理返送日，不能继续了'));
                return false;
            }
            // 20210809  ljh SFDC-C5HDC7 update end
            //1822 yc 20211025 已购待货目的，新品已有发货日不能出库 start
            else if(RaTar.demo_purpose2__c=='已购待货' && RaTar.Follow_UP_Opp__r.Shipping_Finished_Day_Func__c!= null){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '已购待货目的，新品已有发货日，不能继续了'));
                return false;
            }
            //1822 yc 20211025 已购待货目的，新品已有发货日不能出库 end
            //1822 yc 20211108 start
            else if(RaTar.demo_purpose2__c=='索赔QIS' && RaTar.next_action__c=='无偿更换' && RaTar.QIS_number__r.ReplaceDeliveryDate__c!= null){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '索赔QIS目的，QIS已有新品发货日,不能继续了'));
                return false;
            }//1822 yc 20211108 end
            //20220225 sx start obpm 办事处增加判断：是否申请决裁勾着没有决裁编号不能进行操作
            else if(RaTar.Campaign__c != null && RaTar.Campaign__r.IF_Approved__c && RaTar.Campaign__r.Meeting_Approved_No__c == null){
                ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Error, '已申请决裁但决裁编码为空'));
                return false;
            }
            //20220225 sx end obpm 办事处增加判断：是否申请决裁勾着没有决裁编号不能进行操作
            //20220315 sx  obpm备品决裁状态相关修改 add start
            else if(RaTar.Campaign__c != null && RaTar.Campaign__r.IF_Approved__c && RaTar.Campaign__r.Meeting_Approved_No__c != null && statusList.contains(RaTar.Campaign__r.Approved_Status__c)){
                ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Error, '已申请决裁但决裁状态不符合条件'));
                return false;
            }
            //20220315 sx  obpm备品决裁状态相关修改 add end
        }
        return true;
    }
    /**
    @description 分配按钮
    */
    public void assign() {
        done_flg = false;
        if(!isRaStatusOK()) {
            return;
        }
        Savepoint sp = Database.setSavepoint();
        try {
            Map<Id, Rental_Apply_Equipment_Set_Detail__c> raesdMap = getDetailsMap(); // 取最新的明细数据
            Map<Id, Rental_Apply_Equipment_Set__c> updateRaesMap = new Map<Id, Rental_Apply_Equipment_Set__c>(); // 用于更新一览的预计货日
            List<Rental_Apply_Equipment_Set_Detail__c> updateRaesdList = new List<Rental_Apply_Equipment_Set_Detail__c>(); // 更新明细
            List<Rental_Apply_Equipment_Set_Detail__c> cancelRaesdList = new List<Rental_Apply_Equipment_Set_Detail__c>(); // 更新取消的明细
            List<Rental_Apply_Equipment_Set_Detail__c> insertRaesdList = new List<Rental_Apply_Equipment_Set_Detail__c>(); // 追加明细
            Map<Id, Rental_Apply_Equipment_Set_Detail__c> deleteRaesdMap = new Map<Id, Rental_Apply_Equipment_Set_Detail__c>(); // 删除因重新分配而取消的明细
            List<Rental_Apply_Equipment_Set__c>  deleteRaesList = new List<Rental_Apply_Equipment_Set__c>(); //20210521 ljh add 1829 删除分配替代品中间的生成的一览
            Map<Id,Rental_Apply_Equipment_Set__c>  updateRaesMap1 = new Map<Id,Rental_Apply_Equipment_Set__c>(); //20210523 ljh add 1829 更新替代分配一览
            Rental_Apply__c updateRa = null;

            Set<String> oldLinkIdSet = new Set<String> (); // 换分配或删明细时旧的link已分配数量要清0
            Set<Id> raesIdSet = new Set<Id>();
            Set<Id> raesIdSetCheck = new Set<Id>(); //20210601 ljh add 1829
            Set<Id> raesIdSubSet = new Set<Id>(); //20210520 ljh add 1829
            Set<Id> mainIds = new Set<Id>(); // 主体Id集合，用于检查是否有重复分配

            Datetime now = System.now();
            Id userId =  Userinfo.getUserId();
            Set<Id> assIdSet = new Set<Id>();
            Boolean hasChecked = false;
            //20210518 ljh add 1829 start
            Map<Id, Id> mapOnId = new Map<Id, Id>();
            List<Rental_Apply_Equipment_Set__c> getReasListAll = getReas(true,null);//获取所有一览
            Map<Id, Rental_Apply_Equipment_Set__c> getReasMap = getReasMap(false);//未取消的一览
            Map<String,Integer> fsIndexMap =  new Map<String,Integer>();
            for(Rental_Apply_Equipment_Set__c reas:getReasListAll){
                if(fsIndexMap.containsKey(reas.Loaner_code_F__c)){
                    if(Integer.valueOf(reas.IndexFromUniqueKey__c) > fsIndexMap.get(reas.Loaner_code_F__c) ){
                        fsIndexMap.put(reas.Loaner_code_F__c,Integer.valueOf(reas.IndexFromUniqueKey__c));
                    }
                }else{
                    fsIndexMap.put(reas.Loaner_code_F__c,Integer.valueOf(reas.IndexFromUniqueKey__c));
                }
                
            }
            //遍历数据 新增的一览和明细
            Map<String,Date> RentalStartDateMap = new Map<String,Date>();
            for(EsdInfo esd: esdList) {
                if(esd.checked || raesIdSetCheck.contains(esd.rec.Rental_Apply_Equipment_Set__c)){
                    Rental_Apply_Equipment_Set_Detail__c raesd = raesdMap.get(esd.rec.Id);
                    if (esd.checked && esd.rec.Rental_Apply_Equipment_Set__r.Rental_Start_Date__c == null) {
                        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '请输入[备品预计出货日]'));
                        return;
                    }
                    if (esd.checked && esd.rec.Rental_Apply_Equipment_Set__r.Rental_Start_Date__c != null && esd.rec.Rental_Apply_Equipment_Set__r.Rental_Start_Date__c < Date.today()) {
                        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '[备品预计出货日]必须入力从今天开始起的日期'));
                        return;
                    }
                    if(esd.rec.Is_Body__c && esd.rec.Asset__c == null && !esd.SubChecked) {
                        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, esd.rec.Fixture_Model_No__c + '未分配，无法保存!'));
                        return;
                    }
                    if(raesd != null && raesd.LastModifiedDate != esd.rec.LastModifiedDate) {
                        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, raesd.Fixture_Model_No__c + '后台数据被' + raesd.LastModifiedBy.Name + '修改，请刷新画面！'));
                        return;
                    }
                    if(esd.checked && esd.SubChecked){
                        if(!IsCanSubReas(esd.rec.Rental_Apply_Equipment_Set__c)) return;//验证是否可分配替代品 已有两处限制1.初始化class中 2.扫描的时候 若101可注释此行代码
                        raesIdSubSet.add(esd.rec.Rental_Apply_Equipment_Set__c);
                    }
                    if(esd.rec.Is_Body__c) { 
                        raesIdSetCheck.add(esd.rec.Rental_Apply_Equipment_Set__c);
                    }
                    RentalStartDateMap.put(esd.rec.Rental_Apply_Equipment_Set__c,esd.rec.Rental_Apply_Equipment_Set__r.Rental_Start_Date__c);
                }                     
            }
            // 20210906 ljh SFDC-C568C4 update start
            List<Rental_Apply_Equipment_Set__c> raesNUList = new List<Rental_Apply_Equipment_Set__c>();
            Set<Id> nRAEId = new Set<Id>();
            for(EsdInfo esd: esdList) {
                if(mainIds.contains(esd.rec.Asset__c)) {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, esd.tempSerial + '不可被同时分配给多个配套一览!'));
                    return;
                }
                if(esd.rec.Is_Body__c && esd.rec.Asset__c != null) {
                    mainIds.add(esd.rec.Asset__c);
                    if(raesIdSubSet.contains(esd.tempOldRaesIdSub)){
                        if(esd.tempOldRaesIdSub != null && getReasMap.get(esd.tempOldRaesIdSub) != null){
                            Rental_Apply_Equipment_Set__c craes = getReasMap.get(esd.tempOldRaesIdSub);//原一览
                            Rental_Apply_Equipment_Set__c robj = new Rental_Apply_Equipment_Set__c(); //替换生成的新的一览
                            robj = craes.clone();
                            // 4.新增一條相同的“借出備品配套一覽”記錄----clone一条新记录（直接修改分配替代品页面选中的那条记录，然后插入数据库）
                            robj.Old_RetalFSetDetail_Cnt__c = craes.canDelete__c?craes.Old_RetalFSetDetail_Cnt__c:craes.RetalFSetDetail_Cnt__c; // 原配套明细数
                            // 防止clone时与申请单内已有备品配套UK重复
                            // 20210914 ljh SFDC-C568C4 update
                            if(fsIndexMap.containsKey(esd.tempModel)){
                                robj.IndexFromUniqueKey__c = fsIndexMap.get(esd.tempModel)+1;
                                Integer tempIndex = fsIndexMap.get(esd.tempModel)+1;
                                fsIndexMap.put(esd.tempModel,tempIndex);
                            }else{
                                robj.IndexFromUniqueKey__c = 1;
                            }
                            // 20210914 ljh SFDC-C568C4 update
                            // 20210914 ljh SFDC-C568C4 add start
                            if(!fsIndexMap.containsKey(esd.tempModel)){
                                fsIndexMap.put(esd.tempModel, 1);
                            }
                            // 20210914 ljh SFDC-C568C4 add end
                            //robj.Groupby_SortInt__c = craes.Groupby_SortInt__c;
                            robj.Irreplaceable_flag__c = false;    // 代替品不可
                            robj.Same_Accessory_flag__c = false;   // 同一附属品
                            robj.Substitute_flag__c = true;        // 代替品Flag勾选
                            robj.Fixture_Set__c = esd.tempFixtureSet; //保有设备
                            robj.Cancel_Select__c = false; 
                            robj.Cancel_Reason__c = '';
                            robj.Rental_Start_Date__c = RentalStartDateMap.containsKey(esd.tempOldRaesIdSub)?RentalStartDateMap.get(esd.tempOldRaesIdSub):craes.Rental_Start_Date__c ;
                            robj.Rental_End_Date__c = setRentalEndDate(robj.Rental_Start_Date__c, parentObj);

                            //robj.Rental_End_Date__c  = robj.Rental_Start_Date__c + Integer.valueOf(craes.Test_Day__c);
                            // 新记录 Canceled__c & Canceled_Id__c 为选中一览的Id
                            robj.Canceled__c = craes.canDelete__c?craes.Canceled__c:craes.Id;
                            robj.Canceled_Id__c = craes.canDelete__c?robj.Canceled_Id__c:craes.Id;
                            if(!craes.canDelete__c){
                                craes.Cancel_Select__c = true; 
                                craes.Cancel_Reason__c = '分配代替品';
                                // 20210906 ljh SFDC-C6D9C2 add start
                                craes.Rental_Start_Date__c = null;
                                craes.Rental_End_Date__c = null;
                                // 20210906 ljh SFDC-C6D9C2 add end
                                robj.canDelete__c = true;
                                raesNUList.add(craes);
                                raesNUList.add(robj);
                                // FixtureUtil.withoutUpsertObjects(new Rental_Apply_Equipment_Set__c[]{craes,robj});
                                // 原一览关联clone出来的新一览
                                nRAEId.add(craes.Id);
                                // craes.New_Rental_Apply_Equipment__c = robj.Id;
                                //FixtureUtil.withoutUpsertObjects(new Rental_Apply_Equipment_Set__c[]{craes});
                            }else{
                                robj.canDelete__c = true;
                                raesNUList.add(robj);
                                // FixtureUtil.withoutUpsertObjects(new Rental_Apply_Equipment_Set__c[]{robj});
                                // 原一览关联clone出来的新一览
                                nRAEId.add(craes.Canceled__c);
                                // Rental_Apply_Equipment_Set__c oldCraes = new Rental_Apply_Equipment_Set__c();
                                // oldCraes.Id = craes.Canceled__c;
                                // oldCraes.New_Rental_Apply_Equipment__c = robj.Id;
                                //FixtureUtil.withoutUpsertObjects(new Rental_Apply_Equipment_Set__c[]{oldCraes}); 
                                deleteRaesList.add(craes);
                            }
                            // mapOnId.put(esd.tempOldRaesIdSub,robj.Id);   
                        }
                    }
                }
            } 
            FixtureUtil.withoutUpsertObjects(raesNUList);
            // 原一览关联clone出来的新一览
            List<Rental_Apply_Equipment_Set__c> nRAEList = new List<Rental_Apply_Equipment_Set__c>(); 
            Map<Id,List<Id>> tempMap = new Map<Id,List<Id>>();
            List<Id> IdList = new List<Id>();
            Map<Id,Rental_Apply_Equipment_Set__c> cancelidMap = new Map<Id,Rental_Apply_Equipment_Set__c>();
            for(Rental_Apply_Equipment_Set__c raeT:[Select Id,Canceled__c,Canceled__r.First_RAESD__r.Queue_Time_Text__c,Canceled__r.First_RAESD__r.Queue_Day_Text__c From Rental_Apply_Equipment_Set__c WHERE Canceled__c IN :nRAEId order by CreatedDate desc]){
                if(tempMap.containsKey(raeT.Canceled__c)){
                    IdList = tempMap.get(raeT.Canceled__c);
                    IdList.add(raeT.Id);
                    tempMap.put(raeT.Canceled__c,IdList);
                }else{
                    IdList = new List<Id>();
                    IdList.add(raeT.Id);
                    tempMap.put(raeT.Canceled__c,IdList);
                    cancelidMap.put(raeT.Id,raeT); //新一览id和新一览数据  //20210914 you SFDC-C6E3WQ 
                }                
            }
            system.debug('===='+cancelidMap);
            for(Id key:tempMap.keySet()){
                Rental_Apply_Equipment_Set__c tempRae = new Rental_Apply_Equipment_Set__c();
                tempRae.Id = key;
                tempRae.New_Rental_Apply_Equipment__c = tempMap.get(key)[0];

                nRAEList.add(tempRae);
                if(tempMap.get(key).size() == 2){
                    mapOnId.put(tempMap.get(key)[1],tempMap.get(key)[0]);
                }else{
                    mapOnId.put(key,tempMap.get(key)[0]);
                }
            }
            FixtureUtil.withoutUpsertObjects(nRAEList);
            // System.debug('zheli:'+mapOnId);
            // 20210906 ljh SFDC-C568C4 update end
            //重新构造esdlist  原一览关联clone出来的新一览
            for(Integer i = 0; i < esdList.size(); i++) {
                EsdInfo esd4 = esdList[i];
                //分配替代品new 关联reasId
                if(esd4.tempOldRaesIdSub != null && mapOnId.containsKey(esd4.tempOldRaesIdSub) && getReasMap.containsKey(esd4.tempOldRaesIdSub)){
                    esd4.rec.Rental_Apply_Equipment_Set__c = mapOnId.get(esd4.tempOldRaesIdSub);
                    if(esd4.rec.Is_Body__c){
                        esd4.checked = true;
                    }
                    esd4.tempDate = RentalStartDateMap.get(esd4.tempOldRaesIdSub);
                }
            }
            //20210518 ljh add 1829 end
            for(EsdInfo esd: esdList) {
                // if(esd.rec.Is_Body__c){
                //     System.debug('zheli00:'+esd.checked);
                // }
                //20210518 ljh update 1829 start
                /*
                if(mainIds.contains(esd.rec.Asset__c)) {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, esd.tempSerial + '不可被同时分配给多个配套一览!'));
                    return;
                }
                if(esd.rec.Is_Body__c && esd.rec.Asset__c != null) {
                    mainIds.add(esd.rec.Asset__c);
                }*/
                //20210518 ljh update 1829 end
                if(esd.checked || raesIdSet.contains(esd.rec.Rental_Apply_Equipment_Set__c)) {
                    //20210523 ljh update 1829 start
                    // if(esd.rec.Is_Body__c && esd.rec.Asset__c == null && !esd.SubChecked) {
                    //     ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, esd.rec.Fixture_Model_No__c + '未分配，无法保存!'));
                    //     return;
                    // }
                    //20210523 ljh update 1829 end
                    hasChecked = true;
                    if(!raesdMap.containsKey(esd.rec.Id)) {
                        //20210518 ljh update 1829 start
                        //if(esd.tempStatus == '追加') {
                        if(esd.tempStatus == '追加' || esd.tempOldRaesIdSub != null) {
                        //20210518 ljh update 1829 end
                            esd.rec.Id = null;
                            esd.rec.Select_Time__c = now;
                            if(esd.tempOldRaesIdSub != null && esd.tempStatus == '取消'){
                                //替代扫描的做临时取消
                                esd.rec.AgencyTempCancel__c = true;
                                esd.rec.AgencyTempCancelTime__c = now;
                                esd.rec.Select_Time__c = null;
                            }
                            insertRaesdList.add(esd.rec);
                        }
                        //20210518 ljh update 添加if 1829 start
                        // 不continue的情况  1.本次替代扫描(esd.tempOldRaesIdSub != null)&esd.tempStatus != '取消'
                        if( esd.tempOldRaesIdSub == null || esd.tempStatus == '取消'){
                            continue;
                        }
                        //20210518 ljh update 添加if 1829 end    
                    }    
                    Rental_Apply_Equipment_Set_Detail__c raesd = raesdMap.get(esd.rec.Id);
                    //20210519  ljh 1829 update start
                    // if(raesd.LastModifiedDate != esd.rec.LastModifiedDate) {
                    //     ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, raesd.Fixture_Model_No__c + '后台数据被' + raesd.LastModifiedBy.Name + '修改，请刷新画面！'));
                    //     return;
                    // }
                    // 与后台数据做比较，防止重复更新  //20210519  ljh 1829 update 下面的If 增加 raesd != null &&
                    if(esd.rec.Asset__c != null) {
                        //20210523 ljh add 1829 start
                        //一对一还是需要在这里更新
                        //system.debug('zheli000:'+esd.tempStatus+'~'+esd.tempModel+'~'+esd.SubChecked+'~'+oldLinkIdSet);
                        if(esd.SubChecked && esd.tempStatus == '取消' && raesd != null && raesd.Fixture_OneToOne_Link_Id__c != null){
                            oldLinkIdSet.add(raesd.Fixture_OneToOne_Link_Id__c);
                        }
                        //20210523 ljh add 1829 end
                        if(raesd != null && !esd.SubChecked && //20210523 ljh 条件 add 1829
                        (raesd.Asset__c != esd.rec.Asset__c // 保有设备变化
                            || raesd.Fixture_OneToOne_Link_Id__c != esd.rec.Fixture_OneToOne_Link_Id__c)) { // link变化
                            // 换link时旧link里的已分配数在明细更新时清掉
                            oldLinkIdSet.add(raesd.Fixture_OneToOne_Link_Id__c);
                            assIdSet.add(esd.rec.Asset__c); //20210523 ljh 1829 看代码没用到
                            assIdSet.add(raesd.Asset__c); //20210523 ljh 1829 看代码没用到

                            esd.rec.Select_Time__c = now;
                            if(raesd.StockDown__c) {
                                // 下架后重新分配
                                /*raesd.Cancel_Select__c = true;
                                raesd.Cancel_Reason__c = '重新分配';
                                cancelRaesdList.add(raesd);

                                // 用画面上显示的造明细
                                esd.rec.Id = null;
                                esd.rec.StockDown__c = false;
                                esd.rec.Fixture_Model_No_text__c      = raesd.FSD_Fixture_Model_No__c;
                                esd.rec.Fixture_Name_text__c          = raesd.FSD_Name_CHN__c;
                                esd.rec.Canceled__c                   = raesd.Id;
                                esd.rec.FSD_Is_Optional__c            = raesd.FSD_Is_Optional_F__c;
                                esd.rec.FSD_Is_OneToOne__c            = raesd.FSD_Is_OneToOne_F__c;
                                esd.rec.FSD_OneToOneAccessory_Cnt__c  = raesd.FSD_OneToOneAccessory_Cnt_F__c;
                                esd.rec.Rental_Num__c                 = raesd.Rental_Num__c;
                                esd.rec.LastModifiedDate              = null;//20210522 ljh add 1829
                                esd.rec.LastModifiedById              = null;//20210522 ljh add 1829
                                insertRaesdList.add(esd.rec);*/
                                /**
                                20210916 ljh 现在没有下架操作，分配后发货，点击发货按钮的时候更新下架，
                                所以不存在下架后重新分配 为了覆盖率注释代码
                                */ 
                            }
                            else {
                                updateRaesdList.add(esd.rec);
                            }
                        }
                    }
                    else { // 画面上取消，后台做临时取消
                        //20210523 ljh add  if 1829 end
                        //system.debug('zheli001:'+esd.tempModel+'~'+esd.SubChecked+'~'+raesd.Fixture_OneToOne_Link_Id__c);
                        if(raesd.Fixture_OneToOne_Link_Id__c != null){
                            oldLinkIdSet.add(raesd.Fixture_OneToOne_Link_Id__c); 
                        }
                        //20210523 ljh add  if 1829 end
                        if(!raesd.StockDown__c) {
                            // 针对从link追加出来的明细，未下架时取消直接删除
                            if(raesd.AgencyAssignAdd__c) {
                                deleteRaesdMap.put(raesd.Id, raesd);
                            }
                            else if(esd.tempOldRaesIdSub == null && !esd.SubChecked){ //20210523 add if 1829 
                                // 本来申请的做临时取消
                                esd.rec.AgencyTempCancel__c = true;
                                esd.rec.AgencyTempCancelTime__c = now;
                                updateRaesdList.add(esd.rec);
                            }
                        }
                        else if(esd.tempOldRaesIdSub == null && !esd.SubChecked){ //20210523 add if 1829 
                            raesd.Cancel_Select__c = true;
                            raesd.Cancel_Reason__c = '重新分配';
                            cancelRaesdList.add(raesd);
                        }
                    }
                    if(esd.rec.Is_Body__c) { 
                        raesIdSet.add(esd.rec.Rental_Apply_Equipment_Set__c);
                        //20210519 ljh update ljh 1829 start  增加条件 esd.tempOldRaesIdSub == null  !esd.SubChecked
                        //if(esd.rec.Rental_Apply_Equipment_Set__r.Rental_Start_Date__c != raesd.Rental_Start_Date__c) {
                        if(!esd.SubChecked &&
                            (   raesd == null ||
                                (raesd != null && esd.rec.Rental_Apply_Equipment_Set__r.Rental_Start_Date__c != raesd.Rental_Start_Date__c)
                            )
                        ) { 
                            if (esd.rec.Rental_Apply_Equipment_Set__r.Rental_Start_Date__c == null && esd.tempOldRaesIdSub == null) {
                                
                                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '请输入[备品预计出货日]'));
                                return;
                            }
                            if (esd.rec.Rental_Apply_Equipment_Set__r.Rental_Start_Date__c != null && esd.rec.Rental_Apply_Equipment_Set__r.Rental_Start_Date__c < Date.today() && esd.tempOldRaesIdSub == null) {
                                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '[备品预计出货日]必须入力从今天开始起的日期'));
                                return;
                            }
                        //20210519 ljh update ljh 1829 end 
                            //20210430 ljh XLII-C2F3AN start
                            //if(esd.tempDate == null) {
                            if(esd.tempOldRaesIdSub == null) { //20210520 ljh 1829 add 
                                esd.tempDate = esd.rec.Rental_Apply_Equipment_Set__r.Rental_Start_Date__c;
                            }
                            //}
                            //20210430 ljh XLII-C2F3AN end
                            Date endDay = esd.tempDate;
                            //system.debug('zheli000:'+esd.tempDate+'~'+parentObj.Hope_Lonaer_date_Num__c);
                            switch on parentObj.demo_purpose2__c{
                                when '试用（无询价）','试用（有询价）','新产品评价','其他','协议借用' {
                                    endDay = esd.tempDate + intValueOf(parentObj.Hope_Lonaer_date_Num__c);
                                }
                                when '一般用户','保修用户','市场多年保修','再修理','索赔QIS','已购待货','故障排查' {
                                    endDay = esd.tempDate + 30;
                                }
                                when '学会展会' {
                                    endDay = parentObj.Campaign_EndDate_F__c + 5;
                                }
                            }
                            //esd.tempDate = esd.rec.Rental_Apply_Equipment_Set__r.Rental_Start_Date__c;
                            updateRaesMap.put(esd.rec.Rental_Apply_Equipment_Set__c,
                                                new Rental_Apply_Equipment_Set__c(
                                                    Id = esd.rec.Rental_Apply_Equipment_Set__c
                                                  , Rental_Start_Date__c = esd.tempDate
                                                  , Rental_End_Date__c = endDay));
                            if(updateRa == null) {
                                updateRa = new Rental_Apply__c(Id=parentObj.Id
                                    , Asset_loaner_start_day__c=esd.tempDate
                                    , Asset_loaner_closed_day__c=endDay
                                );
                            }
                            else {
                                if(esd.tempDate > updateRa.Asset_loaner_start_day__c) {
                                    updateRa.Asset_loaner_start_day__c = esd.tempDate;
                                }
                                if(endDay > updateRa.Asset_loaner_closed_day__c) {
                                    updateRa.Asset_loaner_closed_day__c = endDay;
                                }
                            }
                        }   
                    }
                    //对于分配替代之后下架在分配 把可删除标记 false 20210527 ljh 1829 start
                    if(esd.tempOldRaesIdSub == null && !esd.SubChecked){
                        Rental_Apply_Equipment_Set__c oldUpdateCraes = new Rental_Apply_Equipment_Set__c();
                        oldUpdateCraes.Id = esd.rec.Rental_Apply_Equipment_Set__c;
                        oldUpdateCraes.canDelete__c = false;
                        updateRaesMap1.put(esd.rec.Rental_Apply_Equipment_Set__c,oldUpdateCraes);
                    }
                    //20210527 ljh 1829 end
                }
            }
            if(!hasChecked) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '请勾选后再分配！'));
                return;
            }
            Boolean needReset = false;
            // 必须先更新一览的预计出货日，否则明细分配不上
            if(!updateRaesMap.isEmpty()) {
                //print('更新一览', updateRaesMap);
                FixtureUtil.withoutUpdate(updateRaesMap.values());
                if(updateRa != null) {
                    List<Rental_Apply__c> raList = [
                        SELECT Id
                          , Asset_loaner_start_day__c
                          , Asset_loaner_closed_day__c
                        FROM Rental_Apply__c
                        WHERE Id=:parentObj.Id
                    ];
                    if(!raList.isEmpty()
                        && (raList[0].Asset_loaner_start_day__c == null
                            || raList[0].Asset_loaner_closed_day__c == null)) {
                        FixtureUtil.withoutUpdate(new List<Rental_Apply__c> {updateRa});
                    }
                }
                updateRaesMap.clear();
                updateRa = null;
                needReset = true;
            }
            Map<Id, Fixture_OneToOne_Link__c> updateLinkMap = new Map<Id, Fixture_OneToOne_Link__c>();
            // 旧link清0
            //system.debug('更新link00:'+oldLinkIdSet);
            if(!oldLinkIdSet.isEmpty()) {
                for(String linkId:oldLinkIdSet) {
                    if(String.isBlank(linkId)){
                        continue;
                    }
                    updateLinkMap.put(linkId, new Fixture_OneToOne_Link__c(Id=linkId, Select_Accessory_Asset_Cnt__c=0));
                }
            }
            List<Asset> assList = [SELECT Id FROM Asset WHERE Id IN:assIdSet FOR UPDATE];
            Oly_TriggerHandler.bypass(AssetHandlerCheck.class.getName());
            // 删除明细
            if(!deleteRaesdMap.isEmpty()) {
                //print('删除明细', deleteRaesdMap);
                FixtureUtil.withoutDelete(deleteRaesdMap.values());
                needReset = true;
            }
            if(!cancelRaesdList.isEmpty()) {
                updateRaesdList.addAll(cancelRaesdList);
                //FixtureUtil.withoutUpdate(cancelRaesdList);
            }
            //20210522 ljh add 1829 start
            if(updateRaesMap1.size() > 0){
                //更新删除验证标识
                FixtureUtil.withoutUpdate(updateRaesMap1.values());
            }
            //20210522 ljh add 1829 end
            // 更新现有明细
            if(!updateRaesdList.isEmpty()) {
                for(Rental_Apply_Equipment_Set_Detail__c raesd: updateRaesdList) {
                    String linkId = raesd.Fixture_OneToOne_Link_Id__c;
                    if(String.isBlank(linkId)){
                        continue;
                    }
                    Fixture_OneToOne_Link__c link;
                    // link分配数量占用
                    if(updateLinkMap.containsKey(linkId)) {
                        link = updateLinkMap.get(linkId);
                    }
                    else {
                        link = new Fixture_OneToOne_Link__c(Id = linkId, Select_Accessory_Asset_Cnt__c = 0);
                    }
                    link.Select_Accessory_Asset_Cnt__c += 1;
                    updateLinkMap.put(linkId, link);
                }
                //print('更新明细', updateRaesdList);
                FixtureUtil.withoutUpsertObjects(updateRaesdList);
                needReset = true;
            }
            // 插入后设置一览的第一条明细，并在最后更新
            List<Rental_Apply_Equipment_Set_Detail__c> rupsobjList =new List<Rental_Apply_Equipment_Set_Detail__c>();//20210914 you SFDC-C6E3WQ
                
            // 插入新追加的明细
            if(!insertRaesdList.isEmpty()) {
                for(Rental_Apply_Equipment_Set_Detail__c raesd: insertRaesdList) {
                    String linkId = raesd.Fixture_OneToOne_Link_Id__c;
                    if(String.isBlank(linkId)){
                        continue;
                    }
                    Fixture_OneToOne_Link__c link;
                    // link分配数量占用
                    if(updateLinkMap.containsKey(linkId)) {
                        link = updateLinkMap.get(linkId);
                    }
                    else {
                        link = new Fixture_OneToOne_Link__c(Id = linkId, Select_Accessory_Asset_Cnt__c = 0);
                    }
                    link.Select_Accessory_Asset_Cnt__c += 1;
                    updateLinkMap.put(linkId, link);
                }
                //print('新建明细', insertRaesdList);
                FixtureUtil.withoutUpsertObjects(insertRaesdList);
                for(Rental_Apply_Equipment_Set_Detail__c raesd: insertRaesdList) {
                    if(raesd.Is_Body__c) {
                        Id raesId = raesd.Rental_Apply_Equipment_Set__c;
                        //20210914 you SFDC-C6E3WQ start
                        system.debug('20210914=='+raesId);
                        if(cancelidMap.containsKey(raesId)){
                           raesd.Queue_Time_Text__c = cancelidMap.get(raesId).Canceled__r.First_RAESD__r.Queue_Time_Text__c;
                           raesd.Queue_Day_Text__c = cancelidMap.get(raesId).Canceled__r.First_RAESD__r.Queue_Day_Text__c;
                        }
                        rupsobjList.add(raesd);
                        //20210914 you SFDC-C6E3WQ end
                        updateRaesMap.put(raesId, new Rental_Apply_Equipment_Set__c(Id=raesId, First_RAESD__c=raesd.Id));
                    }
                }
                needReset = true;
            }
            if(!updateLinkMap.isEmpty()) {
                //print('更新link', updateLinkMap);
                FixtureUtil.withoutUpdate(updateLinkMap.values());
                needReset = true;
            }
            // 一览的第一条明细必须待新明细插入后才能设
            if(!updateRaesMap.isEmpty()) {
                //print('更新一览', updateRaesMap);
                FixtureUtil.withoutUpdate(updateRaesMap.values());
                needReset = true;
            }
            // Upsert 
            FixtureUtil.withoutUpsertObjects(rupsobjList);//20210914 you SFDC-C6E3WQ
            //20210522 ljh add 1829 start
            if(deleteRaesList.size() > 0){
                //删除中间替代
                //先删除一览明细，在删除一览吧~为了释放内存~
                FixtureUtil.withoutDelete(getDetails(deleteRaesList));
                FixtureUtil.withoutDelete(deleteRaesList);
                needReset = true;
            }
            Oly_TriggerHandler.clearBypass(AssetHandlerCheck.class.getName());
            //20210522 ljh add 1829 end
            if(needReset) {
                init();
                done_flg = true;
            }
            //Database.rollback(sp);
        }
        catch (Exception ex) {
            system.debug('=====' + ex.getMessage()+ex.getStackTraceString());
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage()));
            Database.rollback(sp);
            done_flg = false;
        }
    }
    //// 调试用
    //private void print(String title, Map<Id, Object> m) {
    //    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Info, title));
    //    for(Id a:m.keyset()) {
    //        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Info, '' + m.get(a)));
    //    }
    //}
    //// 调试用
    //private void print(String title, List<Object> l) {
    //    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Info, title));
    //    for(Object o:l) {
    //        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Info, '' + o));
    //    }
    //}
    /**
    @description 根据主体型号和打勾情况，找出要分配的一览，返回一览的第一条明细和最后一条明细的下标+1
    @param linkList 主体连着的所有一对一link
    @return 最匹配的一览Id
    */
    private Id getBestRaesId(Asset mainAsset, List<Fixture_OneToOne_Link__c> linkList) {
        Id bestRaesId = null;
        // 一览Id->一览下的明细
        Map<Id,List<EsdInfo>> detailsMap = new Map<Id, List<EsdInfo>>();
        // 有勾选的
        for(EsdInfo esd:esdList) {
            Id raesId = esd.rec.Rental_Apply_Equipment_Set__c;
            if(esd.checked || detailsMap.containsKey(esd.rec.Rental_Apply_Equipment_Set__c)) {
                List<EsdInfo> tempList = new List<EsdInfo>();
                if(detailsMap.containsKey(raesId)) {
                    tempList = detailsMap.get(raesId);
                }
                tempList.add(esd);
                detailsMap.put(raesId, tempList);
            }
        }
        if(!detailsMap.isEmpty()) {
            Integer minDis = null;
            for(Id raesId: detailsMap.keySet()) {
                Integer distance = getRaesMatchingDistance(detailsMap.get(raesId), mainAsset.Fixture_Model_No_F__c, linkList) ;
                if(distance == null) {
                    // 只要有型号不符合就停止
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '分配的主体型号与当前勾选的申请型号不符'));
                    return null;
                }
                else if(minDis == null || distance < minDis) {
                    bestRaesId = raesId;
                    minDis = distance;
                }
            }
        }
        // 没有勾选的
        else {
            for(EsdInfo esd:esdList) {
                // 扫出的主体如果已被分配给一览，直接返回
                if(esd.rec.Asset__c == mainAsset.Id) {
                    return esd.rec.Rental_Apply_Equipment_Set__c;
                }
                // 扫出的主体还没被分配给画面上的任何一览，则跳过已分配的，给还没分配的配套做匹配
                if(esd.rec.Asset__c != null || esd.rec.AgencyTempCancel__c || esd.tempStatus == '取消') {
                    continue;
                }
                Id raesId = esd.rec.Rental_Apply_Equipment_Set__c;
                List<EsdInfo> tempList = new List<EsdInfo>();
                if(detailsMap.containsKey(raesId)) {
                    tempList = detailsMap.get(raesId);
                }
                tempList.add(esd);
                detailsMap.put(raesId, tempList);
            }
            Integer minDis = null;
            for(Id raesId: detailsMap.keySet()) {
                Integer distance = getRaesMatchingDistance(detailsMap.get(raesId), mainAsset.Fixture_Model_No_F__c, linkList) ;
                if(distance != null && (minDis == null || distance < minDis)) {
                    bestRaesId = raesId;
                    minDis = distance;
                }
            }
            if(bestRaesId == null) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '没有匹配的一览'));
            }
        }
        return bestRaesId;
    }

    /**
    @description 计算每个一览和主体所带的link的匹配程度
    @param details 一览内的明细
    @param mainModel 主体型号
    @param linkList 主体下的link
    @return 配套与link之间的差异数，null表示无穷大
    */
    private Integer getRaesMatchingDistance (List<EsdInfo> details, String mainModel, List<Fixture_OneToOne_Link__c> linkList) {
        Map<String, Integer> modelCountMap = new Map<String, Integer>();
        for(EsdInfo esd : details) {
            if(esd.rec.Is_Body__c) {
                if(mainModel != esd.tempModel) {
                    return null;
                }
            }
            else {
                Integer cnt = 0;
                if(modelCountMap.containsKey(esd.tempModel)) {
                    cnt = modelCountMap.get(esd.tempModel);
                }
                modelCountMap.put(esd.tempModel, cnt + 1);
            }
        }
        Integer distance = 0;
        for(Fixture_OneToOne_Link__c link: linkList) {
            if(modelCountMap.containsKey(link.Accessory_Asset__r.Fixture_Model_No_F__c)) {
                distance += Math.abs(intValueOf(link.In_wh_Fu_Shu_Pin_You_Xiao_Ku_Cun_F__c) - modelCountMap.get(link.Accessory_Asset__r.Fixture_Model_No_F__c));
                modelCountMap.remove(link.Accessory_Asset__r.Fixture_Model_No_F__c);
            }
            else {
                distance += intValueOf(link.In_wh_Fu_Shu_Pin_You_Xiao_Ku_Cun_F__c);
            }
        }
        for(String model: modelCountMap.keySet()) {
            distance += modelCountMap.get(model);
        }
        return distance;
    }
    /**
    @description 将一览的画面信息恢复到扫码匹配之前
    @param raesId 一览Id
    */
    private void clearRaesd(Id raesId) {
        Integer i = esdList.size()-1;
        while(i >= 0) {
            EsdInfo esd = esdList[i];
            if(esd.rec.Rental_Apply_Equipment_Set__c == raesId) {
                if(esd.rec.Id == null) {
                    esdList.remove(i);
                }
                else {
                    esd.tempLocation = '';
                    esd.tempKey = '';
                    esd.tempSerial = '';
                    esd.tempEquipmentType = '';// 备品分类 //20210510 ljh add 1672
                    esd.tempOldRaesIdSub = null; //20210520 ljh add 1829
                    esd.SubChecked = false; //20210520 ljh add 1829
                    esd.tempFixtureSet = null; //20210520 ljh add 1829
                    esd.tempStatus  = ''; //20210520 ljh add 1829
                    esd.tempDetailStatus = esd.rec.RAESD_Status__c;
                    esd.rec.Asset__c = null;
                    esd.rec.Select_Time__c = null;
                }
                if(esd.rec.Is_Body__c) {
                    break;
                }
            }
            i--;
        }
    }
    //20210519 ljh add 1829
    /*
    //验证是否可分配
    可分配代替品前提1 -- 备品借出申请的状态：“已批准”到“已出库指示”
    可分配代替品前提2 -- 所选借出备品配套一览的状态：‘已批准’到‘出库前已检测’
    代替品不可 Irreplaceable_flag__c
    */
    public Boolean IsCanSubReas(Id raesId){
        List<Rental_Apply_Equipment_Set__c> IsCanSubList = getReas(true,raesId);
        if(IsCanSubList.size() != 1){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '数据有误，不能继续操作了'));
            return false;
        }else if(IsCanSubList[0].Rental_Apply__r.Status__c != '已批准' && IsCanSubList[0].Rental_Apply__r.Status__c!= '已出库指示'){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '申请书状态不符合分配代替品条件，请确认申请的状态'));
            return false;    
        }else if(IsCanSubList[0].RAES_Status__c == '草案中' || IsCanSubList[0].RAES_Status__c == '申请中' || IsCanSubList[0].Shippment_loaner_time2__c != null){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '一览的状态不符合分配替代品条件'));
            return false;
        }else if(IsCanSubList[0].Irreplaceable_flag__c){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '申请人勾选了代替品不可'));
            return false;
        }
        return true;
    }
    //20210519 ljh add 1829
    // 扫一扫按钮
    public void scanAndMatch() {
        done_flg = false;
        Boolean IsSub = false; //是否是分配替代 //20210513 ljh add 1829
        Id OldRaesId;
        if(String.isBlank(qrcode)) {
            return ;
        }
        //20210513 ljh add 1829 start
        else{
            //system.debug('qrcode'+qrcode);
            //qrcode+';'+scanType
            //scanType = 2;{!esdInfo.rec.Rental_Apply_Equipment_Set__c}
            if(qrcode.contains(';')){
                //两行代码不可换顺序
                IsSub = Integer.valueOf(qrcode.split(';')[1]) == 2?true:false;
                OldRaesId = qrcode.split(';')[2];
                qrcode = qrcode.split(';')[0];   
            }
        }
        if(IsSub){
           //验证是否可以【分配替代品】
            if(!IsCanSubReas(OldRaesId)) return;
        }
        //20210513 ljh add 1829 end
        Savepoint sp = Database.setSavepoint();

        try {
            Datetime now = System.now();
            //system.debug('qrcode:'+qrcode+'===bieBeiPinFenLeiList'+bieBeiPinFenLeiList);
            List<Asset> mainAssetList = [
                SELECT Id
                     , Fixture_Model_No_F__c
                     , Internal_asset_location__c
                     , SerialNumber
                     , Salesdepartment__c
                     , SalesProvince__c
                     , Product_category__c
                     , Equipment_Type__c
                     , Internal_Asset_number_key__c
                  FROM Asset
                 WHERE Fixture_QRCode__c =: qrcode
                   //AND Main_OneToOne__c = true //20210508 ljh add 1834
                   AND You_Xiao_Ku_Cun__c > 0
                 LIMIT 1
            ];

            //system.debug('+mainAssetList:'+mainAssetList);
            if(mainAssetList.isEmpty()) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '保有设备不存在或已被分配'));
                return;
            }else if(bieBeiPinFenLeiList.size()>0 && !bieBeiPinFenLeiList.contains(mainAssetList[0].Equipment_Type__c)){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '分配备品的备品分类与借用目的不符'));
                return;
            }
            Asset mainAsset = mainAssetList[0];
            List<Fixture_OneToOne_Link__c> linkList = [
                SELECT Id
                     , Accessory_Asset__c
                     , Accessory_Asset__r.Fixture_Model_No_F__c
                     , Accessory_Asset__r.Internal_asset_location__c
                     , Accessory_Asset__r.SerialNumber
                     , Accessory_Asset__r.Equipment_Type__c // 备品分类 //20210510 ljh add 1672
                     , Accessory_Asset__r.Internal_Asset_number_key__c
                     , Accessory_Asset__r.Loaner_accsessary__c //20210519 ljh add 1829
                     , Main_Asset__c
                     , Main_Asset__r.Fixture_Model_No_F__c
                     , Main_Asset__r.Internal_asset_location__c
                     , Main_Asset__r.SerialNumber
                     , In_wh_Fu_Shu_Pin_You_Xiao_Ku_Cun_F__c
                     , Select_Accessory_Asset_Cnt__c
                  FROM Fixture_OneToOne_Link__c
                 WHERE Main_Asset__c=:mainAsset.Id
            ];


            //20210513 ljh add 1829 start
            Map<String,Fixture_OneToOne_Link__c> linkMap = new Map<String,Fixture_OneToOne_Link__c>();
            for(Fixture_OneToOne_Link__c link:linkList) {
                linkMap.put(link.Accessory_Asset__r.Fixture_Model_No_F__c, link);
            }
            Map<String, Fixture_Set_Detail__c> fsdModelMap;
            //分配替代品
            if(IsSub){ 
                //根据型号找到标准配套
                List<Fixture_Set__c> fsList = [
                    SELECT Id
                         // , Name
                         , Fixture_Set_Body_Model_No__c
                    FROM Fixture_Set__c
                    WHERE Fixture_Set_Body_Model_No__c=:mainAsset.Fixture_Model_No_F__c 
                    LIMIT 1
                ];
                if(fsList.isEmpty()) {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '保有设备的标准配套不存在'));
                    return;
                }
                if(OldRaesId == null) {
                    return;
                }
                // 标准配套明细
                fsdModelMap = getFsdModelMap(fsList[0].Id);

                //报错： 1.备品一对一 比标准配套多 2.link里可分配的数量比标准配套多
                for(Fixture_OneToOne_Link__c link: linkList) {
                    Integer cnt = intValueOf(link.In_wh_Fu_Shu_Pin_You_Xiao_Ku_Cun_F__c); // link里可分配的数量
                    if(!fsdModelMap.containsKey(link.Accessory_Asset__r.Fixture_Model_No_F__c)) {
                        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, link.Accessory_Asset__r.Fixture_Model_No_F__c + '没有相应的配套明细，请添加后重试！'));
                        clearRaesd(OldRaesId);
                        return;
                    }else{
                        Integer cntFs = Integer.valueOf(fsdModelMap.get(link.Accessory_Asset__r.Fixture_Model_No_F__c).Quantity__c);
                        if(cnt>cntFs){
                            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, link.Accessory_Asset__r.Fixture_Model_No_F__c + '实物附属品多于标准配套，请确认后再分配。'));
                            clearRaesd(OldRaesId);
                            return;
                        }
                    } 
                }
                //页面显示  原来的申请取消 新的显示出来 
                // 恢复到未分配
                clearRaesd(OldRaesId);
                Integer newRaesIndex = 0; // 要替代的保有设备 + 1
                //Date mainDate = null;
                for(Integer i = 0; i < esdList.size(); i++) {
                    //重新替代分配
                    if(esdList[i].tempOldRaesIdSub == OldRaesId){
                        esdList.remove(i--);
                    }
                }
                for(Integer i = 0; i < esdList.size(); i++) {
                    EsdInfo esd1 = esdList[i];
                    if( esd1.rec.Rental_Apply_Equipment_Set__c == OldRaesId) {
                        if(esd1.rec.Fixture_Model_No__c == mainAsset.Fixture_Model_No_F__c){
                            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '分配代替品不能选择当前配套'));
                            return;
                        }
                        newRaesIndex = i;
                        esd1.tempStatus = '取消';
                        esd1.tempDetailStatus = '取消';
                        if(!esd1.rec.Is_Body__c){
                            esd1.tempDate =  null;
                        }
                        esd1.SubChecked = true;
                    }
                }
                List<Fixture_Set_Detail__c> fsdList = (List<Fixture_Set_Detail__c>)fsdModelMap.values();
                // 遍历配套明细
                for(Fixture_Set_Detail__c fsd: fsdList) {
                    Integer index = 1;
                    // 20210707 ljh update
                    // Integer cnt = -1;
                    Integer cnt = 0;
                    Integer quantity = Integer.valueOf(fsd.Quantity__c);
                    Integer cntfs = quantity;
                    Boolean inLink = linkMap.containsKey(fsd.Fixture_Model_No_F__c);
                    Fixture_OneToOne_Link__c link;
                    if(inLink){
                        link = linkMap.get(fsd.Fixture_Model_No_F__c);
                        cnt = intValueOf(link.In_wh_Fu_Shu_Pin_You_Xiao_Ku_Cun_F__c); // link里可分配的数量 
                    }
                    while(quantity > 0) {
                        Rental_Apply_Equipment_Set_Detail__c raesd = new Rental_Apply_Equipment_Set_Detail__c();
                        raesd.Asset__c = fsd.Is_Body__c?mainAsset.Id:(inLink?link.Accessory_Asset__c:null);
                        if(!fsd.Is_Body__c && inLink){
                            raesd.Fixture_OneToOne_Link_Id__c = link.Id;
                        }
                        raesd.FSD_Is_OneToOne__c = fsd.Is_OneToOne__c; //主体这个false ***
                        raesd.Rental_Apply__c = parentObj.Id;
                        //raesd1.Rental_Apply_Equipment_Set__c = raesId;
                        raesd.Is_Body__c = fsd.Is_Body__c;
                        if(fsd.Is_Body__c){
                            raesd.Loaner_accsessary__c = false; 
                        }else if(inLink){
                            raesd.Loaner_accsessary__c = link.Accessory_Asset__r.Loaner_accsessary__c; 
                        }
                        raesd.IndexFromUniqueKey__c = index++;
                        raesd.AgencyAssignAdd__c = false; //办事处追加
                        raesd.Fixture_Set_Detail__c = fsd.Id;
                        raesd.IndexFromUniqueKey_Text__c = fsd.SortInt_F__c;

                        EsdInfo esd = new EsdInfo(raesd);
                        esd.tempLocation = fsd.Is_Body__c?mainAsset.Internal_asset_location__c: (inLink?link.Accessory_Asset__r.Internal_asset_location__c:'');
                        esd.tempModel = fsd.Is_Body__c?mainAsset.Fixture_Model_No_F__c:(inLink?link.Accessory_Asset__r.Fixture_Model_No_F__c:fsd.Fixture_Model_No_F__c);
                        esd.tempKey = fsd.Is_Body__c?mainAsset.Internal_Asset_number_key__c:(inLink?link.Accessory_Asset__r.Internal_Asset_number_key__c:'');
                        esd.tempSerial = fsd.Is_Body__c?mainAsset.SerialNumber:(inLink?link.Accessory_Asset__r.SerialNumber:'');
                        esd.tempEquipmentType = fsd.Is_Body__c?mainAsset.Equipment_Type__c:(inLink?link.Accessory_Asset__r.Equipment_Type__c:'');// 备品分类 //20210510 ljh add 1672
                        esd.tempDetailStatus = '已分配';
                        esd.tempStatus = '已分配';
                        esd.tempOldRaesIdSub = OldRaesId;
                        esd.tempFixtureSet = fsd.Fixture_Set__c;
                        esd.editable = false;
                        // 20210707 ljh update
                        // if((cntfs-quantity > cnt) && !fsd.Is_Body__c){
                        if((cntfs-quantity >= cnt) && !fsd.Is_Body__c){
                            //一对一中没有的或者一对一数量小于标准配套数量 
                            esd.tempStatus = '取消';
                            esd.tempDetailStatus = '取消'; 
                            raesd.Fixture_OneToOne_Link_Id__c = null;
                            raesd.Asset__c = null;
                            raesd.AgencyAssignAdd__c = true; //办事处追加
                        }
                        newRaesIndex++; // 新的一览插入的位置 
                        if(newRaesIndex < esdList.size()) {
                            esdList.add(newRaesIndex,esd);
                        }else {
                            esdList.add(esd);
                        }
                        quantity--;
                    }                  
                }
            }
            //20210513 ljh add 1829 end
            else{
                Id raesId = getBestRaesId(mainAsset, linkList); // 一次只给一个还没分配的一览分配
                if(raesId == null) {
                    return;
                } 
                // 恢复到未分配
                clearRaesd(raesId);
                //20210520 ljh add 1829 start
                for(Integer i = 0; i < esdList.size(); i++) {
                    //重新替代分配
                    if(esdList[i].tempOldRaesIdSub == raesId){
                        esdList.remove(i--);
                    }
                }
                //20210520 ljh add 1829 end
                Id fsId = null;
                List<EsdInfo> esdListOneSet = new List<EsdInfo>();
                Integer lastIndex = 0; // 一览中最后一条明细的下标 + 1
                Date mainDate = null;
                for(Integer i = 0; i < esdList.size(); i++) {
                    EsdInfo esd = esdList[i];
                    if( esd.rec.Rental_Apply_Equipment_Set__c == raesId) {
                        esdListOneSet.add(esd);
                        lastIndex = i;
                        if(esd.rec.Is_Body__c) {
                            fsId = esd.rec.Fixture_Set_Id__c;
                            // 分配主体
                            esd.rec.Asset__c = mainAsset.Id;
                            esd.rec.AgencyTempCancel__c = false;
                            esd.rec.AgencyTempCancelTime__c = null;
                            esd.rec.IndexFromUniqueKey__c = 1;
                            // 画面显示用
                            esd.tempLocation = mainAsset.Internal_asset_location__c;
                            esd.tempKey = mainAsset.Internal_Asset_number_key__c;
                            esd.tempSerial = mainAsset.SerialNumber;
                            esd.tempEquipmentType = mainAsset.Equipment_Type__c;// 备品分类 //20210510 ljh add 1672;
                            esd.tempStatus = '已分配';
                            esd.tempDetailStatus = '已分配';
                            mainDate = esd.rec.Rental_Apply_Equipment_Set__r.Rental_Start_Date__c;
                        }
                    }
                }
                lastIndex++; // 一览最后明细下标 + 1

                // 配套明细
                //Map<String, Fixture_Set_Detail__c> fsdModelMap = getFsdModelMap(fsId); //20210521 ljh update 1829
                fsdModelMap = getFsdModelMap(fsId);
                // 按link去匹配明细
                for(Fixture_OneToOne_Link__c link: linkList) {
                    Boolean isMatch = false;
                    Integer cnt = intValueOf(link.In_wh_Fu_Shu_Pin_You_Xiao_Ku_Cun_F__c); // link里可分配的数量
                    Integer cntFs = 1;
                    Integer index = 1;
                    //20210521 ljh add 1829 start
                    if(!fsdModelMap.containsKey(link.Accessory_Asset__r.Fixture_Model_No_F__c)) {
                        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, link.Accessory_Asset__r.Fixture_Model_No_F__c + '没有相应的配套明细，请添加后重试！'));
                        clearRaesd(raesId);
                        return;
                    }else{
                        cntFs = Integer.valueOf(fsdModelMap.get(link.Accessory_Asset__r.Fixture_Model_No_F__c).Quantity__c);
                        if(cnt>cntFs){
                            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, link.Accessory_Asset__r.Fixture_Model_No_F__c + '实物附属品多于标准配套，请确认后再分配。'));
                            clearRaesd(raesId);
                            return;
                        }
                    }
                    //20210521 ljh add 1829 end
                    for(EsdInfo esd: esdListOneSet) {
                        if(esd.rec.Is_Body__c) {
                            continue;
                        }
                        if(link.Accessory_Asset__r.Fixture_Model_No_F__c == esd.tempModel && cnt > 0) {
                            cnt--;
                            index++;
                            // 明细分配
                            esd.rec.Asset__c = link.Accessory_Asset__c;
                            esd.rec.Fixture_OneToOne_Link_Id__c = link.Id;
                            esd.rec.FSD_Is_OneToOne__c = true;
                            esd.rec.AgencyTempCancel__c = false;
                            esd.rec.AgencyTempCancelTime__c = null;

                            // 画面显示
                            esd.tempLocation = link.Accessory_Asset__r.Internal_asset_location__c;
                            esd.tempKey = link.Accessory_Asset__r.Internal_Asset_number_key__c;
                            esd.tempSerial = link.Accessory_Asset__r.SerialNumber;
                            esd.tempEquipmentType = link.Accessory_Asset__r.Equipment_Type__c;// 备品分类 //20210510 ljh add 1672
                            if(esd.tempStatus != '追加') {
                                esd.tempStatus = '已分配';
                            }
                            esd.tempDetailStatus = '已分配';
                            esd.tempDate = mainDate;
                            isMatch = true;
                        }
                    }
                    // 有link但没有明细，或link里的数量超过借出明细数，追加明细（没有超过标准配套）
                    if(!isMatch || cnt > 0) {
                        while(cnt > 0) {
                            Rental_Apply_Equipment_Set_Detail__c raesd = new Rental_Apply_Equipment_Set_Detail__c();
                            raesd.Asset__c = link.Accessory_Asset__c;
                            raesd.Fixture_OneToOne_Link_Id__c = link.Id;
                            raesd.FSD_Is_OneToOne__c = true;
                            raesd.Rental_Apply__c = parentObj.Id;
                            raesd.Rental_Apply_Equipment_Set__c = raesId;
                            raesd.Is_Body__c = false;
                            raesd.IndexFromUniqueKey__c = index++;
                            raesd.AgencyAssignAdd__c = true;
                            if(fsdModelMap.containsKey(link.Accessory_Asset__r.Fixture_Model_No_F__c)) {
                                Fixture_Set_Detail__c fsd = fsdModelMap.get(link.Accessory_Asset__r.Fixture_Model_No_F__c);
                                raesd.Fixture_Set_Detail__c = fsd.Id;
                                raesd.IndexFromUniqueKey_Text__c = fsd.SortInt_F__c;
                            }
                            //20210521 ljh update 1829 start
                            // else {
                            //     ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, link.Accessory_Asset__r.Fixture_Model_No_F__c + '没有相应的配套明细，请添加后重试！'));
                            //     clearRaesd(raesId);
                            //     return;
                            // }
                            //20210521 ljh update 1829 end
                            EsdInfo esd = new EsdInfo(raesd);
                            esd.tempStatus = '追加';
                            esd.tempLocation = link.Accessory_Asset__r.Internal_asset_location__c;
                            esd.tempModel = link.Accessory_Asset__r.Fixture_Model_No_F__c;
                            esd.tempKey = link.Accessory_Asset__r.Internal_Asset_number_key__c;
                            esd.tempSerial = link.Accessory_Asset__r.SerialNumber;
                            esd.tempEquipmentType = link.Accessory_Asset__r.Equipment_Type__c;// 备品分类 //20210510 ljh add 1672
                            esd.tempDetailStatus = '已分配';
                            esd.tempDate = mainDate;
                            if(lastIndex < esdList.size()) {
                                esdList.add(lastIndex++, esd);
                            }
                            else {
                                esdList.add(esd);
                            }
                            cnt--;
                        }
                    }
                }
                // 没有被分配的明细，取消
                for(EsdInfo esd: esdListOneSet) {
                    if(esd.rec.Asset__c == null) {
                        esd.tempStatus = '取消';
                        esd.tempDetailStatus = '取消';
                        esd.tempDate = null;
                    }
                }
            }
        }
        catch (Exception ex) {
            system.debug('=====' + ex.getMessage());
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage()));
            Database.rollback(sp);
        }
    }
    private Map<String, Fixture_Set_Detail__c> getFsdModelMap(Id fsId) {
        List<Fixture_Set_Detail__c> fsdList = [
            SELECT Id
                 , Fixture_Model_No_F__c
                 , Quantity__c //20210518 ljh 1829 add
                 , Is_Body__c //20210521 ljh 1829 add
                 , Is_OneToOne__c  //20210521 ljh 1829 add
                 , Fixture_Set__c //20210521 ljh 1829 add
                 , SortInt_F__c
            FROM Fixture_Set_Detail__c
            WHERE Fixture_Set__c=:fsId
            ORDER BY SortInt_F__c // 20211018 ljh add 防止默认查询不按照顺序
        ];
        Map<String, Fixture_Set_Detail__c> fsdModelMap = new Map<String, Fixture_Set_Detail__c>();
        for(Fixture_Set_Detail__c fsd:fsdList) {
            fsdModelMap.put(fsd.Fixture_Model_No_F__c, fsd);
        }
        return fsdModelMap;
    }
    private Integer intValueOf(Object obj){
        if(obj == null){
            return 0;
        }
        return Integer.valueOf((Decimal) obj);
    }

    /**
    @decription 下架按钮
    */
    // public void stockDown() {
    //     done_flg = false;
    //     if(!isRaStatusOK()) {
    //         return;
    //     }
    //     Map<Id, Rental_Apply_Equipment_Set_Detail__c> raesdMap = getDetailsMap();
    //     List<Rental_Apply_Equipment_Set_Detail__c> updateRaesdList = new List<Rental_Apply_Equipment_Set_Detail__c>();
    //     Set<Id> raesIdSet = new Set<Id>();
    //     Datetime now = System.now();
    //     Id userId =  Userinfo.getUserId();
    //     Boolean hasChecked = false;
    //     for (EsdInfo esd : esdList) {
    //         if(!raesdMap.containsKey(esd.rec.Id)) {
    //             ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, esd.tempModel + '不存在或追加后未保存，请刷新画面重试！')) ;
    //             return;
    //         }
    //         Rental_Apply_Equipment_Set_Detail__c raesd = raesdMap.get(esd.rec.Id);
    //         if(esd.checked || raesIdSet.contains(esd.rec.Rental_Apply_Equipment_Set__c)) {
    //             if(esd.rec.AgencyTempCancel__c) {continue;}
    //             hasChecked = true;
    //             if(raesd.LastModifiedDate != esd.rec.LastModifiedDate) {
    //                 ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, raesd.Fixture_Model_No__c + '后台数据被' + raesd.LastModifiedBy.Name + '修改，请刷新画面！'));
    //                 return;
    //             }
    //             if(esd.rec.Asset__c == null) {
    //                 ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,esd.tempModel + '未分配不可下架！'));
    //                 return;
    //             }
    //             else if(raesd.Asset__c == null) {
    //                 ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,esd.tempModel + '请保存分配结果后重试！'));
    //                 return;
    //             }
    //             else if(!raesd.StockDown__c) {
    //                 raesd.StockDown__c = true;
    //                 raesd.StockDown_time__c = now;
    //                 raesd.StockDown_staff__c = userId;
    //                 raesd.Shipment_request_time2__c = now;
    //                 raesd.Shipment_request__c = true;
    //                 updateRaesdList.add(raesd);
    //             }
    //             if(esd.rec.Is_Body__c) {
    //                 raesIdSet.add(esd.rec.Rental_Apply_Equipment_Set__c);
    //             }
    //         }
    //     }
    //     if(!hasChecked) {
    //         ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '未选择下架的一览！'));
    //         return;
    //     }
    //     Savepoint sp = Database.setSavepoint();
    //     try {
    //         if(!updateRaesdList.isEmpty()) {
    //             //print('更新明细', updateRaesdList);
    //             FixtureUtil.withoutUpdate(updateRaesdList);
    //             // 只要有下架就设为出库指示
    //             if(parentObj.Status__c!='已出库指示') {
    //                 Rental_Apply__c ra = new Rental_Apply__c(Id = parentObj.Id, Status__c='已出库指示');
    //                 FixtureUtil.withoutUpdate(new List<Rental_Apply__c> {ra});
    //             }
    //             init();
    //             done_flg = true;
    //         }
    //     }
    //     catch (Exception ex) {
    //         system.debug('=====' + ex.getMessage());
    //         ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage()));
    //         Database.rollback(sp);
    //         done_flg = false;
    //     }
    // }
    /**
    @description 发货按钮，切换发货单信息是否可编辑
    */
    public void shipment() {
        done_flg = false;
        if(!isRaStatusOK()) {
            return;
        }

        Id userId =  Userinfo.getUserId(); // 20210624 ljh add SFDC-C448GR
        Datetime now = System.now();
        if(isSameCity) {
            slip.Name = parentObj.Name + '_Dummy_SameCity';
            slip.DeliveryCompany__c = '其他';
            slip.Distributor_method__c = '其他';
            slip.Shippment_loaner_time__c = now;
        }
        Boolean insertSlip = (slip.Id == null);
        Map<Id, Rental_Apply_Equipment_Set_Detail__c> raesdMap = getDetailsMap();
        Savepoint sp = Database.setSavepoint();
        try {
            Set<Id> raesIdSet = new Set<Id>();
            List<Id> mainIdList = new List<Id>();
            List<Rental_Apply_Equipment_Set_Detail__c> updateRaesdList = new List<Rental_Apply_Equipment_Set_Detail__c>();
            if(esdList.isEmpty()) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '没有明细，不能发货!'));
                return;
            }
            Map<Datetime, List<Rental_Apply_Equipment_Set_Detail__c>> approvalMap = new Map<Datetime, List<Rental_Apply_Equipment_Set_Detail__c>>();// 20220309 ljh SFDC-CC6CLJ phase5上线课题131 提交申请到备品出库时长
            for(EsdInfo esd:esdList) {
                if(!raesdMap.containsKey(esd.rec.Id)) {
                    continue;
                }
                Rental_Apply_Equipment_Set_Detail__c raesd = raesdMap.get(esd.rec.Id);
                if(esd.checked || raesIdSet.contains(esd.rec.Rental_Apply_Equipment_Set__c)) {
                    if(raesd.Is_Body__c) {
                        mainIdList.add(raesd.Asset__c);
                        raesIdSet.add(esd.rec.Rental_Apply_Equipment_Set__c);

                        // add lc 20220927 SFDC-CJ48VE 备品预计出库日逻辑调整 start
                        // 备品预计出库日应该等于今天，否则不能发货
                        if( esd.rec.Rental_Apply_Equipment_Set__r.Rental_Start_Date__c != Date.today() ){
                            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '备品预计出货日应该等于今天，否则不能发货!'));
                            return;
                        }
                        // add lc 20220927 SFDC-CJ48VE 备品预计出库日逻辑调整 end
                    }

                    // 分配时临时取消的在发货后彻底取消
                    if(raesd.AgencyTempCancel__c) {
                        raesd.Cancel_Select__c = true;
                        raesd.Cancel_Reason__c = '被动取消';
                        raesd.Loaner_cancel_Remarks__c = '该主体下没有可对应此型号的库存';
                        updateRaesdList.add(raesd);
                        continue;
                    }
                    if(raesd.LastModifiedDate != esd.rec.LastModifiedDate) {
                        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, raesd.Fixture_Model_No__c + '后台数据被' + raesd.LastModifiedBy.Name + '修改，请刷新画面！'));
                        return;
                    }
                    // 20210624 ljh update SFDC-C448GR
                    // if(esd.rec.Select_Time__c == null) {
                    if(esd.rec.Asset__c == null) {
                        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,esd.tempModel + '未分配不可发货！'));
                        return;
                    }
                    // 20210624 ljh update SFDC-C448GR
                    // else if(raesd.Select_Time__c == null) {
                    else if(raesd.Asset__c == null) {
                        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,esd.tempModel + '请保存分配结果后重试！'));
                        return;
                    }
                    // 20210624 ljh update SFDC-C448GR start
                    // else if(!raesd.StockDown__c) {
                    //     ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,esd.tempModel + '未下架不可发货！'));
                    //     return;
                    // }
                    // 20210624 ljh update SFDC-C448GR end
                    else if(raesd.Shippment_loaner_time__c != null) {
                        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,esd.tempModel + '已发货，请刷新画面！'));
                        return;
                    }
                    // 20210624 ljh update SFDC-C448GR start
                    else if(!raesd.StockDown__c) {
                        raesd.StockDown__c = true;
                        raesd.StockDown_time__c = now;
                        // raesd.StockDown_staff__c = userId;//20210728 1719
                        raesd.Shipment_request_time2__c = now;
                        raesd.Shipment_request__c = true;
                    }
                    // 20210624 ljh update SFDC-C448GR end
                    raesd.Inspection_result__c = 'OK';
                    // 发货前检测时间和检测人在trigger里设
                    raesd.Shippment_loaner_time__c = now;
                    // 20220309 ljh SFDC-CC6CLJ phase5上线课题131 提交申请到备品出库时长 start
                    Datetime keyDt = raesd.Add_Request_approval_time__c != null?raesd.Add_Request_approval_time__c:raesd.Rental_Apply__r.Request_approval_time__c;
                    List<Rental_Apply_Equipment_Set_Detail__c> tempRaesdL;
                    if(approvalMap.containsKey(keyDt)){
                        tempRaesdL = approvalMap.get(keyDt);
                    }else{
                        tempRaesdL = new List<Rental_Apply_Equipment_Set_Detail__c>();
                    }
                    tempRaesdL.add(raesd);                        
                    approvalMap.put(keyDt,tempRaesdL);
                    // 20220309 ljh SFDC-CC6CLJ phase5上线课题131 提交申请到备品出库时长 end  
                    updateRaesdList.add(raesd);
                }
                else {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '必须全部勾选发货'));
                    return;
                }
            }

            if(String.isBlank(parentObj.Delivery_Agency__c)){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '发货-办事处为空,不能发货'));
                return;
            }
            Id addressId;
            List<Shipment_address__c> shipmentAddressList = [SELECT Id,Name FROM Shipment_address__c WHERE Name =: parentObj.Delivery_Agency__c];
            if(shipmentAddressList.size() > 0){
                addressId = shipmentAddressList[0].Id;
            }
            else {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '该办事处【办事处地址】无值，请确认！'));
                return;
            }
            if(String.isBlank(slip.Name)
                || String.isBlank(slip.DeliveryCompany__c)
                || String.isBlank(slip.Distributor_method__c)
                || String.isBlank(slip.Wh_Staff__c)) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '发货物流信息必填！'));
                return;
            }
            //20201209 ljh update end
            // 删除link
            if(!mainIdList.isEmpty()) {
                Oly_TriggerHandler.bypass(AssetHandlerCheck.class.getName());
                FixtureUtil.delOtOLinkData(mainIdList);
                Oly_TriggerHandler.clearBypass(AssetHandlerCheck.class.getName());
            }
            if(!updateRaesdList.isEmpty()) {
                slip.Shippment_loaner_time__c = now;
                FixtureUtil.withoutUpsertObjects(new List<FixtureDeliverySlip__c> {slip});
                // 20220309 ljh SFDC-CC6CLJ phase5上线课题131 提交申请到备品出库时长 start
                map<String,Decimal> ApplyToShipmentMap = new map<String,Decimal>();
                if(approvalMap.size() > 0 ){
                    // dtList[0] 第一个就是最小时间
                    List<Datetime> dtList = new List<Datetime>(approvalMap.keySet());
                    Date startDateSOQL  = date.newinstance(dtList[0].year(), dtList[0].month(), dtList[0].day());
                    List<OlympusCalendar__c> ocList = [SELECT Id, Date__c,IsWorkDay__c 
                                     FROM OlympusCalendar__c
                                    WHERE Date__c >= :startDateSOQL
                                      AND Date__c <= :Date.today()
                                    ORDER BY Date__c ASC];
                    Map<Date,String> ocMap = new Map<Date,String>();
                    for(OlympusCalendar__c oc:ocList){
                        String IsWorkDay = oc.IsWorkDay__c.format();
                        ocMap.put(oc.Date__c,IsWorkDay);
                    }
                    for(Datetime dt:dtList){
                        Boolean startFlag = false;
                        Boolean endFlag = false;
                        Datetime startTime = dt;
                        Date startDate = Date.newInstance(startTime.year(),startTime.month(),startTime.day());
                        Datetime endTime = Datetime.now();
                        Date endDate = Date.today();
                        // 审批时间是非奥林巴斯工作日  
                        // if(ocList[0].IsWorkDay__c == 0){
                        if(ocMap.get(startDate) == '0'){
                            for(OlympusCalendar__c oc:ocList){
                                if(startDate < oc.Date__c && oc.IsWorkDay__c == 1){
                                    startTime = Datetime.newInstance(oc.Date__c.year(),oc.Date__c.month(),oc.Date__c.day(),0,0,0);
                                    startDate = oc.Date__c;
                                    startFlag = true;
                                    break;
                                }
                            }
                        }
                        // 发货时间是非奥林巴斯工作日
                        if(ocList[ocList.size() - 1].IsWorkDay__c == 0){
                            for(Integer i = ocList.size() - 1; i >= 0;i--){
                                if(ocList[i].IsWorkDay__c == 1){
                                    endTime = Datetime.newInstance(ocList[i].Date__c.addDays(1).year(),ocList[i].Date__c.addDays(1).month(),ocList[i].Date__c.addDays(1).day(),0,0,0);
                                    endDate = ocList[i].Date__c.addDays(1);
                                    endFlag = true;
                                    break;
                                }
                            }
                        }
                        Decimal timeDifLast;
                        if(ocList[0].IsWorkDay__c == 0 && ocList[ocList.size() - 1].IsWorkDay__c == 0 && !startFlag && !endFlag){
                            timeDifLast = 0;
                        }else{
                            Long startL = startTime.getTime();
                            Long tendL = endTime.getTime();
                            Long timeDif = tendL - startL;                            
                            Decimal time11 = timeDif*1.00;
                            Decimal time12 = 24*3600*1000*1.00;
                            timeDifLast = time11/time12;                            
                            Integer tempWeek = 0;
                            for(OlympusCalendar__c oc:ocList){
                                if(oc.IsWorkDay__c == 0 && startDate < oc.Date__c && oc.Date__c < endDate){
                                    tempWeek++;
                                }
                            }
                            timeDifLast = timeDifLast - tempWeek;
                        }
                        // dtestLast 四舍五入 保留1位小数
                        for(Rental_Apply_Equipment_Set_Detail__c raesd00:approvalMap.get(dt)){
                            ApplyToShipmentMap.put(raesd00.Id,timeDifLast.setScale(1));
                        }
                    }
                }
                // 20220309 ljh SFDC-CC6CLJ phase5上线课题131 提交申请到备品出库时长 end 
                // 明细和申请连到发货单上
                for(Rental_Apply_Equipment_Set_Detail__c raesd: updateRaesdList) {
                    if(!raesd.Cancel_Select__c) {
                        raesd.DeliverySlip__c = slip.Id;
                    }
                    // 20220315 ljh SFDC-CC6CLJ phase5上线课题131 提交申请到备品出库时长 start
                    if(ApplyToShipmentMap.containsKey(raesd.Id)){
                        raesd.ApplyToShipmentWorkTime__c = ApplyToShipmentMap.get(raesd.Id);
                    }
                    // 20220315 ljh SFDC-CC6CLJ phase5上线课题131 提交申请到备品出库时长 end
                }
                FixtureUtil.withoutUpdate(updateRaesdList);
                // 20210624 ljh update SFDC-C448GR start
                // Rental_Apply__c ra = new Rental_Apply__c(Id=parentObj.Id, DeliverySlip__c = slip.Id, Delivery_Agency__c = parentObj.Delivery_Agency__c, Agency_Address_Id__c = addressId );
                Rental_Apply__c ra = new Rental_Apply__c();
                ra.Id = parentObj.Id;
                if(parentObj.Status__c!='已出库指示') {
                    ra.Status__c = '已出库指示';
                }
                ra.DeliverySlip__c = slip.Id;
                ra.Delivery_Agency__c = parentObj.Delivery_Agency__c; 
                ra.Agency_Address_Id__c = addressId;
                // 20210624 ljh update SFDC-C448GR end

                //20220217 sx add 备品借出申请-决裁控制 No.4 出库成功时，把此时点的决裁编号和决裁状态写到决裁编号（出库）和决裁状态（出库）上
                if (String.isNotBlank(parentObj.Campaign__c) && parentObj.Campaign__r.IF_Approved__c){
                    // ra.ApprovedNo_Delivery__c = parentObj.Campaign__r.Meeting_Approved_No__r.MeetingApprovedNo__c;
                    // ra.Approved_State_Delivery__c = parentObj.Campaign__r.Meeting_Approved_No__r.ProcessState__c;
                    ra.ApprovedNo_Delivery__c = parentObj.Campaign__r.Meeting_Approved_No__r.Name;
                    ra.Approved_State_Delivery__c = parentObj.Campaign__r.Approved_Status__c;
                }
                FixtureUtil.withoutUpdate(new List<Rental_Apply__c> {ra});
            }
            // 同城时自动收货
            if(isSameCity && !raesIdSet.isEmpty()) {
                List<Rental_Apply_Equipment_Set__c> raesList = new List<Rental_Apply_Equipment_Set__c>();
                Date rentalEndDate = setRentalEndDate(Date.today(), parentObj);
                for(Id raesId:raesIdSet) {
                    raesList.add(new Rental_Apply_Equipment_Set__c(Id=raesId, Received_Confirm__c = 'OK', Rental_Start_Date__c = Date.today(), Rental_End_Date__c = rentalEndDate));
                }
                FixtureUtil.withoutUpdate(raesList);
            }
            init();
            done_flg = true;
        }
        catch (Exception ex) {
            system.debug('=====' + ex.getMessage());
            // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getDmlMessage(0)));
            ApexPages.addMessages(ex);
            Database.rollback(sp);
            // 运输单插入成功，但明细或申请更新失败时，运输单的假Id要清掉
            if(insertSlip) {
                slip.Id = null;
            }
            done_flg = false;
        }
    }

    public Date setRentalEndDate(Date startDate, Rental_Apply__c rentalApplyObj) {
        Date endDate = null;
        switch on rentalApplyObj.demo_purpose2__c{
            when '试用（无询价）','试用（有询价）','新产品评价','其他','协议借用' {
                endDate = startDate + intValueOf(rentalApplyObj.Hope_Lonaer_date_Num__c);
            }
            when '一般用户','保修用户','市场多年保修','再修理','索赔QIS','已购待货','故障排查' {
                endDate = startDate + 30;
            }
            when '学会展会' {
                endDate = rentalApplyObj.Campaign_EndDate_F__c + 5;
            }
        }

        return endDate;
    }
    

    public class EsdInfo {
        public Rental_Apply_Equipment_Set_Detail__c rec { get; set; }
        public Boolean checked {get;set;}
        public boolean editable { get; set; }
        public boolean IsCanSub { get; set; } //20210519 ljh add 1829
        public boolean SubChecked { get; set; } //20210519 ljh add 1829
        public String tempStatus {get;set;} // 已分配/取消/追加
        public Date tempDate {get;set;} //出货日
        public String tempLocation {get;set;} // 存放地
        public String tempSerial {get;set;} // 机身编号
        public String tempKey {get;set;} // 固定资产编号Key
        public String tempEquipmentType {get;set;} // 备品分类 //20210510 ljh add 1672
        public String tempDetailStatus {get;set;}  
        public String tempModel {get;set;}
        public ID tempOldRaesIdSub {get;set;} //20210518 ljh add 1829 
        public ID tempFixtureSet {get;set;} //20210519 ljh add 1829
        

        public EsdInfo(Rental_Apply_Equipment_Set_Detail__c rec) {
            this.rec = rec;
            this.checked = false;
            this.editable = rec.Shippment_loaner_time__c == null && rec.Is_Body__c;
            /*
            可分配代替品前提1 -- 备品借出申请的状态：“已批准”到“已出库指示”
            可分配代替品前提2 -- 所选借出备品配套一览的状态：‘已批准’到‘出库前已检测’
            代替品不可 Irreplaceable_flag__c
            */
            this.IsCanSub = (rec.Rental_Apply_Equipment_Set__r.Irreplaceable_flag__c) ||
                (rec.Rental_Apply__r.Status__c != '已批准' && rec.Rental_Apply__r.Status__c!= '已出库指示')  ||
                (rec.Rental_Apply_Equipment_Set__r.RAES_Status__c == '草案中' || rec.Rental_Apply_Equipment_Set__r.RAES_Status__c == '申请中' || rec.Rental_Apply_Equipment_Set__r.Shippment_loaner_time2__c != null);
            this.tempModel = rec.Fixture_Model_No__c;
            this.tempLocation = rec.Asset__r.Internal_asset_location__c;
            this.tempKey = rec.Asset__r.Internal_Asset_number_key__c;
            this.tempSerial = rec.Asset__r.SerialNumber;
            this.tempEquipmentType = rec.Asset__r.Equipment_Type__c; //20210510 ljh add 1672
            this.tempDetailStatus = rec.RAESD_Status__c;
            this.tempDate = rec.Rental_Apply_Equipment_Set__r.Rental_Start_Date__c;
            this.SubChecked = false; //20210520 ljh add 1829
            if(rec.Asset__c == null) {
                this.tempStatus = '';
            }
            else if(rec.Select_Time__c != null) {
                this.tempStatus = '已分配';
            }
        }
    }
}