/**
 * 分配画面(代替品・附属品)の設定
 */
public with sharing class RentalFixtureSetAssignController extends CreateRelationListPagingCtrlBase {
    public override Integer getSearchNumMax() {
        //各ページに制御あれば、最大件数を指定する
        searchNumMax = Integer.valueOf(Label.Product_Select_Limit);
        searchNumMax = 20;
        return searchNumMax;
    }

    /* 選択されたデータ取得用Soql　Fromから*/
    public override String getSelectedDataSql() {
        // オブジェクトAPI名
        selectedDataSql = ' From Rental_Apply_Equipment_Set__c';
        selectedDataSql += ' where Rental_Apply__c = \'' + String.escapeSingleQuotes(parentId) + '\'';
        selectedDataSql += '   and Cancel_Select__c = False';
        selectedDataSql += '   and Wei_loaner_arranged__c > 0';
        selectedDataSql += ' order by Groupby_SortInt__c, IndexFromUniqueKey__c ASC nulls last';
        // myComponentController.columnRightRW.put('QueueType__c', 'r');
        return selectedDataSql;
    }

    // 検索元対象オブジェクトAPI名
    public override String getOriginObjName() {
        // オブジェクトAPI名
        originObjName = 'Rental_Apply_Equipment_Set__c';
        return originObjName;
    }

    public override String getOriginObjColumns() {
        // 項目セット
        originObjColumns =  '';
        return originObjColumns;
    }

    public override String getObjName() {
        // オブジェクトAPI名
        objName = 'Rental_Apply_Equipment_Set__c';
        return objName;
    }
    public override String getColumnLeftFieldSetName() {
        // 左の項目セット
        columnLeftFieldSetName = '';
        return columnLeftFieldSetName;
    }
    public override String getColumnRightFieldSetName() {
        // 右の項目セット
        columnRightFieldSetName = 'RentalFixtureSetAssign_RightFieldSet';
        return columnRightFieldSetName;
    }
      
    public override String getRecordTypeId() {
        //ページレイアウトを収得するのレコードタイプ
        recordTypeId = '';
        return recordTypeId;
    }

    // ページコントローラに検索処理は、WhereSoql作成のみ、パラメータとして、コンポーネントに渡される
    public override String getSqlWhereStr() {
        sqlWhereStr = '';
        return sqlWhereStr;
    }

    public override List<String> getColumnFieldList() {
        // strColumus 里加 field
        // 'QueueType__c',
        return new List<String>{'Fixture_Set__c', 'Yi_Shipment_request__c', 'First_RAESD__r.Is_Body__c',
                'RetalFSetDetail_Cnt__c', 'RAES_Status__c', 'Rental_Apply__r.Status__c',
                'Wei_Assigned_Cnt__c', 'Yi_Assigned_Cnt__c','LastModifiedDate','First_RAESD_Is_Main__c','First_Status__c'};
                // 20220104 ljh add First_RAESD_Is_Main__c,First_Status__c
                // 20210906  ljh SFDC-C6D9C2 add LastModifiedDate
    }
    // 20211203 ljh add start
    public override List<String> getHiddenFieldList() {
        return new List<String>{'QueueType__c','First_RAESD_Model_No_F__c'};
    }
    // 20211203 ljh add end
    // 画面里直接可以输入的項目 List
    public override List<String> getWritableColumnFieldList() { 
        return new List<String>{'Rental_Start_Date__c', 'Rental_End_Date__c'};    
    }
    // getObjName 连 getOriginObjName 的 FK
    public override String getFKColumnField() {
        return null;
    }

    public override Boolean getIsNeedRunSearch(){
        return false;
    }

    public String bieCunFangDi;     //别存放地
    public String bieBenBu {get;set;}        //别本部
    public String bieChanPinFenLei; //产品分类
    public String bieBeiPinFenLei { get;
        set{
            bieBeiPinFenLeiList.add(bieBeiPinFenLei);
        }
    }  //别备品分类
    public List<String> bieBeiPinFenLeiList { get; set; }  //别备品分类


    /*****************画面Object******************/
    public Boolean hasError { get; private set; }
    public String checkEventUrl { get; set; }

    public Boolean bieField { get; set; }   //别省、别本部、别存放地、别用途
    // 备品智能化项目对应 20231122 by lc Start
    public Boolean isBefore7Days { get; set; }
    // 备品智能化项目对应 20231122 by lc End

    public Rental_Apply__c parentObj { get; private set; }
    public Rental_Apply_Equipment_Set__c rentalApplyEquipmentObj { get; private set; }

    List<Map<String, Boolean>> showButtonList = new List<Map<String, Boolean>>();
    public String salesdepartments {set;get;}
    public String equipmenttypes {set;get;}
    public Boolean is2B1 = true;
    public static String wrapperStr{set;get;}
    public static String oldCampaignType {set;get;}
    public Boolean changeCampaignType{set;get;}
    public RentalFixtureSetAssignController() {
        parentId = ApexPages.currentPage().getParameters().get('pt_recid');
         bieBeiPinFenLeiList = new List<String>();
         is2B1 = UserInfo.getProfileId() == System.Label.ProfileId_EquipmentCenter;
    }

    public void init() {
        isBefore7Days = false;
        //备品配套下的所有明细
        if (!String.isBlank(this.parentId)) {
            List<Rental_Apply__c> parentObjs =
                [SELECT Name,
                        Id,
                        Demo_purpose1__c,
                        Salesdept__c,
                        Demo_purpose2__c,
                        Internal_asset_location_F__c,
                        Equipment_Type_F__c,
                        Loaner_centre_mail_address__c,
                        Product_category_Sys__c,
                        Request_shipping_day__c,
                        Request_return_day__c,
                        Asset_loaner_start_day__c,
                        Asset_loaner_closed_day__c,
                        Product_category__c,
                        CampaignType__c,
                        Status__c,
                        Owner.Profile.Name,
                        Salesdepartment__c,
                        Hope_Lonaer_date_Num__c,
                        Campaign_EndDate_F__c,
                        OPDPlan__c,
                        Cross_Region_Assign__c
                   FROM Rental_Apply__c
                  WHERE Id = :parentId];

            if(parentObjs.size()>0){
                parentObj = parentObjs.get(0);
                bieCunFangDi = parentObj.Internal_asset_location_F__c;
                bieBenBu = parentObj.Salesdepartment__c;
                bieChanPinFenLei = parentObj.Product_category__c;
                // bieBeiPinFenLei = parentObj.Equipment_Type_F__c;
                oldCampaignType = parentObj.CampaignType__c;
                changeCampaignType = false;
                parentObj.Product_category_Sys__c = parentObj.Product_category__c;

                if (bieBeiPinFenLeiList.size() == 0 && String.isNotBlank(parentObj.Equipment_Type_F__c)) {
                    for (String et : parentObj.Equipment_Type_F__c.split(',')) {
                        bieBeiPinFenLeiList.add(et);
                    }
                }
                
                // 备品智能化项目对应 20231122 by lc Start
                // 所有的申请单只有学会展会的可以提前7天做人工处理，学会展会可以提前只能分配，但是都不能提前排队
                if (parentObj.Request_shipping_day__c > Date.today().addDays(7)) {
                    isBefore7Days = true;
                }
                // 备品智能化项目对应 20231122 by lc End

                //备品预计出货日、备品预计回收日初期値は、希望到货日-2天と预定归还日+2天
                // if (parentObj.Request_shipping_day__c != null) {
                //     parentObj.Asset_loaner_start_day__c = parentObj.Request_shipping_day__c.addDays(-2);
                // }
                // if (parentObj.Request_return_day__c != null) {
                //     parentObj.Asset_loaner_closed_day__c = parentObj.Request_return_day__c.addDays(2);
                // }
            }
        }
    }

    // 适用按钮
    public void checkDate() {
        String strMessage = null;
        hasError = false;
        System.debug(LoggingLevel.INFO, '***checkDate parentObj: ' + parentObj);
        if (parentObj.Asset_loaner_start_day__c == null) {
            hasError = true;
            strMessage = '请输入[备品预计出货日]';
        }
        if (parentObj.Asset_loaner_closed_day__c == null) {
            hasError = true;
            strMessage = '请输入[备品预计回收日]';
        }
        if (parentObj.Asset_loaner_start_day__c != null && parentObj.Asset_loaner_start_day__c < Date.today()) {
            hasError = true;
            // 20231011 ljh update start
            // strMessage = '[备品预计出货日]必须入力从今天开始起的日期 ';
            strMessage = '[备品预计出货日]必须输入从今天开始起的日期 ';
            // 20231011 ljh update end
        }
        if (parentObj.Asset_loaner_start_day__c != null && parentObj.Asset_loaner_closed_day__c != null && parentObj.Asset_loaner_start_day__c > parentObj.Asset_loaner_closed_day__c) {
            hasError = true;
            strMessage = '[备品预计出货日]必须小于等于[备品预计回收日]';
        }
        if (hasError) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, strMessage));
        }

        system.debug(' working!!!');
    }

    //产品分类 SelectOption
    public List<SelectOption> getbieChanPinFenLeiOps() {
        //产品分类(GI/SP) F Product_category_F__c
        // return FixtureUtil.bieChanPinFenLeiOpsMap.get(sonObj.Product_category_F__c);
        return FixtureUtil.bieChanPinFenLeiOpsMap.get('GISP');
    }

    //别备品分类 SelectOption
    public List<SelectOption> getbieBeiPinFenLeiOps() {
        //备品分类(现在) Equipment_Type__c
        // return FixtureUtil.bieBeiPinFenLeiOpsMap.get(sonObj.Equipment_Type__c);
        List<SelectOption> options = FixtureUtil.bieBeiPinFenLeiOpsMap.get('备品分类');
        System.debug(LoggingLevel.INFO, '*** options: ' + options);
        options.remove(0);
        // if(parentObj.demo_purpose2__c != '其他'){
        //     for(Integer i = options.size() - 1;i >= 0; i -- ){
        //         if(i != 1 && i != 2){
        //             options.remove(i);
        //         }
        //     }
        // }
        
        
        System.debug(LoggingLevel.INFO, '*** options1111: ' + options);
        return options;
    }

    //别存放地 SelectOption
    public List<SelectOption> getbieCunFangDiOps() {
        //备品存放地(现在)
        // return FixtureUtil.bieCunFangDiOpsMap.get(sonObj.Internal_asset_location__c);
        // return new List<SelectOption>{
        //     new SelectOption(sonObj.Rental_Apply__r.Internal_asset_location_F__c, sonObj.Rental_Apply__r.Internal_asset_location_F__c)
        // };
        // cunfangdiSet = new Set<String>();
        List<SelectOption> opList;
        if (UserInfo.getProfileId() == System.Label.ProfileId_SystemAdmin
                || System.Label.ProfileId_EquCenAdmin.contains(UserInfo.getProfileId())
                || is2B1) {
            opList = FixtureUtil.bieCunFangDiOpsMap.get('备品管理中心');
        } else {
            opList = new List<SelectOption>{
                new SelectOption(bieCunFangDi, bieCunFangDi)
            };
        }

        // for (SelectOption op : opList) {
        //     if (String.isNotBlank(op.getValue())) {
        //         cunfangdiSet.add(op.getValue());
        //     }
        // }
        return opList;
    }
    //别本部 SelectOption
    public List<SelectOption> getbieBenBuOps() {
        
        List<SelectOption> opList = FixtureUtil.bieBenBuOpsMap.get(bieCunFangDi);
        if(opList!= null && opList.size() > 0){
            opList.remove(0);
        }
        return opList;
    }

    //产品分类 SelectOption
    // public List<SelectOption> getbieChanPinFenLeiOps() {
    //     //产品分类(GI/SP) F Product_category_F__c
    //     // return FixtureUtil.bieChanPinFenLeiOpsMap.get(sonObj.Product_category_F__c);
    //     return FixtureUtil.bieChanPinFenLeiOpsMap.get('GISP');
    // }

    //别备品分类 SelectOption
    // public List<SelectOption> getbieBeiPinFenLeiOps() {
    //     //备品分类(现在) Equipment_Type__c
    //     // return FixtureUtil.bieBeiPinFenLeiOpsMap.get(sonObj.Equipment_Type__c);
    //     return FixtureUtil.bieBeiPinFenLeiOpsMap.get('备品分类');
    // }


    public PageReference save() {
        hasError = false;
        // updateだけ使用する
        List<Rental_Apply_Equipment_Set__c> mfUpdate = new List<Rental_Apply_Equipment_Set__c>();
        Savepoint sp = Database.setSavepoint();
        List<String> statusList = System.Label.StatusProcessState.split(',');

        try {
            Boolean updRAFlg = false;
            Rental_Apply__c raUpd = [
                    SELECT Id, Shipment_request_Cnt__c,
                           Asset_loaner_start_day__c,
                           Asset_loaner_closed_day__c,
                           Campaign__c,
                           Campaign__r.IF_Approved__c,
                           Campaign__r.Meeting_Approved_No__c,
                           Campaign__r.Approved_Status__c   //2022 sx obpm备品决裁状态相关修改
                      FROM Rental_Apply__c
                     WHERE Id = :parentId
                       FOR Update];
            if (!(raUpd.Shipment_request_Cnt__c > 0)) {
                if (raUpd.Asset_loaner_start_day__c == null) {
                    raUpd.Asset_loaner_start_day__c = parentObj.Asset_loaner_start_day__c;
                    updRAFlg = true;
                }
                if (raUpd.Asset_loaner_closed_day__c == null) {
                    raUpd.Asset_loaner_closed_day__c = parentObj.Asset_loaner_closed_day__c;
                    updRAFlg = true;
                }
            }

            //20220228 sx obpm修改 是否申请决裁勾着没有决裁编号不能进行操作
            if( raUpd.Campaign__c!= null && raUpd.Campaign__r.IF_Approved__c && raUpd.Campaign__r.Meeting_Approved_No__c == null){
                throw new ControllerUtil.myException('已申请决裁但决裁编码为空');
            }
            //20220315 sx obpm obpm备品决裁状态相关修改 start
            else if( raUpd.Campaign__c!= null && raUpd.Campaign__r.IF_Approved__c && raUpd.Campaign__r.Meeting_Approved_No__c != null && statusList.contains(raUpd.Campaign__r.Approved_Status__c) ){
                throw new ControllerUtil.myException('已申请决裁但决裁状态不符合条件');
            }
            //20220315 sx obpm obpm备品决裁状态相关修改 end
            Integer indexNum = 1;
            // 20210708 ljh SFDC-C47CLV add start
            Set<Id> raeIdset = new Set<Id>();
            // Map<String,String> raeIdraIdM = new Map<String,String>(); // 20210906  ljh SFDC-C6D9C2
            Map<String,Rental_Apply_Equipment_Set__c> raeIdraIdM = new Map<String,Rental_Apply_Equipment_Set__c>();// 20210906  ljh SFDC-C6D9C2 add
            for (WrapperInfo prInfo : viewList) {
                Rental_Apply_Equipment_Set__c robj = (Rental_Apply_Equipment_Set__c) prInfo.sobj;
                if (prInfo.check) {
                    raeIdset.add(robj.Id);    
                }
            }

            List<Rental_Apply_Equipment_Set__c> raeList = [SELECT Id, Name,Rental_Apply__c,Cancel_Select__c,LastModifiedDate FROM Rental_Apply_Equipment_Set__c where Id in :raeIdset];
            // 20210906  ljh SFDC-C6D9C2 add LastModifiedDate
            for(Rental_Apply_Equipment_Set__c rae:raeList){
                // 20210906  ljh SFDC-C6D9C2 update
                // raeIdraIdM.put(rae.Id,rae.Rental_Apply__c);
                raeIdraIdM.put(rae.Id,rae);
                // 20210906  ljh SFDC-C6D9C2 end
            }
            // 20210708 ljh SFDC-C47CLV add end
            for (WrapperInfo prInfo : viewList) {
                Rental_Apply_Equipment_Set__c robj = (Rental_Apply_Equipment_Set__c) prInfo.sobj;
                // 画面上にチェックした
                if (prInfo.check) {
                    // 20210708 ljh add start
                    //system.debug('zheli'+robj.Rental_Apply__c+'~'+raUpd.Id);
                    // 20210906  ljh SFDC-C6D9C2 update start
                    // if (robj.Rental_Apply__c != raeIdraIdM.get(robj.Id)) {
                    if (robj.Rental_Apply__c != raeIdraIdM.get(robj.Id).Rental_Apply__c) {
                    // 20210906  ljh SFDC-C6D9C2 update end
                        hasError = true;
                        throw new ControllerUtil.myException('第' + indexNum +'行数据已被分割申请单，请刷新后重试！');
                    }

                    // 20210708 ljh update end
                    // 20210906  ljh SFDC-C6D9C2 add start
                    // 20210929 ljh SFDC-C6D9C2 注释 恢复改其他方案 start
                    // 20211018 ljh 注释放开 start
                    // 取消状态只能从 不取消变成取消 
                    // 点击保存或分配按钮后，校验一览是否已取消，若勾选的有取消的一览，提示【第X行数据已取消，请刷新后重试！】
                    if (robj.Cancel_Select__c != raeIdraIdM.get(robj.Id).Cancel_Select__c) {
                        hasError = true;
                        throw new ControllerUtil.myException('第' + indexNum +'行'+robj.First_RAESD_Model_No_F__c+'已取消，请取消相应配套的勾选或刷新页面！');
                    }
                    // 20211018 ljh 注释放开 start
                    // 20210929 ljh SFDC-C6D9C2 注释 恢复改其他方案 end
                    // 20210906  ljh SFDC-C6D9C2 add emd
                    if (robj.Rental_Start_Date__c == null) {
                        hasError = true;
                        // throw new ControllerUtil.myException('第' + indexNum +'行数据的[备品预计出货日]为空,备品预计出货日必须入力');
                        throw new ControllerUtil.myException('第' + indexNum +'行数据的[备品预计出货日]为空,备品预计出货日必须输入');
                    }
                    if (robj.Rental_End_Date__c == null) {
                        hasError = true;
                        // throw new ControllerUtil.myException('第' + indexNum +'行数据的[备品预计回收日]为空,备品预计回收日必须入力');
                        throw new ControllerUtil.myException('第' + indexNum +'行数据的[备品预计回收日]为空,备品预计回收日必须输入');
                    }
                    if (robj.Rental_Start_Date__c != null && robj.Rental_Start_Date__c < Date.today()) {
                        hasError = true;
                        // throw new ControllerUtil.myException('第' + indexNum +'行数据的[备品预计出货日]必须入力从今天开始起的日期');
                        throw new ControllerUtil.myException('第' + indexNum +'行数据的[备品预计出货日]必须输入从今天开始起的日期');
                    }

                    mfUpdate.add(robj);
                }
                indexNum += 1;
            }

            if (updRAFlg) { update raUpd; }
            if (mfUpdate.size() > 0) {
                FixtureUtil.withoutUpdate(mfUpdate);
            }

        } catch (Exception ex) {

            System.debug(ex.getStackTraceString());
            ApexPages.addMessages(ex);
            Database.rollback(sp);
            hasError = true;
            return null;
        }

        return null;
    }

    // 返回按钮
    public PageReference cancel() {
        PageReference ref =  new Pagereference('/');
        if (String.isNotBlank(parentId)) {
            // 返回备品借出申请
            ref = new Pagereference('/' + parentId);
        }
        ref.setRedirect(true);
        return ref;
    }

    public override void checkEvent() {
        Rental_Apply_Equipment_Set__c raes = (Rental_Apply_Equipment_Set__c) viewList[clickLineNo].sobj;
        String iszhu = ApexPages.currentPage().getParameters().get('isZhu');
        if (iszhu == 'true') {
            // 主体備品選択画面url
            checkEventUrl = '/apex/MainFixtureSelect?pt_recid='
                + ((Rental_Apply_Equipment_Set__c) viewList[clickLineNo].sobj).Id;
        } else {
            checkEventUrl = '/apex/AccessorySelect?pt_recid=' + raes.Id;
        }
    }

    public override void setViewList(List<SObject> queryList) {
        viewList = new List<WrapperInfo>();

        //别存放地
        String bieWhere = ' and ((Internal_asset_location__c like \'%' + String.escapeSingleQuotes(bieCunFangDi) + '%\'';

        //别本部
        if (String.isNotBlank(bieBenBu)) {
            bieWhere += ' and Salesdepartment__c like \'%' + String.escapeSingleQuotes(bieBenBu) + '%\'';
        }

        //产品分类
        if (String.isNotBlank(bieChanPinFenLei)) {
            bieWhere += 'and Product_category__c like \'%' + String.escapeSingleQuotes(bieChanPinFenLei) + '%\'';
        }

        //别备品分类
        bieWhere += RentalFixtureSetAssignController.setSoql('Equipment_Type__c', bieBeiPinFenLeiList);
        // //别备品分类
        // if (String.isNotBlank(bieBeiPinFenLei)) {
        //     bieWhere += 'and Equipment_Type__c = \'' + String.escapeSingleQuotes(bieBeiPinFenLei) + '\'';
        // }

        bieWhere += 'and Loaner_accsessary__c= false) OR (Loaner_accsessary__c= true ';
        //别存放地
        bieWhere += ' and Internal_asset_location__c = \'' + String.escapeSingleQuotes(bieCunFangDi) + '\'';
        // OLY_OCM-654 保有设备合并 本部的检索条件至少有MA和产品检测的时候才需要 Start
        //别本部
        if (String.isNotBlank(bieBenBu) && FixtureUtil.needSalesdepartment.contains(bieBenBu)) {
        // OLY_OCM-654 保有设备合并 本部的检索条件至少有MA和产品检测的时候才需要 End
            bieWhere += ' and Salesdepartment__c = \'' + String.escapeSingleQuotes(bieBenBu) + '\'';
        } else {
            bieWhere += ' and Salesdepartment__c IN ' + FixtureUtil.otherBenbus;
        }

        bieWhere += '))';

        System.debug(bieWhere);




        // 数式項目値を取れるのために、一回Insertする
        List<Rental_Apply_Equipment_Set__c> tempList = new List<Rental_Apply_Equipment_Set__c>();
        Map<Id, Map<Rental_Apply_Equipment_Set_Detail__c, Map<String, FixtureUtil.groupBean>>> raesMap = FixtureUtil.raesGroupBy(selectedData, myComponentController.columus, bieWhere);

        // 選択済みの明细
        if(selectedData.size()>0) {
            Map<Id, Rental_Apply_Equipment_Set_Detail__c> raesdMapz = new Map<Id, Rental_Apply_Equipment_Set_Detail__c>();
            Map<Id, Rental_Apply_Equipment_Set_Detail__c> raesdMapf = new Map<Id, Rental_Apply_Equipment_Set_Detail__c>();
            for (Integer i = 0; i < selectedData.size(); i++) {
                /* not include the selected data num */
                // 501を超えた場合前500のみを出す
                Rental_Apply_Equipment_Set__c rentalObj = (Rental_Apply_Equipment_Set__c) selectedData[i];
                Map<Rental_Apply_Equipment_Set_Detail__c, Map<String, FixtureUtil.groupBean>> rmap = raesMap.get(rentalObj.Id);
                //别用途库存num
                Integer yongyuKucunNum = 0;
                //别本部库存num
                Integer benbuKucunNum = 0;
                //别产品分类num
                Integer chanpinFenleiNum = 0;
                //别存放地的库存num
                Integer cunfangdiKucunNum = 0;

                // 主机数量汇总:大于零时是主体;等于零时是附属品
                Map<String, Boolean> showMap = new Map<String, Boolean>();

                if (rentalObj.First_RAESD__r.Is_Body__c == true) {
                    showMap.put('ZHU', true);
                    showMap.put('FU', rentalObj.RetalFSetDetail_Cnt__c > 1);
                } else if (rentalObj.RetalFSetDetail_Cnt__c > 0 && rentalObj.First_RAESD__r.Is_Body__c == false) {
                    showMap.put('ZHU', false);
                    showMap.put('FU', true);
                } else {
                    showMap.put('ZHU', false);
                    showMap.put('FU', false);
                }
                showButtonList.add(showMap);
                //用来判断是不是一览里面的第一条明细
                Boolean isf = true;
                System.debug('sizeis' + rmap.size());
                for (Rental_Apply_Equipment_Set_Detail__c rentalc : rmap.keySet()) {
                    if (rentalc.Is_Body__c) {
                         raesdMapz.put(rentalc.Id, rentalc);
                    } else {
                        raesdMapf.put(rentalc.Id, rentalc);
                    }

                    Map<String, FixtureUtil.groupBean> rsdGroupInfo = rmap.get(rentalc);
                    for (String apikey : rsdGroupInfo.keySet()){
                        if (apikey.indexOf('_Jia__c') >= 0) {

                            if (apikey == 'You_Xiao_Kun_Cun_Jia__c'
                                    || apikey == 'Jie_Chu_Fen_Pei_Jia__c'
                                    || apikey == 'Fu_Shu_Pin_Fen_Pei_Jia__c'
                                    || apikey == 'Zhu_Ti_Fen_Pei_Jia__c'
                                    // || apikey == 'Jie_Chu_Shi_Jian_Jia__c'
                                    ) {
                                // 別途設定する or 設定しない
                                continue;
                            }
                            else if (apikey == 'Bie_Yong_Tu_Ku_Cun_Jia__c') {
                                yongyuKucunNum += rsdGroupInfo.get(apikey).gnum;
                            }
                            else if (apikey == 'Bie_Ben_Bu_Ku_Cun_Jia__c') {
                                benbuKucunNum += rsdGroupInfo.get(apikey).gnum;
                            }
                            else if (apikey == 'Bie_Chan_Pin_Fen_Lei_Jia__c') {
                                chanpinFenleiNum += rsdGroupInfo.get(apikey).gnum;
                            }
                            else if (apikey == 'Bie_Cun_Fang_Di_Ku_Cun_Jia__c') {
                                cunfangdiKucunNum += rsdGroupInfo.get(apikey).gnum;
                            }
                            else if (apikey == 'Ke_Yi_Fen_Pei_Zhu_Ti_Jia__c') {
                                // 主体的状态从FixtureUtil中获取
                                // 附属品的状态从FixtureUtil中获取
                                if(rentalc.Is_Body__c == true) {
                                    rentalObj.put(apikey, rsdGroupInfo.get(apikey).gnum);
                                }
                            }
                            else {
                                //如果是一览里面的第一次设置，假字段需要清0，因为保存的时候会把假字段的值赋值进去
                                if (isf) {
                                    rentalObj.put(apikey, 0);
                                    isf = false;
                                }
                                System.debug('测试1:' + apikey);
                                System.debug('测试2:' + rsdGroupInfo.get(apikey).gnum);
                                if (rentalObj.get(apikey) != null) {
                                    rentalObj.put(apikey, (Decimal)rentalObj.get(apikey) + rsdGroupInfo.get(apikey).gnum);
                                }
                            }
                        }
                    }
                }

                if (yongyuKucunNum > 0) {
                    rentalObj.Bie_Yong_Tu_Ku_Cun_Jia__c = '有';
                } else {
                    rentalObj.Bie_Yong_Tu_Ku_Cun_Jia__c = '无';
                }

                if (benbuKucunNum > 0) {
                    rentalObj.Bie_Ben_Bu_Ku_Cun_Jia__c = '有';
                } else {
                    rentalObj.Bie_Ben_Bu_Ku_Cun_Jia__c = '无';
                }

                if (chanpinFenleiNum > 0) {
                    rentalObj.Bie_Chan_Pin_Fen_Lei_Jia__c = '有';
                } else {
                    rentalObj.Bie_Chan_Pin_Fen_Lei_Jia__c = '无';
                }

                if (cunfangdiKucunNum > 0) {
                    rentalObj.Bie_Cun_Fang_Di_Ku_Cun_Jia__c = '有';
                } else {
                    rentalObj.Bie_Cun_Fang_Di_Ku_Cun_Jia__c = '无';
                }

                // rentalObj.Fu_Shu_Pin_Fen_Pei_Jia__c = FixtureUtil.assetStatusMap.get(accessoryStatus);
                // rentalObj.Zhu_Ti_Fen_Pei_Jia__c = FixtureUtil.assetStatusMap.get(subjectStatus);
                System.debug('测试rentalObj.Yi_Shipment_request__c:' + rentalObj.Yi_Shipment_request__c);
                if (!(rentalObj.Yi_Shipment_request__c > 0)) {
                    if (rentalObj.Rental_Start_Date__c == null) {
                        rentalObj.Rental_Start_Date__c = parentObj.Asset_loaner_start_day__c;
                    }
                    if (rentalObj.Rental_End_Date__c == null) {
                        rentalObj.Rental_End_Date__c = parentObj.Asset_loaner_closed_day__c;
                    }
                }
                WrapperInfo info =  new WrapperInfo(rentalObj, myComponentController);
                info.additionalInfoMap.put('QueueType__c', rentalObj.QueueType__c==null?'':rentalObj.QueueType__c); // 20211203 ljh add
                info.additionalInfoMap.put('First_RAESD_Model_No_F__c', rentalObj.First_RAESD_Model_No_F__c==null?'':rentalObj.First_RAESD_Model_No_F__c); // 20211203 ljh add
                
                
                viewList.add(info);
                viewList[viewList.size() - 1].lineNo = viewList.size() - 1;
                viewList[viewList.size() - 1].check = true;
                viewList[viewList.size() - 1].oldCheck = true; 
                // viewList[viewList.size() - 1].additionalInfoMap.put('QueueType__c ', rentalObj.QueueType__c == null?'':rentalObj.QueueType__c);
            }
            Map<Id, String> zmap = FixtureUtil.makeZhu_Ti_Fen_Pei_Jia(raesdMapz, raesMap);
            Map<Id, String> fmap = FixtureUtil.makeFu_Shu_Pin_Fen_Pei_Jia(raesdMapf, raesMap);
            for (Integer i = 0; i < selectedData.size(); i++) {
                /* not include the selected data num */
                // 501を超えた場合前500のみを出す
                Rental_Apply_Equipment_Set__c rentalObj = (Rental_Apply_Equipment_Set__c)selectedData[i];
                if (fmap.containsKey(rentalObj.Id)) {
                    if ((rentalObj.Rental_Apply__r.Status__c == '已批准'
                                || rentalObj.Rental_Apply__r.Status__c == FixtureUtil.raStatusMap.get(FixtureUtil.RaStatus.Yi_Chu_Ku_Zhi_Shi.ordinal())
                        )
                        && rentalObj.Wei_Assigned_Cnt__c > 0
                    ) {
                        rentalObj.Fu_Shu_Pin_Fen_Pei_Jia__c = fmap.get(rentalObj.Id);
                    } else {
                        //rentalObj.Zhu_Ti_Fen_Pei_Jia__c = rentalObj.RAES_Status__c;
                        rentalObj.Fu_Shu_Pin_Fen_Pei_Jia__c = rentalObj.RAES_Status__c;
                    }
                }

                if (zmap.containsKey(rentalObj.Id)) {
                    //20231224 sx add 备品智能化添加状态申请中（OPD未通过） 优化
                    if (rentalObj.Rental_Apply__r.Status__c == '填写完毕' || rentalObj.Rental_Apply__r.Status__c == '草案中'
                        || rentalObj.Rental_Apply__r.Status__c == '申请中' || rentalObj.Rental_Apply__r.Status__c == '申请中（OPD未通过）' || rentalObj.Rental_Apply__r.Status__c == '不批准') {
                            rentalObj.Zhu_Ti_Fen_Pei_Jia__c = rentalObj.RAES_Status__c;
                    } else {
                        rentalObj.Zhu_Ti_Fen_Pei_Jia__c = zmap.get(rentalObj.Id);
                    }
                }
            }
        }
        wrapperStr = JSON.serialize(viewList);
        System.debug(LoggingLevel.INFO, '*** wrapperStr: ' + wrapperStr);
        system.debug('●●●●● setViewList END ' );
    }

    public static String setSoql(String field, List<String> valieList) {
        String whereStr = '';
        for (String  val : valieList) {
            if (String.isNotBlank(val)) {
                if (String.isBlank(whereStr)) {
                    whereStr += ' and (';
                    whereStr += field + ' = \'' + val + '\'';
                }
                else {
                    whereStr += ' or ' + field + ' = \'' + val + '\'';
                }
            }
        }
        if (String.isNotBlank(whereStr)) {
            whereStr += ')';
        }
        return whereStr;
    }

    public String getBodyModelNoJson() {
        return JSON.serialize(showButtonList);
    }

    public String getWrapperJSON(){
        System.debug(LoggingLevel.INFO, '*** wrapperStr: ' + wrapperStr);
        return wrapperStr;
    }

    


    //特殊排队
    public PageReference specialScheduel(){

        
        hasError = false;
        List<Rental_Apply_Equipment_Set__c> mfUpdate = new List<Rental_Apply_Equipment_Set__c>();
        Savepoint sp = Database.setSavepoint();
        try {
            equipmenttypes = equipmenttypes =='--无--'?'':equipmenttypes;
            salesdepartments = salesdepartments =='--无--'?'':salesdepartments;
            // 20220104 ljh 排队 update start
            if(String.isEmpty(equipmenttypes)){
                // throw new ControllerUtil.myException('特殊排队时，备品分类必填！');
                throw new ControllerUtil.myException('特殊排队时，请选择备品分类');
            }
            if(String.isEmpty(salesdepartments)){
                // throw new ControllerUtil.myException('特殊排队时，本部必填！');
                throw new ControllerUtil.myException('特殊排队时，请选择本部');
            }
            // 20220104 ljh 排队 update  end
            if(parentObj.Demo_purpose1__c =='产品试用' && (equipmenttypes.contains('维修') || equipmenttypes.contains('协议借用'))){
                throw new ControllerUtil.myException('产品试用的申请单，不可以选择维修类、协议借用类的备品分类');
            }
            if(parentObj.demo_purpose2__c == '学会展会' && parentObj.Owner.Profile.Name.contains('FSE')){
                // 20220107 ljh update start
                // throw new ControllerUtil.myException('FSE的学会展会申请单不允许特殊排队!');
                throw new ControllerUtil.myException('服务培训/学会申请单无特殊排队！');
                // 20220107 ljh update end
            }
            
            // if(parentObj.demo_purpose2__c == '学会展会' && !(parentObj.Salesdepartment__c.contains('MA本部') || parentObj.Salesdepartment__c.contains('产品培训')) && String.isEmpty(parentObj.CampaignType__c) ){
            //     throw new ControllerUtil.myException('请选择学会类型！');
            // }
            // if(parentObj.CampaignType__c == '服务培训/学会'){
            //     throw new ControllerUtil.myException('当前学会类型不允许特殊排队!');
            // }
            if(parentObj.Demo_purpose1__c == '维修代用' || parentObj.Demo_purpose1__c == '协议借用'){
                 throw new ControllerUtil.myException('当前使用目的不允许特殊排队!');
            }
            if((salesdepartments.contains('MA本部') || salesdepartments.contains('产品培训')) && (salesdepartments.countMatches('本部') > 1 || salesdepartments.contains('备品中心'))){
                throw new ControllerUtil.myException('MA本部/产品培训本部不能与其他本部同时选择!');
            }
            if(((equipmenttypes.contains('产品试用') || equipmenttypes.contains('学会展会'))&& equipmenttypes.contains('协议借用')) 
                || (equipmenttypes.contains('协议借用') && equipmenttypes.contains('维修'))
                || ((equipmenttypes.contains('产品试用') || equipmenttypes.contains('学会展会'))&& equipmenttypes.contains('维修'))){
                throw new ControllerUtil.myException('维修类、试用类、协议借用类不能同时选择!');
            }
            if(String.isEmpty(parentObj.Product_category_Sys__c)){
                throw new ControllerUtil.myException('请填写产品分类！');
            }
            startQueue('特殊排队');
            if(allSpecialQueue()){
                parentObj.CampaignType__c = null;
                update parentObj;
            }

        }
        catch (Exception e) {
            System.debug('e.getMessage()***'+ e.getMessage()+e.getLineNumber());
            ApexPages.addMessages(e);
            Database.rollback(sp);
            hasError = true;
            return null;
        }
        // 20220105 ljh add start
        myComponentController.getSelectedDataInfo();
        getSqlWhereStr();
        myComponentController.searchAndPaging();
        // 20220105 ljh add end
        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM,'排队成功'));
        return null;
    }

    //默认排队
    public PageReference defaultScheduel(){
        hasError = false;
        
        Savepoint sp = Database.setSavepoint();
        System.debug(LoggingLevel.INFO, '*** parentObj: ' + parentObj);

        try {
            if(parentObj.demo_purpose2__c == '学会展会' && !(parentObj.Salesdepartment__c.contains('MA本部') || parentObj.Salesdepartment__c.contains('产品培训')) && String.isEmpty(parentObj.CampaignType__c) ){
                throw new ControllerUtil.myException('请选择学会类型！');
            }
            startQueue('默认排队');
        }
        catch (Exception e) {
            System.debug('e.getMessage()***'+ e.getMessage()+e.getLineNumber());
            ApexPages.addMessages(e);
            Database.rollback(sp);
            hasError = true;
            return null;
        }
        // 20220105 ljh add start
        myComponentController.getSelectedDataInfo();
        getSqlWhereStr();
        myComponentController.searchAndPaging();
        // 20220105 ljh add end
        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM,'排队成功'));
        return null;
    }
    //排队置顶
    public PageReference topInLine(){
        hasError = false;
        Savepoint sp = Database.setSavepoint();
        try {
            List<Rental_Apply_Equipment_Set_Detail__c> raesdObjs = getdetailList(viewList,parentObj);
            System.debug(LoggingLevel.INFO, '*** raesdObjs.size(): ' + raesdObjs.size());
            saveAgdustQueue(raesdObjs,'front');

            // QueuePageByAssetIdController.saveQueue();
        }
        catch (Exception e) {
            System.debug('e.getMessage()***'+ e.getMessage()+e.getLineNumber());
            ApexPages.addMessages(e);
            Database.rollback(sp);
            hasError = true;
            return null;
        }
        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM,'排队置顶成功'));
        return null;
    }

    /**
     * 调整队列
     * */
    public static void saveAgdustQueue(List<Rental_Apply_Equipment_Set_Detail__c> raesdObjs,String fromtype) {

        System.debug(LoggingLevel.INFO, '*** applysetMap: ' + applysetMap);
        List<String> keyList = new List<String>();
        List<String> detailIds = new List<String>();
        Map<String,List<Rental_Apply_Equipment_Set_Detail__c>> detailMap = new Map<String,List<Rental_Apply_Equipment_Set_Detail__c>>();
        for(Rental_Apply_Equipment_Set_Detail__c raesd:raesdObjs){
            System.debug(LoggingLevel.INFO, '*** raesd.Id: ' + raesd.Id);
            String index = '';
            if(applysetMap.containskey(raesd.Rental_Apply_Equipment_Set__c)){
                index = applysetMap.get(raesd.Rental_Apply_Equipment_Set__c); 
            }
              
            String msg = '';

            if(raesd.Queue_Number__c == null){
                if(fromtype == 'front'){
                    msg = '第' + index + '行未进行过排队，不能调整。';
                }else{
                    msg = '一览：' + index + '未进行过排队，不能调整。';
                }
                throw new ControllerUtil.myException(msg);
            }
            if (!raesd.Allow_Adjust_Queue_Flag__c) {
                if(fromtype == 'front'){
                    msg = '第' + index + '行备品总窗口未申请插队，无法调整顺序。';
                }else{
                    msg = '一览：' + index + '备品总窗口未申请插队，无法调整顺序。';
                }
                throw new ControllerUtil.myException(msg);
            }
            keyList.add(raesd.ExternalKey__c);
            if(!detailMap.containsKey(raesd.ExternalKey__c)){
                detailMap.put(raesd.ExternalKey__c,new List<Rental_Apply_Equipment_Set_Detail__c>());
            }   
            detailMap.get(raesd.ExternalKey__c).add(raesd);
            
            detailIds.add(raesd.Id);
        }
        List<Rental_Apply_Equipment_Set_Detail__c> raesdList = [SELECT Id, Rental_Apply_Equipment_Set__c, Asset__c,Rental_Apply_Equipment_Set__r.Fixture_Set__r.Product_Type__c,
                                                                   FSD_Fixture_Model_No__c, Fixture_Model_No_text__c,Rental_Apply__r.demo_purpose2__c,Queue_Day__c,ExternalKey__c,
                                                                   Is_Body__c, FSD_Is_OneToOne__c, Select_Time__c,Rental_Apply__r.EquipmentGuaranteeFlg__c,Allow_Adjust_Queue_Flag__c,
                                                                   Cancel_Select__c, Fixture_Model_No_F__c, Queue_Number__c, Internal_asset_location__c,Fixture_Model_No__c,Rental_Apply__c,
                                                                   Internal_asset_location_before__c,Salesdepartment__c, Product_category_F__c, Product_category_text__c,Equipment_Type_text__c,
                                                                   Salesdepartment_before__c,Rental_Apply__r.Request_shipping_day__c,QuenType__c,IsAdjust__c,Rental_Apply__r.Request_approval_time__c,
                                                                   Equipment_Type__c, Rental_Apply__r.Internal_asset_location_F__c,Cancel_Reason__c,Loaner_cancel_reason__c,
                                                                   Loaner_cancel_Remarks__c ,Rental_Apply_Equipment_Set__r.Name
                                                            FROM Rental_Apply_Equipment_Set_Detail__c
                                                            WHERE Queue_Number__c > 0
                                                              AND Cancel_Select__c = false
                                                              AND ExternalKey__c IN: keyList
                                                              AND Id NOT IN:detailIds
                                                            ORDER BY Queue_Number__c ASC nulls last];
        System.debug(LoggingLevel.INFO, '*** raesdList: ' + raesdList);
        Map<String,List<Rental_Apply_Equipment_Set_Detail__c>> queueMap = new Map<String,List<Rental_Apply_Equipment_Set_Detail__c>>();
        for(Rental_Apply_Equipment_Set_Detail__c detail:raesdList){
            if(!queueMap.containskey(detail.Externalkey__c)){
                queueMap.put(detail.Externalkey__c,new List<Rental_Apply_Equipment_Set_Detail__c>());
            }
            queueMap.get(detail.Externalkey__c).add(detail);
        }
        System.debug(LoggingLevel.INFO, '*** queueMap: ' + queueMap);
        Decimal orderNo = 0;
        List<String> sequencekeylist = new List<String>();
        List<Rental_Apply_Equipment_Set_Detail__c> queueList = new List<Rental_Apply_Equipment_Set_Detail__c>();
        for(String key:detailMap.keySet()){
            System.debug(LoggingLevel.INFO, '*** key: ' + key);
            List<Rental_Apply_Equipment_Set_Detail__c> ajdusts = detailMap.get(key);
            Integer k = 1;
            for(Rental_Apply_Equipment_Set_Detail__c ajdust:ajdusts){
                queueList.add(ajdust);
                KeyObj obj = getSequenceInfo(ajdust);
                sequencekeylist.addAll(obj.sequencekeylist);
                System.debug(LoggingLevel.INFO, '*** ajdust.Queue_Number__c: ' + ajdust.Queue_Number__c);
                orderNo = ajdust.Queue_Number__c;
                System.debug(LoggingLevel.INFO, '*** k: ' + k);
                ajdust.Queue_Number__c = k;
                ajdust.IsAdjust__c = true;
                k ++;
            }
            
            
            if(queueMap.containskey(key)){
                Decimal i = k;
                for(Rental_Apply_Equipment_Set_Detail__c detail:queueMap.get(key)){
                    if(detail.Queue_Number__c != i){
                        KeyObj dobj = getSequenceInfo(detail);
                        sequencekeylist.addAll(dobj.sequencekeylist);
                        System.debug(LoggingLevel.INFO, '*** i: ' + i);

                        detail.Queue_Number__c = i;
                        queueList.add(detail);
                    }
                    i ++;
                }
            }
        }
        FixtureUtil.withoutUpdate(queueList);
        List<String> nodusequencekeylist = new List<String>(new Set<String>(sequencekeylist));
        List<Rental_Apply_Sequence__c> updateSequenceList = new List<Rental_Apply_Sequence__c>();
        List<Rental_Apply_Sequence__c> applysequenceList = [SELECT Id,ExternalKey__c,Demo_Purpose2__c,
                                                    Apply_Set_Detail__c,Apply_Set_Detail_ExternalKey__c,
                                                    Series_No__c,Salesdepartment__c,Product_category__c,
                                                    Rental_Apply__c,Internal_asset_location__c,
                                                    Apply_Set_Detail__r.Queue_Number__c,Series_Unequal_Queue_Flag__c,
                                                    Fixture_Model_No__c,Equipment_Type__c
                                                    FROM Rental_Apply_Sequence__c
                                                    WHERE ExternalKey__c IN: nodusequencekeylist
                                                    AND Series_No__c > 0
                                                    AND Invalid_Flag__c =false
                                                    FOR Update 
                                                    ];
        System.debug(LoggingLevel.INFO, '*** applysequenceList: ' + applysequenceList);
        if(applysequenceList.size() > 0){
            if(queueList.size() + applysequenceList.size() > 9000){
                throw new ControllerUtil.myException('当前数据量过大，请到主题分配页面进行单条数据排队操作');
            }
            Map<String,List<Rental_Apply_Sequence__c>> modelSequenceMap = new Map<String,List<Rental_Apply_Sequence__c>>();
            for(Rental_Apply_Sequence__c rasequence:applysequenceList){
                if(!modelSequenceMap.containsKey(rasequence.ExternalKey__c)){
                    modelSequenceMap.put(rasequence.ExternalKey__c,new List<Rental_Apply_Sequence__c>());
                }
                modelSequenceMap.get(rasequence.ExternalKey__c).add(rasequence);
            }
            System.debug(LoggingLevel.INFO, '*** modelSequenceMap: ' + modelSequenceMap);
            for(String key: modelSequenceMap.keySet()){
                List<Rental_Apply_Sequence__c> sequenceList = modelSequenceMap.get(key);
               System.debug(LoggingLevel.INFO, '*** sequenceList: ' + sequenceList);
                if(isSinglekey(sequenceList)){
                    for(Rental_Apply_Sequence__c sequeuece:sequenceList){
                        sequeuece.Series_No__c = sequeuece.Apply_Set_Detail__r.Queue_Number__c;
                        updateSequenceList.add(sequeuece);
                    }
                    
                }
            }
            FixtureUtil.withoutUpdate(updateSequenceList);
        }
        
    }


    public void startQueue(String queuetype){
        System.debug(LoggingLevel.INFO, '*** queuetype: ' + queuetype);
        List<Rental_Apply_Equipment_Set_Detail__c> raesdObjs = getdetailList(viewList,parentObj);
        Boolean sameCampaignType = false;
        // 2022014 ljh update start
        // if(parentObj.CampaignType__c == oldCampaignType){
        
        String locationEmail = FixtureUtil.locationMap.get(bieCunFangDi);
         System.debug(LoggingLevel.INFO, '*** locationEmail: ' + locationEmail);
        if(locationEmail!=null && !locationEmail.equalsIgnoreCase(parentObj.Loaner_centre_mail_address__c)){
            throw new ControllerUtil.myException('无权限操作当前单据进行排队！');
        } 

        if((String.isBlank(parentObj.CampaignType__c) && String.isBlank(oldCampaignType))
        || (!String.isBlank(parentObj.CampaignType__c) && !String.isBlank(oldCampaignType) && parentObj.CampaignType__c == oldCampaignType)
        ){
        // 2022014 ljh update end
            sameCampaignType = true;
        }
        if(queuetype == '默认排队'){
            if(changeCampaignType){
                List<String> raesdIds = new List<String>();
                for(Rental_Apply_Equipment_Set_Detail__c raesd:raesdObjs){
                    raesdIds.add(raesd.Id);
                }
                List<Rental_Apply_Equipment_Set_Detail__c> oldquenlist = [SELECT Id, Rental_Apply_Equipment_Set__c, Asset__c,Rental_Apply_Equipment_Set__r.Fixture_Set__r.Product_Type__c,
                                                                       FSD_Fixture_Model_No__c, Fixture_Model_No_text__c,Rental_Apply__r.demo_purpose2__c,Queue_Day__c,ExternalKey__c,
                                                                       Is_Body__c, FSD_Is_OneToOne__c, Select_Time__c,Rental_Apply__r.EquipmentGuaranteeFlg__c,Allow_Adjust_Queue_Flag__c,
                                                                       Cancel_Select__c, Fixture_Model_No_F__c, Queue_Number__c, Internal_asset_location__c,Fixture_Model_No__c,Rental_Apply__c,
                                                                       Internal_asset_location_before__c,Salesdepartment__c, Product_category_F__c, Product_category_text__c,Equipment_Type_text__c,
                                                                       Salesdepartment_before__c,Rental_Apply__r.Request_shipping_day__c,QuenType__c,IsAdjust__c,Rental_Apply__r.Request_approval_time__c,
                                                                       Queue_Time_F__c,IndexFromUniqueKey__c,Rental_Apply_Equipment_Set__r.IndexFromUniqueKey__c,
                                                                        // 20220105 ljh add ueue_Time_F__c,IndexFromUniqueKey__c,
                                                                       Equipment_Type__c, Rental_Apply__r.Internal_asset_location_F__c,Cancel_Reason__c,Loaner_cancel_reason__c,
                                                                       // 备品智能化项目对应 20231122 by lc Start
                                                                       Rental_Apply__r.OPD_OrderNum__c,Rental_Apply__r.OPD_AdjustmentOrderNum_Flag__c,
                                                                       // 备品智能化项目对应 20231122 by lc End
                                                                       Loaner_cancel_Remarks__c ,Rental_Apply_Equipment_Set__r.Name
                                                                FROM Rental_Apply_Equipment_Set_Detail__c
                                                                WHERE Rental_Apply__c =:parentObj.Id
                                                                AND Id NOT IN:raesdIds
                                                                AND QuenType__c = '默认排队'
                                                                AND Queue_Number__c > 0
                                                                AND Cancel_Select__c = false
                                                                AND Is_Body__c = true 
                                                                FOR Update];
                raesdObjs.addAll(oldquenlist);
            }else{
                if(String.isNotEmpty(oldCampaignType)){
                    parentObj.CampaignType__c = oldCampaignType;
                }
            }
            update parentObj;
        }
        
        List<String> modelList = new List<String>();
        List<String> departmentsList = new List<String>();
        List<String> departmentList = new List<String>();
        List<String> locationList = new List<String>();
        List<String> categoryList = new List<String>();
        List<String> equipmentList = new List<String>();
        List<String> equipmentsList = new List<String>();
        List<String> locationsetList = new List<String>();
        List<String> sequencekeylist = new List<String>();
        List<String> detailIds = new List<String>();
        List<String> queuekeyList = new List<String>();
        // Map<String,KeyObj> keyObjMap = new Map<String,KeyObj>();
        Map<String,Integer> keyMap = new Map<String,Integer>();

        List<String> changeddetailIds = new List<String>();
        List<Rental_Apply_Sequence__c> allsequenceList = new List<Rental_Apply_Sequence__c>();
        Map<String,List<Rental_Apply_Equipment_Set_Detail__c>> detailMap = new Map<String,List<Rental_Apply_Equipment_Set_Detail__c>>();
        List<String> queueIds = new List<String>();
        List<Rental_Apply_Equipment_Set_Detail__c> updateList = new List<Rental_Apply_Equipment_Set_Detail__c>();
        List<FixtureUtil.SetDetailWrapper> detailWrappers = new List<FixtureUtil.SetDetailWrapper>();
        for(Rental_Apply_Equipment_Set_Detail__c raesd:raesdObjs){
            detailWrappers.add(new FixtureUtil.SetDetailWrapper(raesd));
        }
        detailWrappers.sort();
        raesdObjs = new List<Rental_Apply_Equipment_Set_Detail__c>();
        for(FixtureUtil.SetDetailWrapper wrapper:detailWrappers){
            raesdObjs.add(wrapper.detail);
        }

        for(Rental_Apply_Equipment_Set_Detail__c raesd:raesdObjs){
            String oldKey = raesd.ExternalKey__c;
            String index = applysetMap.get(raesd.Rental_Apply_Equipment_Set__c);
            if(String.isBlank(index)){
                index = '0';
            }
            System.debug(LoggingLevel.INFO, '*---** index: ' + index+'~'+sameCampaignType);
            System.debug(LoggingLevel.INFO, '*** oldCampaignType: ' + oldCampaignType);
            System.debug(LoggingLevel.INFO, '*** parentObj.CampaignType__c: ' + parentObj.CampaignType__c);
            if(queuetype == '默认排队' && raesd.QuenType__c == '默认排队' && raesd.Queue_Number__c > 0 && raesd.Queue_Day__c != null && sameCampaignType){
                throw new ControllerUtil.myException('第' + index + '行 '+ raesd.Fixture_Model_No__c +' 型号已参与默认排队');
            }
            String modelType = raesd.Rental_Apply_Equipment_Set__r.Fixture_Set__r.Product_Type__c;
            if((parentObj.demo_purpose2__c == '试用（无询价）' || parentObj.demo_purpose2__c == '试用（有询价）'
                    || parentObj.demo_purpose2__c == '已购待货' || parentObj.demo_purpose2__c == '新产品评价') && modelType == '新产品' && queuetype == '特殊排队'){
                throw new ControllerUtil.myException('第' + index + '行 '+ raesd.Fixture_Model_No__c +' 不能参与特殊排队');
            }
            if(modelType == null && queuetype == '默认排队' && (parentObj.demo_purpose2__c == '试用（无询价）' || parentObj.demo_purpose2__c == '试用（有询价）'
                    || parentObj.demo_purpose2__c == '已购待货' || parentObj.demo_purpose2__c == '新产品评价' || (parentObj.demo_purpose2__c == '学会展会' && parentObj.CampaignType__c == '营业本部学会'))){
                throw new ControllerUtil.myException('第' + index + '行 '+ raesd.Fixture_Model_No__c +' 备品产品类型为空！');
            }
            KeyObj obj = null;
            System.debug(LoggingLevel.INFO, '*00** index: ' + index);
            if(queuetype == '默认排队'){
                ApplyObj applyObj = new ApplyObj();
                applyObj.location = parentObj.Internal_asset_location_F__c;
                applyObj.productType = parentObj.Product_category__c;
                applyObj.salesdepartment = parentObj.Salesdepartment__c ;
                applyObj.purpose1 = parentObj.Demo_purpose1__c;
                applyObj.purpose2 = parentObj.demo_purpose2__c;
                System.debug(LoggingLevel.INFO, '*** parentObj.CampaignType__c: ' + parentObj.CampaignType__c);
                applyObj.campaignType = parentObj.CampaignType__c;
                obj = getdefultInfo(raesd,applyObj,bieCunFangDi);
            }else{
                obj = getSpecialInfo(raesd,parentObj,salesdepartments,equipmenttypes);
            }
            System.debug(LoggingLevel.INFO, '*11** index: ' + index);
            queueIds.add(raesd.Id);
            // keyObjMap.put(raesd.Id,obj);
            modelList.add(obj.model);
            departmentsList.addAll(obj.salesdepartmentList);
            locationList.add(obj.location);
            equipmentsList.addAll(obj.equipmentList);
            categoryList.addAll(obj.productTypes);
            sequencekeylist.addAll(obj.sequencekeylist);
            System.debug(LoggingLevel.INFO, '*22** index: ' + index);
            for(String sequencekey:obj.sequencekeylist){
                System.debug(LoggingLevel.INFO, '*** sequencekey: ' + sequencekey);
                System.debug(LoggingLevel.INFO, '*** index: ' + index);
                System.debug(LoggingLevel.INFO, '*** keyMap: ' + keyMap);
                keyMap.put(sequencekey,Integer.valueOf(index));
            }
            String key = obj.model + obj.location + obj.salesdepartments + obj.equipmenttypes + obj.productType;
            if(key == oldKey){
                changeddetailIds.add(raesd.Id);
            }
            // 备品配套明细型号(借出时)
            raesd.Fixture_Model_No_text__c = obj.model;
            // 所在地区(本部) 借出时
            raesd.Salesdepartment_before__c = obj.salesdepartments;
            
            // 产品分类(GI/SP)(借出时)
            raesd.Product_category_text__c = obj.productType;
            // 备品分类(借出时)
            raesd.Equipment_Type_text__c = obj.equipmenttypes;
            // 备品存放地(借出时)
            raesd.Internal_asset_location_before__c = obj.location;
            raesd.ExternalKey__c = key;
            raesd.QuenType__c = queuetype;

            // raesd.Queue_User__c   = UserInfo.getUserId();
            raesd.Queue_Day__c    = Date.today();
            raesd.Queue_Time__c   = getCurrentTime();
            raesd.Select_Time__c  = null;
            raesd.Asset__c        = null;
            // 已出库指示的排队后清除出库指示信息
            raesd.Shipment_request_time2__c = null;
            raesd.Shipment_request__c = false;
            raesd.Queue_User__c   = UserInfo.getUserId();
            raesd.Queue_Number__c = -1;
            raesd.IsAdjust__c     = false;
            raesd.Select_Time__c  = null;
            raesd.Asset__c        = null;
            // 已出库指示的排队后清除出库指示信息
            raesd.Shipment_request_time2__c = null;
            raesd.Shipment_request__c = false;

            // OLY_OCM-243 追加字段对应 备品管理编码(借出时) 排队时清除与asset相连的借出时相关的字段
            raesd.EquipmentSet_Managment_Code_text__c = null;
            // 机身编号（借出时）
            raesd.SerialNumber_text__c = null;
            // 备品成本(借出时)
            raesd.Asset_cost_del_before__c = null;
            detailIds.add(raesd.Id);
            updateList.add(raesd);
            // KeyObj obj = keyObjMap.get(raesd.Id);
            System.debug(LoggingLevel.INFO, '*** KeyObj obj: ' + obj);
            for(String sales:obj.salesdepartmentList){
            
                for(String equip:obj.equipmentList){
                    for(String type:obj.productTypes){
                        Rental_Apply_Sequence__c newSequence = new Rental_Apply_Sequence__c();
                        newSequence.ExternalKey__c = obj.model + obj.location + sales + equip + type;
                        newSequence.Demo_Purpose2__c = raesd.Rental_Apply__r.demo_purpose2__c;
                        newSequence.Apply_Set_Detail__c = raesd.Id;
                        newSequence.Series_No__c = raesd.Queue_Number__c;
                        newSequence.Salesdepartment__c = sales;
                        newSequence.Product_category__c = type;
                        newSequence.Rental_Apply__c = raesd.Rental_Apply__c;
                        newSequence.Internal_asset_location__c = obj.location;
                        newSequence.Fixture_Model_No__c = obj.model;
                        newSequence.Equipment_Type__c = equip;
                        
                        allsequenceList.add(newSequence);
                       
                    }
                }
            }
           
            queuekeyList.add(key);
            departmentList.addAll(transferStringToList(obj.salesdepartments));
            equipmentList.addAll(transferStringToList(obj.equipmenttypes));
        }
        System.debug(LoggingLevel.INFO, '**1111* updateList: ' + updateList);
        System.debug(LoggingLevel.INFO, '*** queueIds: ' + queueIds);
        System.debug(LoggingLevel.INFO, '*** modelList: ' + modelList);
        System.debug(LoggingLevel.INFO, '*** departmentsList: ' + departmentsList);
        System.debug(LoggingLevel.INFO, '*** locationList: ' + locationList);
        System.debug(LoggingLevel.INFO, '*** categoryList: ' + categoryList);
        System.debug(LoggingLevel.INFO, '*** equipmentList: ' + equipmentList);
        String soqlStr = 'Select Id, Last_Reserve_RAES_Detail__c, Fixture_Model_No_F__c, You_Xiao_Ku_Cun__c,'
                    + ' Salesdepartment__c, SalesProvince__c, Product_category__c, Equipment_Type__c, Internal_asset_location__c'
                     + ' From Asset '
                    + ' Where Asset_Owner__c = \'Olympus\''
                    + ' and Asset_loaner_category__c != \'耗材\''
                    + ' and RecordTypeId = \''+System.label.access_1+'\''
                    + ' and Delete_Flag__c = False'
                    + ' and Freeze_sign_Abandoned_Flag__c = False'
                    + ' and Product2.Fixture_Model_No_T__c IN:modelList'
                    + ' and Salesdepartment__c IN: departmentsList'
                    + ' and Internal_asset_location__c IN: locationList'
                    + ' and Product_category__c IN:categoryList'
                    + ' and Equipment_Type__c IN: equipmentList'
                    + ' and ' + FixtureUtil.getAssetSoqlBase()
                    + ' order by Id';
        // 检索符合这四个别字段和同一产品型号的数据存在与否
        System.debug(LoggingLevel.INFO, '*** soqlStr: ' + soqlStr);
        List<Asset> aSetCheck = Database.query(soqlStr);
        System.debug(LoggingLevel.INFO, '*** keyMap: ' + JSON.serialize(keyMap));
        for (Asset ass : aSetCheck) {
            String key = ass.Fixture_Model_No_F__c + ass.Internal_asset_location__c + ass.Salesdepartment__c + ass.Equipment_Type__c + ass.Product_category__c;
            System.debug(LoggingLevel.INFO, '*** key: ' + key);
            if(keyMap.containsKey(key)){
                if (ass.Last_Reserve_RAES_Detail__c == null && ass.You_Xiao_Ku_Cun__c > 0) {
                    throw new ControllerUtil.myException('第'+ keyMap.get(key)+'行 '+ ass.Fixture_Model_No_F__c +' 有可以分配主体不需要排队');
                }
            }
            
        }
        System.debug(LoggingLevel.INFO, '*** queuekeyList: ' + queuekeyList);

        Map<String,List<Rental_Apply_Equipment_Set_Detail__c>> queueMap = new Map<String,List<Rental_Apply_Equipment_Set_Detail__c>>();
       List<Rental_Apply_Equipment_Set_Detail__c> queueList = [SELECT Id, Rental_Apply_Equipment_Set__c, Asset__c,Rental_Apply_Equipment_Set__r.Fixture_Set__r.Product_Type__c,
                                                                   FSD_Fixture_Model_No__c, Fixture_Model_No_text__c,Externalkey__c,Rental_Apply__r.demo_purpose2__c,Equipment_Type_text__c,
                                                                   Is_Body__c, FSD_Is_OneToOne__c, Select_Time__c,Rental_Apply__r.EquipmentGuaranteeFlg__c,Fixture_Model_No__c,
                                                                   Cancel_Select__c, Fixture_Model_No_F__c, Queue_Number__c, Internal_asset_location__c,IsAdjust__c,Queue_Day__c,Queue_Time__c,
                                                                   Salesdepartment__c, Product_category_F__c, Equipment_Type__c, Rental_Apply__r.Internal_asset_location_F__c,
                                                                   Queue_Time_F__c,IndexFromUniqueKey__c,Rental_Apply_Equipment_Set__r.IndexFromUniqueKey__c,
                                                                   // 20220105 ljh add Queue_Time_F__c,IndexFromUniqueKey__c,
                                                                   // 备品智能化项目对应 20231122 by lc Start
                                                                   Rental_Apply__r.OPD_OrderNum__c,Rental_Apply__r.OPD_AdjustmentOrderNum_Flag__c,
                                                                   // 备品智能化项目对应 20231122 by lc End
                                                                   Cancel_Reason__c,Loaner_cancel_reason__c,Loaner_cancel_Remarks__c ,Rental_Apply__r.Request_shipping_day__c,Rental_Apply__r.Request_approval_time__c
                                                            FROM Rental_Apply_Equipment_Set_Detail__c
                                                            WHERE Externalkey__c IN :queuekeyList
                                                            AND Cancel_Select__c = false
                                                            AND Is_Body__c = true
                                                            AND Id NOT IN:queueIds
                                                            AND Queue_Number__c > 0
                                                            FOR Update ];

        updateList.addAll(queueList);
        System.debug(LoggingLevel.INFO, '***old updateList: ' + updateList.size());
        System.debug(LoggingLevel.INFO, '***old updateList.detail: ' + updateList);
        updateList = Batch_QueueAllDetail.getSortDetailList(updateList);
        System.debug(LoggingLevel.INFO, '*** updateList: ' + updateList.size());
        System.debug(LoggingLevel.INFO, '*** updateList.detail: ' + updateList);
        FixtureUtil.withoutUpdate(updateList);
        
        System.debug(LoggingLevel.INFO, '*** allsequenceList: ' + allsequenceList.size());
        List<Rental_Apply_Sequence__c> oldSequenceList = [SELECT Id,ExternalKey__c,Fixture_Model_No__c FROM Rental_Apply_Sequence__c
                                                        WHERE Apply_Set_Detail__c IN:detailIds];
        System.debug(LoggingLevel.INFO, '*** oldSequenceList.size(): ' + oldSequenceList.size());
        Set<String> keys = new Set<String>();
        for(Rental_Apply_Sequence__c se:oldSequenceList){
            keys.add(se.ExternalKey__c);
        }
        Integer count = [SELECT count() FROM Rental_Apply_Sequence__c WHERE ExternalKey__c IN:keys];
        if(updateList.size() + count + oldSequenceList.size() > 9900){
            throw new ControllerUtil.myException('当前排队数据量过大，请选择单个主体操作');
        }
        List<Rental_Apply_Sequence__c> olddleteSequenceList = [SELECT Id,ExternalKey__c,Fixture_Model_No__c FROM Rental_Apply_Sequence__c
                                                        WHERE Apply_Set_Detail__c IN:changeddetailIds];

        FixtureUtil.withoutDelete(olddleteSequenceList);
        if(updateList.size() + count + oldSequenceList.size() + allsequenceList.size() > 9900){
            throw new ControllerUtil.myException('当前排队数据量过大，请选择单个主体操作');
        }
        FixtureUtil.withoutInsert(allsequenceList);
        List<String> newSequenceIds = new List<String>();
        for(Rental_Apply_Sequence__c se:allsequenceList){
            newSequenceIds.add(se.Id);
        }
        allsequenceList = [SELECT Id,ExternalKey__c,Demo_Purpose2__c,Rental_Apply__r.Request_shipping_day__c,Rental_Apply__r.EquipmentGuaranteeFlg__c,
                                                        Apply_Set_Detail__c,Apply_Set_Detail_ExternalKey__c,Rental_Apply__r.Request_approval_time__c,Apply_Set_Detail__r.IsAdjust__c,
                                                        Series_No__c,Salesdepartment__c,Product_category__c,Apply_Set_Detail__r.Queue_Day__c,Apply_Set_Detail__r.Queue_Time__c,
                                                        Rental_Apply__c,Internal_asset_location__c,Series_Unequal_Queue_Flag__c,
                                                        Apply_Set_Detail__r.Queue_Number__c,Apply_Set_Detail__r.Queue_Time_F__c,Apply_Set_Detail__r.IndexFromUniqueKey__c,
                                                        Apply_Set_Detail__r.Rental_Apply_Equipment_Set__r.IndexFromUniqueKey__c,
                                                        // 20220105 ljh add Apply_Set_Detail__r.Queue_Time_F__c,Apply_Set_Detail__r.IndexFromUniqueKey__c,
                                                        // 备品智能化项目对应 20231122 by lc Start
                                                        Rental_Apply__r.OPD_OrderNum__c,
                                                        // 备品智能化项目对应 20231122 by lc End
                                                        Fixture_Model_No__c,Equipment_Type__c
                                                        FROM Rental_Apply_Sequence__c
                                                        WHERE Id IN:newSequenceIds
                                                        ];

        List<String> nodusequencekeylist = new List<String>(new Set<String>(sequencekeylist));
        System.debug(LoggingLevel.INFO, '*** nodusequencekeylist: ' + JSON.serialize(nodusequencekeylist));
        
        System.debug(LoggingLevel.INFO, '*** nodusequencekeylist.size(): ' + nodusequencekeylist.size());
        if(nodusequencekeylist.size() > 950){
            throw new ControllerUtil.myException('当前排队数据量过大，请选择单个主体操作');
        }
        List<Rental_Apply_Sequence__c> updateSequenceList = new List<Rental_Apply_Sequence__c>();
        List<Rental_Apply_Sequence__c> newSequenceList = new List<Rental_Apply_Sequence__c>();
        List<Rental_Apply_Sequence__c> applysequenceList = [SELECT Id,ExternalKey__c,Demo_Purpose2__c,Rental_Apply__r.Request_shipping_day__c,Rental_Apply__r.EquipmentGuaranteeFlg__c,
                                                        Apply_Set_Detail__c,Apply_Set_Detail_ExternalKey__c,Rental_Apply__r.Request_approval_time__c,Apply_Set_Detail__r.IsAdjust__c,
                                                        Series_No__c,Salesdepartment__c,Product_category__c,Apply_Set_Detail__r.Queue_Day__c,Apply_Set_Detail__r.Queue_Time__c,
                                                        Rental_Apply__c,Internal_asset_location__c,Series_Unequal_Queue_Flag__c,
                                                        Apply_Set_Detail__r.Queue_Number__c,Apply_Set_Detail__r.Queue_Time_F__c,Apply_Set_Detail__r.IndexFromUniqueKey__c,
                                                        // 20220105 ljh add Apply_Set_Detail__r.Queue_Time_F__c,Apply_Set_Detail__r.IndexFromUniqueKey__c,
                                                        // 备品智能化项目对应 20231122 by lc Start
                                                        Rental_Apply__r.OPD_OrderNum__c,
                                                        // 备品智能化项目对应 20231122 by lc End
                                                        Apply_Set_Detail__r.Rental_Apply_Equipment_Set__r.IndexFromUniqueKey__c,
                                                        Fixture_Model_No__c,Equipment_Type__c
                                                        FROM Rental_Apply_Sequence__c
                                                        WHERE ExternalKey__c IN: nodusequencekeylist
                                                        AND Series_No__c > 0
                                                        AND Invalid_Flag__c = false
                                                        FOR Update 
                                                        ];
        // System.debug(LoggingLevel.INFO, '*** JSON.serialize(applysequenceList): ' + JSON.serialize(applysequenceList));
        newSequenceList.addAll(applysequenceList);
        newSequenceList.addAll(allsequenceList);
        System.debug(LoggingLevel.INFO, '*** newSequenceList.size(): ' + newSequenceList.size());
        newSequenceList = Batch_QueueAllDetail.getSortSequenceList(newSequenceList);
        if(updateList.size() + count + oldSequenceList.size() + allsequenceList.size() + newSequenceList.size() > 9900){
            throw new ControllerUtil.myException('当前排队数据量过大，请选择单个主体操作');
        }
        System.debug(LoggingLevel.INFO, '*** newSequenceList: ' + newSequenceList);
        FixtureUtil.withoutUpsertObjects(newSequenceList);

    }

    public Boolean allSpecialQueue(){
        List<Rental_Apply_Equipment_Set_Detail__c> details = [SELECT Id, Rental_Apply_Equipment_Set__c, Asset__c,Rental_Apply_Equipment_Set__r.Fixture_Set__r.Product_Type__c,
                                                                       FSD_Fixture_Model_No__c, Fixture_Model_No_text__c,Rental_Apply__r.demo_purpose2__c,Queue_Day__c,ExternalKey__c,
                                                                       Is_Body__c, FSD_Is_OneToOne__c, Select_Time__c,Rental_Apply__r.EquipmentGuaranteeFlg__c,Allow_Adjust_Queue_Flag__c,
                                                                       Cancel_Select__c, Fixture_Model_No_F__c, Queue_Number__c, Internal_asset_location__c,Fixture_Model_No__c,Rental_Apply__c,
                                                                       Internal_asset_location_before__c,Salesdepartment__c, Product_category_F__c, Product_category_text__c,Equipment_Type_text__c,
                                                                       Salesdepartment_before__c,Rental_Apply__r.Request_shipping_day__c,QuenType__c,IsAdjust__c,Rental_Apply__r.Request_approval_time__c,
                                                                       Equipment_Type__c, Rental_Apply__r.Internal_asset_location_F__c,Cancel_Reason__c,Loaner_cancel_reason__c,Loaner_cancel_Remarks__c 
                                                                FROM Rental_Apply_Equipment_Set_Detail__c
                                                                WHERE Rental_Apply__c =:parentObj.Id
                                                                ];
        for(Rental_Apply_Equipment_Set_Detail__c detail:details){
            if(detail.QuenType__c == '默认排队'){
                return false;
            }
        }
        return true;
    }

    public static Boolean isSinglekey(List<Rental_Apply_Sequence__c> sequenceList){
        String externalKey = sequenceList[0].Apply_Set_Detail_ExternalKey__c;
        for(Rental_Apply_Sequence__c sequeuece:sequenceList){
            if(externalKey != sequeuece.Apply_Set_Detail_ExternalKey__c){
                return false;
            }
        }
        return true;
    }


    public static Map<String,String> applysetMap = new Map<String,String>();
    public List<Rental_Apply_Equipment_Set_Detail__c> getdetailList(List<WrapperInfo> viewList,Rental_Apply__c parentObj){
        List<String> applysetIds = new List<String>();
        Integer indexNumQ = 1;// 20220104 ljh add start
        for(Integer i = 0;i < viewList.size();i++){
            WrapperInfo prInfo = viewList.get(i);
        // for (WrapperInfo prInfo : viewList) {
            Rental_Apply_Equipment_Set__c robj = (Rental_Apply_Equipment_Set__c) prInfo.sobj;
            if (prInfo.check) {
                // 20220104 ljh add start
                // 待分配和排队中
                if (robj.First_RAESD_Is_Main__c && String.isNotBlank(robj.First_Status__c) && robj.First_Status__c != '待分配' && robj.First_Status__c != '排队中') {
                    // ***一览**型号不满足条件，无法进行排队
                    throw new ControllerUtil.myException('第' + indexNumQ + '行 '+ robj.First_RAESD_Model_No_F__c +' 不满足条件，无法进行排队');
                }
                // 20220104 ljh add end
                applysetIds.add(robj.Id);
                applysetMap.put(robj.Id,String.valueOf(i+1));
            }
            indexNumQ += 1;// 20220104 ljh add start
        }
        System.debug(LoggingLevel.INFO, '*** applysetMap: ' + applysetMap);
        List<Rental_Apply_Equipment_Set_Detail__c> assignList = [SELECT Id, Rental_Apply_Equipment_Set__c, Asset__c,Rental_Apply_Equipment_Set__r.Fixture_Set__r.Product_Type__c,
                                                                   FSD_Fixture_Model_No__c, Fixture_Model_No_text__c,Rental_Apply__r.demo_purpose2__c,Queue_Day__c,ExternalKey__c,
                                                                   Is_Body__c, FSD_Is_OneToOne__c, Select_Time__c,Rental_Apply__r.EquipmentGuaranteeFlg__c,Allow_Adjust_Queue_Flag__c,
                                                                   Cancel_Select__c, Fixture_Model_No_F__c, Queue_Number__c, Internal_asset_location__c,Fixture_Model_No__c,Rental_Apply__c,
                                                                   Internal_asset_location_before__c,Salesdepartment__c, Product_category_F__c, Product_category_text__c,Equipment_Type_text__c,
                                                                   Salesdepartment_before__c,Rental_Apply__r.Request_shipping_day__c,QuenType__c,IsAdjust__c,Rental_Apply__r.Request_approval_time__c,
                                                                   Equipment_Type__c, Rental_Apply__r.Internal_asset_location_F__c,Cancel_Reason__c,Loaner_cancel_reason__c,
                                                                   Loaner_cancel_Remarks__c ,Rental_Apply_Equipment_Set__r.Name
                                                            FROM Rental_Apply_Equipment_Set_Detail__c
                                                            WHERE Rental_Apply_Equipment_Set__c IN :applysetIds
                                                            AND Cancel_Select__c = false
                                                            AND Is_Body__c = true
                                                            AND (Shipment_Status_Text__c = '暂定分配' OR Shipment_Status_Text__c ='已分配')];
        if(assignList.size() > 0){

            throw new ControllerUtil.myException(applysetMap.get(assignList[0].Rental_Apply_Equipment_Set__c)+'行已经暂定分配或已分配，不能参与排队！');
        }
        List<Rental_Apply_Equipment_Set_Detail__c> raesdObjs = [SELECT Id, Rental_Apply_Equipment_Set__c, Asset__c,Rental_Apply_Equipment_Set__r.Fixture_Set__r.Product_Type__c,
                                                                   FSD_Fixture_Model_No__c, Fixture_Model_No_text__c,Rental_Apply__r.demo_purpose2__c,Queue_Day__c,ExternalKey__c,
                                                                   Is_Body__c, FSD_Is_OneToOne__c, Select_Time__c,Rental_Apply__r.EquipmentGuaranteeFlg__c,Allow_Adjust_Queue_Flag__c,
                                                                   Cancel_Select__c, Fixture_Model_No_F__c, Queue_Number__c, Internal_asset_location__c,Fixture_Model_No__c,Rental_Apply__c,
                                                                   Internal_asset_location_before__c,Salesdepartment__c, Product_category_F__c, Product_category_text__c,Equipment_Type_text__c,
                                                                   Salesdepartment_before__c,Rental_Apply__r.Request_shipping_day__c,QuenType__c,IsAdjust__c,Rental_Apply__r.Request_approval_time__c,
                                                                   Queue_Time_F__c,IndexFromUniqueKey__c,Rental_Apply_Equipment_Set__r.IndexFromUniqueKey__c,
                                                                   // 20220105 ljh add ueue_Time_F__c,IndexFromUniqueKey__c,
                                                                   Equipment_Type__c, Rental_Apply__r.Internal_asset_location_F__c,Cancel_Reason__c,Loaner_cancel_reason__c,
                                                                   // 备品智能化项目对应 20231122 by lc Start
                                                                   Rental_Apply__r.OPD_OrderNum__c,Rental_Apply__r.OPD_AdjustmentOrderNum_Flag__c,
                                                                   // 备品智能化项目对应 20231122 by lc End
                                                                   Loaner_cancel_Remarks__c ,Rental_Apply_Equipment_Set__r.Name
                                                            FROM Rental_Apply_Equipment_Set_Detail__c
                                                            WHERE Rental_Apply_Equipment_Set__c IN :applysetIds
                                                            AND Cancel_Select__c = false
                                                            AND Is_Body__c = true
                                                            AND (Shipment_Status_Text__c = '待分配' OR Shipment_Status_Text__c = '排队中')
                                                            FOR Update];
        if(raesdObjs.size() == 0){
            throw new ControllerUtil.myException('当前无操作数据！');
        }
        return raesdObjs;
    }


    public class KeyObj{
        public String queuekey;
        public List<String> sequencekeyList;
        public String model;
        public String location;
        public String salesdepartments;
        public List<String> salesdepartmentList;
        public String equipmenttypes;
        public List<String> equipmentList;
        public String productType;
        public List<String> productTypes;
    }

    public static KeyObj getdefultInfo(Rental_Apply_Equipment_Set_Detail__c setDetail,ApplyObj applyObj,String bieCunFangDi){
        String modelType = setDetail.Rental_Apply_Equipment_Set__r.Fixture_Set__r.Product_Type__c;
        KeyObj obj = new KeyObj();
        obj.model = setDetail.Fixture_Model_No__c;
        obj.location = applyObj.location;
        obj.productType = applyObj.productType;
        // String location = 
        String equipmenttypes = '';
        String salesdepartments = '';
        if(applyObj.purpose1 == '其他'){
            throw new ControllerUtil.myException('使用目的为其他，不能参与默认排队');
        }else{
            System.debug(LoggingLevel.INFO, '*** applyObj.purpose1: ' + applyObj.purpose1);
            System.debug(LoggingLevel.INFO, '*** applyObj.purpose2: ' + applyObj.purpose2);
            System.debug(LoggingLevel.INFO, 'pageupdated');

            if(applyObj.purpose1 == '产品试用'){
                if(applyObj.purpose2 == '试用（无询价）' || applyObj.purpose2 == '试用（有询价）'
                    || applyObj.purpose2 == '已购待货' || applyObj.purpose2 == '新产品评价'){
                    equipmenttypes = '产品试用';
                    System.debug(LoggingLevel.INFO, '*** modelType:' + modelType);
                    if(modelType == '新产品' || modelType == '重点产品'){
                        salesdepartments = '0.备品中心,' + applyObj.salesdepartment ;
                    }else if(modelType == '非重点产品'){
                        salesdepartments = transferListtoString(applyObj.purpose1,FixtureUtil.bieBenBuOpsMap.get(bieCunFangDi));
                    }
                }else if(applyObj.purpose2 == '学会展会'){
                    System.debug(LoggingLevel.INFO, '*** applyObj.salesdepartment: ' + applyObj.salesdepartment);
                    if(applyObj.salesdepartment.contains('MA本部')){
                        equipmenttypes ='协议借用';
                        salesdepartments = applyObj.salesdepartment;
                    } else if(applyObj.salesdepartment.contains('产品培训')){
                        equipmenttypes = '产品试用';
                        salesdepartments = applyObj.salesdepartment;
                    }else if(!(applyObj.salesdepartment.contains('产品培训') || applyObj.salesdepartment.contains('MA本部'))){
                        System.debug(LoggingLevel.INFO, 'debugflag------------------'+applyObj.campaignType);
                        if(applyObj.campaignType == '全国性学会' || applyObj.campaignType == '春秋两季医疗展'){
                            salesdepartments = '0.备品中心';
                            equipmenttypes = '学会展会';
                        }else if(applyObj.campaignType == '市场本部主办学会'){
                            equipmenttypes = '学会展会';
                            salesdepartments = applyObj.salesdepartment ;
                        }else if(applyObj.campaignType == '营业本部学会'){
                            if(modelType == '新产品' || modelType == '重点产品'){
                                salesdepartments = '0.备品中心,' + applyObj.salesdepartment ;
                            }else if(modelType == '非重点产品'){
                                salesdepartments = transferListtoString(applyObj.purpose1,FixtureUtil.bieBenBuOpsMap.get(bieCunFangDi));
                            }
                            equipmenttypes = '产品试用';
                        }else if(applyObj.campaignType == '服务培训/学会'){
                            salesdepartments = transferListtoString(applyObj.purpose1,FixtureUtil.bieBenBuOpsMap.get(bieCunFangDi));
                            equipmenttypes = '维修代用（一般维修）';
                        }
                    } else {
                        salesdepartments = applyObj.salesdepartment;
                        equipmenttypes = setDetail.Equipment_Type_F__c;
                    }

                }
            }else if(applyObj.purpose1 == '维修代用'){
                System.debug(LoggingLevel.INFO, '*** bieCunFangDi: ' + bieCunFangDi);
                salesdepartments = transferListtoString(applyObj.purpose1 ,FixtureUtil.bieBenBuOpsMap.get(bieCunFangDi));
                if(applyObj.purpose2 == '保修用户' || applyObj.purpose2 == '索赔QIS'|| applyObj.purpose2 == '市场多年保修'){
                    
                    equipmenttypes = '维修代用（保修合同）,维修代用（一般维修）';
                }else {
                    equipmenttypes ='维修代用（一般维修）';
                }

            }else if(applyObj.purpose1 == '协议借用'){
                equipmenttypes ='协议借用';
                salesdepartments = '9.MA本部';
            }
        }
        System.debug(LoggingLevel.INFO, '*** salesdepartments: ' + salesdepartments);
        System.debug(LoggingLevel.INFO, '*** equipmenttypes: ' + equipmenttypes);
        obj.equipmenttypes = equipmenttypes;
        obj.salesdepartments = salesdepartments;
        getsequencekeyList(obj);
        // System.debug('***zheli:'+obj);
        return obj;
    }

    public static KeyObj getSpecialInfo(Rental_Apply_Equipment_Set_Detail__c setDetail,Rental_Apply__c parentObj,String salesdepartments,String equipmenttypes){
        
        KeyObj obj = new KeyObj();

        obj.model = setDetail.Fixture_Model_No__c;
        obj.location = parentObj.Internal_asset_location_F__c;
        obj.productType = parentObj.Product_category_Sys__c =='All'?'GI,SP':parentObj.Product_category_Sys__c;
        obj.equipmenttypes = equipmenttypes;
        obj.salesdepartments = salesdepartments;
        getsequencekeyList(obj);
        return obj;

    }

    public static KeyObj getSequenceInfo(Rental_Apply_Equipment_Set_Detail__c setDetail){
        KeyObj obj = new KeyObj();
        
        obj.model = setDetail.Fixture_Model_No_text__c;
        obj.location = setDetail.Internal_asset_location_before__c;
        obj.productType = setDetail.Product_category_text__c;
        obj.equipmenttypes = setDetail.Equipment_Type_text__c;
        obj.salesdepartments = setDetail.Salesdepartment_before__c;
        getsequencekeyList(obj);
        // System.debug(LoggingLevel.INFO, '*** obj: ' + obj);
        return obj;
    }

    public static void getsequencekeyList(KeyObj obj){

        
        List<String> sequencekeylist = new List<String>();
        obj.salesdepartmentList = transferStringToList(obj.salesdepartments);
        obj.salesdepartmentList.sort();
        obj.equipmentList = transferStringToList(obj.equipmenttypes);
        obj.equipmentList.sort();
        obj.productTypes = transferStringToList(obj.productType);
        obj.productTypes.sort();
        obj.salesdepartments = '';
        obj.equipmenttypes = '';
        obj.productType = '';
        for(String sales:obj.salesdepartmentList){
            if(!obj.salesdepartments.contains(sales)){
                obj.salesdepartments += sales + ',';
            }
            for(String equip:obj.equipmentList){
                if(!obj.equipmenttypes.contains(equip)){
                    obj.equipmenttypes += equip + ',';
                }
                for(String type:obj.productTypes){
                    if(!obj.productType.contains(type)){
                        obj.productType += type + ',';
                    }
                    
                    String key = obj.model + obj.location + sales + equip + type;
                    sequencekeylist.add(key);
                }
            }
        }
        obj.salesdepartments = obj.salesdepartments.removeEnd(',');
        obj.equipmenttypes = obj.equipmenttypes.removeEnd(',');
        obj.productType = obj.productType.removeEnd(',');
        
        obj.sequencekeyList = sequencekeylist;
        // System.debug(LoggingLevel.INFO, '*** obj: ' + obj);
    }


    public static String transferListtoString(String purpose1,List<SelectOption> options){
        String result = '';
        for(SelectOption op:options){
            if(String.isNotEmpty(op.getValue())){
                if(purpose1 == '产品试用' || purpose1 == '维修代用'){
                    if(!op.getValue().contains('MA本部') && !op.getValue().contains('产品培训')){
                        result += op.getValue() + ',';
                    }
                }
                else{
                    result += op.getValue() + ',';
                }
            }
            
        }
        result = result.removeEnd(',');
        return result;
    }


    public static List<String> transferStringToList(String str){
        // System.debug(LoggingLevel.INFO, '*** str: ' + str);
        List<String> strList = new List<String>();
        if(str.contains(',')){
            strList = str.split(',');
        }else{
            strList.add(str);
        }
        for(Integer i = strList.size()-1;i >= 0 ; i --){
            if(String.isEmpty(strList.get(i))){
                strList.remove(i);
            }
        }
        return strList;
    }

    //获取当前时间 getCurrentTime
    public static Time getCurrentTime() {
        DateTime now = DateTime.now();
        System.debug('GMT: ' + now);
        Integer hours = now.hour();
        Integer minutes = now.minute();
        Integer seconds = now.second();
        Integer milliseconds = now.millisecond();
        System.debug('local time: ' + hours + ':' + minutes + ':' + seconds + ':' + milliseconds);
        Time currentTime = Time.newInstance(hours, minutes, seconds, milliseconds);
        return currentTime;
    }

    public class ApplyObj{
        public String location;
        public String productType;
        public String salesdepartment;
        public String purpose1;
        public String purpose2;
        public String campaignType;
    }

    
}