/**
 * 附属品追加の設定
 * Test
 * AccessoryAddControllerTest
 * RentalFixtureManage1Test
 */
public with sharing class AccessoryAddController extends CreateRelationListPagingCtrlBase {
    public override Integer getSearchNumMax() {
        //各ページに制御あれば、最大件数を指定する
        // searchNumMax = Integer.valueOf(Label.Product_Select_Limit);
        // searchNumMax = 20;
        pagesize = '20';
        return searchNumMax;
    }

    /* 選択されたデータ取得用Soql　Fromから*/
    public override String getSelectedDataSql() {
        System.debug('getSelectedDataSql parentId:' + parentId);
        System.debug('getSelectedDataSql rsdObjId:' + this.rsdObjId);
        // オブジェクトAPI名
        selectedDataSql = ' From Rental_Apply_Equipment_Set_Detail__c';
        selectedDataSql += ' where Rental_Apply_Equipment_Set__c = \'' + String.escapeSingleQuotes(parentId) + '\'';
        selectedDataSql += '   and Id = \'' + String.escapeSingleQuotes(rsdObjId) + '\'';
        selectedDataSql += '   and Is_Body__c = false';
        selectedDataSql += '   and (ApplyPersonAppended_F__c = false OR (' ;
        selectedDataSql += '   ApplyPersonAppended_F__c = true AND (Add_Request_approval_time__c != null OR Select_Time__c != null)))';
        selectedDataSql += '   and Cancel_Select__c = False';
        selectedDataSql += ' order by Id ASC nulls last';
        return selectedDataSql;
    }

    // 検索元対象オブジェクトAPI名
    public override String getOriginObjName() {
        // オブジェクトAPI名
        originObjName = 'Asset';
        return originObjName;
    }
    public override String getOriginObjColumns() {
        // 項目セット
        originObjColumns =  'Id';
        return originObjColumns;
    }

    public override String getObjName() {
        // オブジェクトAPI名
        objName = 'Rental_Apply_Equipment_Set_Detail__c';
        return objName;
    }
    public override String getColumnLeftFieldSetName() {
        // 左の項目セット
        columnLeftFieldSetName = '';
        return columnLeftFieldSetName;
    }
    public override String getColumnRightFieldSetName() {
        // 右の項目セット
        columnRightFieldSetName = 'AccessoryAdd_RightFieldSet';
        return columnRightFieldSetName;
    }

    public override List<String> getColumnFieldList() {
        // strColumus 里加 field
        // FixtureUtil#raesdGroupBy()の項目も必要
        return new List<String>{'Id', 'Rental_Apply_Equipment_Set__c', 'FSD_Id__c',
                'Select_Time__c', 'IndexFromUniqueKey__c', 'FSD_Fixture_Model_No__c',
                'Is_Body_F__c', 'SalesProvince__c', 'Fixture_Model_No_F__c', 'Is_Body__c',
                'Rental_Apply__c', 'Rental_Apply__r.Salesdepartment__c', 'Intervention_Reason__c',
                'Rental_Apply__r.Equipment_Type_F__c', 'Rental_Apply__r.Internal_asset_location_F__c',
                'Rental_Apply__r.Salesdept__c', 'Rental_Apply__r.Product_category__c',
                'Rental_Apply__r.demo_purpose2__c','Rental_Apply__r.Follow_UP_Opp__r.Shipping_Finished_Day_Func__c',
                'Rental_Apply__r.next_action__c','Rental_Apply__r.QIS_number__r.ReplaceDeliveryDate__c'};
    }
    // getObjName 连 getOriginObjName 的 FK
    public override String getFKColumnField() {
        return 'Asset__c';
    }

    public override String getRecordTypeId() {
        //ページレイアウトを収得するのレコードタイプ
        recordTypeId = '';
        return recordTypeId;
    }

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

        if(getIsNeedRunSearch()){
            System.debug('getIsNeedRunSearch enter');
            sqlWhereStr = this.makeSoql(keywdSort);
            System.debug('sqlWhereStr is:' + sqlWhereStr);
        }

        return sqlWhereStr;

    }

    public override String getOrderbyStr() {
        return 'order by Consumable_Guaranteen_end__c ASC NULLS LAST, Ji_Zhong_Guan_Li_Ku_Cun__c DESC, Pre_Arrival_wh_time__c ASC NULLS FIRST, Id DESC';
    }

    public override Boolean getIsNeedRunSearch() {

      //   if (String.isBlank(keyword)) {
            // isNeedRunSearch = false;
      //   }else{
            // isNeedRunSearch = true;
      //   }
        return true;
    }



    /*****************検索用******************/


    /*****************ソート時再検索条件（画面からの入力条件を無視するため）******************/
    private String keywdSort = null;
    private String o2oAssetId = '';    // makeSoql の中で使う
    public String keyword { get; set; }

    public Boolean bieField { get; set;}  //别省、别本部、别存放地、别用途

    public Rental_Apply_Equipment_Set__c parentObj { get; set; }
    // 附属品选择页面里点击分配按钮时的那一行明细的Id
    private String rsdObjId = null;
    public Rental_Apply_Equipment_Set_Detail__c sonObj { get; set; }

    public String bieCunFangDi { get; set; }     //别存放地, 肯定有值 不为null
    public String bieBenBu { get; set; }         //别本部
    public Set<String> benbuSet;
    public Set<String> cunfangdiSet;
    // 备品智能化项目对应 20231122 by lc Start
    public Boolean isMainAssign { get; set; }
    // 备品智能化项目对应 20231122 by lc End
    public Boolean hgerqi { set; get; } // WYL 贸易合规2期
    public String rentalApplyStatus { set;get; }    //2024-1-11 sx add 申请单合规状态
    public String rentalApplyId { set;get; }        //20240204 sx add 合规发邮件

    public AccessoryAddController() {
        rsdObjId = ApexPages.currentPage().getParameters().get('recid');
        benbuSet = new Set<String>();
        cunfangdiSet = new Set<String>();
        this.bieField = true;
        //借出备品一览の情報を取得
        if (!String.isBlank(rsdObjId)) {
            List<Rental_Apply_Equipment_Set_Detail__c> rsdObjs = [
                    SELECT Id, Rental_Apply_Equipment_Set__c, Asset__c, Internal_asset_location_before__c,
                           FSD_Fixture_Model_No__c, Intervention_Reason__c
                     FROM Rental_Apply_Equipment_Set_Detail__c
                    WHERE Id = :rsdObjId];
            if (!rsdObjs.isEmpty()) {
                sonObj = rsdObjs[0];
                // bieCunFangDi = sonObj.Internal_asset_location_before__c;

                parentId = sonObj.Rental_Apply_Equipment_Set__c;

                List<Rental_Apply_Equipment_Set__c> parentObjs = [
                    SELECT Id, Rental_Apply__r.Name,
                           Rental_Apply__r.Owner.Name,
                           Rental_Apply__r.Salesdept__c,
                           Rental_Apply__r.WorkPlace__c,
                           Rental_Apply__r.Request_shipping_day__c,
                           Fu_Shu_Pin_Fen_Pei_Jia__c,
                           Rental_Apply__r.Demo_purpose1__c,
                           Rental_Apply__r.Demo_purpose2__c,
                           //Fixture_Set__r.Product_Category_GI_SP__c,
                           Rental_Apply__r.Product_category__c,
                           Rental_Apply__r.Salesdepartment__c,
                           //Fixture_Set__r.Equipment_Type__c,
                           Rental_Apply__r.Equipment_Type_F__c,
                           Rental_Apply__r.Internal_asset_location_F__c,
                           Rental_Apply__r.Request_return_day__c,
                           Fixture_Set__r.Fixture_Set_Body_Model_No__c,
                           Rental_Apply__r.Cross_Region_Assign__c,
                           Rental_Apply__r.Manually_Flag__c,
                           Irreplaceable_flag__c,
                           Rental_Start_Date__c,
                           Rental_End_Date__c,
                           RequestNoJoinStr2__c,
                           First_RAESD__c,
                           //WYL 贸易合规2期 2023-11-28 start
                           Rental_Apply__r.AccDealerBlacklist__c,
                           //WYL 贸易合规2期 2023-11-28 end
                           Rental_Apply__c                          //贸易合规二期add  sx 邮件发送
                    FROM Rental_Apply_Equipment_Set__c
                    where Id = :parentId];
                System.debug('parentObjs' + parentObjs);
                if (!parentObjs.isEmpty()) {
                    parentObj = parentObjs[0];
                    rentalApplyStatus = parentObj.Rental_Apply__r.AccDealerBlacklist__c;	//贸易合规二期sx add
                    rentalApplyId = parentObj.Rental_Apply__c;                              //贸易合规二期add  sx 邮件发送
                }
                if (String.isBlank(bieCunFangDi)) {
                    List<Rental_Apply_Equipment_Set_Detail__c> bodyObjs = [
                        SELECT Id, Internal_asset_location_before__c, Salesdepartment_before__c, Select_Time__c
                         FROM Rental_Apply_Equipment_Set_Detail__c
                        WHERE Rental_Apply_Equipment_Set__c = :parentId
                          and Id = :parentObj.First_RAESD__c
                          and Select_Time__c != null
                          and Cancel_Select__c = false];
                    if (!bodyObjs.isEmpty()) {
                        bieCunFangDi = bodyObjs[0].Internal_asset_location_before__c;
                        bieBenBu = bodyObjs[0].Salesdepartment_before__c;
                        System.debug('bieCunFangDi1' + bieCunFangDi);
                    }
                }
                if (String.isBlank(bieCunFangDi)) {
                    bieCunFangDi = parentObj.Rental_Apply__r.Internal_asset_location_F__c;
                    bieBenBu = parentObj.Rental_Apply__r.Salesdepartment__c;
                    System.debug('bieCunFangDi2' + bieCunFangDi);
                }
                if (String.isBlank(bieCunFangDi)) {
                    throw new ControllerUtil.myException('不能明确存放地, 请确认数据。');
                } else {
                    sonObj.Internal_asset_location_before__c = bieCunFangDi;
                }
            }
            else {
                throw new ControllerUtil.myException('没有可以操作的备品, 或者数据不正确。');
            }

            //查找主体Asset
            List<Rental_Apply_Equipment_Set_Detail__c> mainSetDetails =[
                    SELECT Id, Asset__c
                      FROM Rental_Apply_Equipment_Set_Detail__c
                     WHERE Rental_Apply_Equipment_Set__c = :parentId and Is_Body__c = true];
            if (!mainSetDetails.isEmpty()) {
                if (String.isNotBlank(mainSetDetails[0].Asset__c)) {
                    // 找到对应的一对一附属品Asset
                    List<Fixture_OneToOne_Link__c> o2oList = [SELECT Id, Accessory_Asset__c
                             FROM Fixture_OneToOne_Link__c
                            WHERE Main_Asset__c = :mainSetDetails[0].Asset__c
                              AND Accessory_Asset__r.Product2.Fixture_Model_No_T__c = :sonObj.FSD_Fixture_Model_No__c
                            ];
                    if (!o2oList.isEmpty()) {
                        for (Fixture_OneToOne_Link__c o2o : o2oList) {
                            o2oAssetId += ('\'' + o2o.Accessory_Asset__c + '\',');
                        }
                        o2oAssetId = o2oAssetId.removeEnd(',');
                    }

                    // 备品智能化项目对应 20231122 by lc Start
                    // 有主体并且主体有保有可以直接操作
                    isMainAssign = true;
                    // 备品智能化项目对应 20231122 by lc End
                }
            } else {
                // 备品智能化项目对应 20231122 by lc Start
                // 没有主体的配套可以直接操作
                isMainAssign = true;
                // 备品智能化项目对应 20231122 by lc End
            }
        }
        if (FixtureUtil.needSalesdepartment.contains(bieBenBu) == false) {
            bieBenBu = '0.备品中心';
        }
    }

    public void init() {
        isNeedSearchFirst = true;

        searchOppSetParam();

        getSqlWhereStr();
    }

    private void searchOppSetParam() {
        keywdSort = keyword;
    }

    //别存放地 SelectOption
    public List<SelectOption> getbieCunFangDiOps() {
        // if (UserInfo.getProfileId() == System.Label.ProfileId_SystemAdmin || System.Label.ProfileId_EquCenAdmin.contains(UserInfo.getProfileId())) {
        //     return FixtureUtil.bieCunFangDiOpsMap.get('备品管理中心');
        // } else {
        //     return new List<SelectOption>{
        //         new SelectOption(bieCunFangDi, bieCunFangDi)
        //     };
        // }

        cunfangdiSet = new Set<String>();
        List<SelectOption> opList;
        if (UserInfo.getProfileId() == System.Label.ProfileId_SystemAdmin || System.Label.ProfileId_EquCenAdmin.contains(UserInfo.getProfileId())) {
            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() {
        // return new List<SelectOption>{
        //     new SelectOption(bieBenBu, bieBenBu)
        // };
        benbuSet = new Set<String>();
        List<SelectOption> opAllList = FixtureUtil.bieBenBuOpsMap.get(sonObj.Internal_asset_location_before__c);
        for (SelectOption op : opAllList) {
            if (String.isNotBlank(op.getValue())) {
                benbuSet.add(op.getValue());
            }
        }
        // 需要条件的本部
        List<SelectOption> opList = FixtureUtil.bieBenBuOpsMap.get(bieCunFangDi);
        List<SelectOption> needSalesdepartmentOpList = new List<SelectOption>();

        Set<String> needSalesdepartmentSet = FixtureUtil.needSalesdepartment;
        for (SelectOption eachOp : opList) {
            if (needSalesdepartmentSet.contains(eachOp.getValue()) || eachOp.getValue() == '0.备品中心' || eachOp.getValue() == '' ) {
                needSalesdepartmentOpList.add(eachOp);
            }
        }

        return needSalesdepartmentOpList;
    }

    public PageReference searchOpp() {
        searchOppSetParam();

        if (!getIsNeedRunSearch()) {
            return null;
        }

        // 選択済みの製品を取得
        myComponentController.getSelectedDataInfo();

        getSqlWhereStr();
        // コンポーネントにSoqlを発行して、ページングする
        myComponentController.searchAndPaging();
        return null;
    }

    //20240111 sx 贸易合规二期校验 start 
    public PageReference tradeCheckTwo(){
        Set<Id> assetId = new Set<Id>();
        List<String> assList = new List<String>();
        for (WrapperInfo wprInfo : viewList) {
            Rental_Apply_Equipment_Set_Detail__c robj = (Rental_Apply_Equipment_Set_Detail__c) wprInfo.sobj;
            if(wprInfo.check){
                assetId.add(robj.Asset__c);
            }

            if(assetId.size()>0){
                List<Asset> aSetList =
                    [Select Id, Product2.ProTradeComplianceStatus__c From Asset
                      where Id IN :assetId for Update];
                if(aSetList.size() == 0){
                    throw new ControllerUtil.myException('不是有效的附属品，请刷新画面后重新操作');
                }else if(System.Label.TradeComplianceStatusFlagBP =='true' && rentalApplyStatus == '2'){
                    for(Asset ass: aSetList){
                        if(ass.Product2.ProTradeComplianceStatus__c == '0'){
                            assList.add(ass.Id);	//20240204 sx  贸易合规二期发邮件 add
                            this.hgerqi = true;
                        }
                    }
                    //20240204 sx  贸易合规二期发邮件 start
                    if(assList.size() > 0){
                        SendEmailUtil.tradeTempleSend(rentalApplyId, '附属品追加', assList , null);
                    }
                    //20240204 sx  贸易合规二期发邮件 end
                }

            }
        }
        return null;
    }
    //20240111 sx 贸易合规二期校验 end 

    public PageReference save() {
        List<Id> delIds = new List<String>();
        //20170906 upsert by UniqueKey__c
        List<Rental_Apply_Equipment_Set_Detail__c> mfUpsert = new List<Rental_Apply_Equipment_Set_Detail__c>();

        Savepoint sp = Database.setSavepoint();
        Set<String> clearUniqueKeySet = new Set<String>();
        try {

            for (Integer indexNum = 0; indexNum < viewList.size(); indexNum++) {
                WrapperInfo wprInfo = viewList[indexNum];
                Rental_Apply_Equipment_Set_Detail__c robj = (Rental_Apply_Equipment_Set_Detail__c) wprInfo.sobj;
                //1822 yc 20211021 已购待货目的，新品已有发货日不能出库 start
                 if(robj.Rental_Apply__r.demo_purpose2__c=='已购待货' && robj.Rental_Apply__r.Follow_UP_Opp__r.Shipping_Finished_Day_Func__c!= null){
                    throw new ControllerUtil.myException('已购待货目的，新品已有发货日，不能继续了');
                 }
                 if(robj.Rental_Apply__r.demo_purpose2__c=='索赔QIS' && robj.Rental_Apply__r.next_action__c=='无偿更换' && robj.Rental_Apply__r.QIS_number__r.ReplaceDeliveryDate__c!= null){
                    throw new ControllerUtil.myException('索赔QIS目的，QIS已有新品发货日，不能继续了');
                   }
                 //1822 yc 20211021 已购待货目的，新品已有发货日不能出库 end
                //20170906 upsert by UniqueKey__c
                // 画面上にチェックした
                if (wprInfo.check) {
                    List<Asset> aSetList =
                            [Select Id, Quantity,
                                    Out_of_wh__c,
                                    Manage_type__c,
                                    Ji_Zhong_Guan_Li_Ku_Cun__c, // 20220118 ljh SFDC-C9V84U start
                                    You_Xiao_Ku_Cun__c
                               From Asset
                              where Id = :robj.Asset__c
                                for Update];
                    // 不能lock到数据的时候
                    if (aSetList.size() == 0) {
                        throw new ControllerUtil.myException('第' + (indexNum + 1) +'行，不是有效的附属品，请刷新画面后重新操作');
                    }
                    Asset aSet = aSetList[0];
                    Map<Id, Asset> assetUpdateMap = new Map<Id, Asset>();
                    // 操作対象
                    List<Rental_Apply_Equipment_Set_Detail__c> rasedList = [
                            SELECT Id, Asset__c,
                                   Queue_Number__c,
                                   Queue_Day__c
                            FROM Rental_Apply_Equipment_Set_Detail__c
                            where Id = :rsdObjId
                              FOR Update];
                    if (rasedList.isEmpty()) {
                        throw new ControllerUtil.myException('分配的附属品不存在，请刷新画面后重新操作');
                    }
                    // 分配时间
                    if (robj.Select_Time__c == null || rasedList[0].Asset__c != robj.Asset__c) {
                        if (aSet.Out_of_wh__c == null || aSet.Out_of_wh__c == 0) {
                            aSet.Out_of_wh__c = 0;
                        }
                        // 备品有效库存
                        {
                            Integer num = Integer.valueof(aSet.You_Xiao_Ku_Cun__c);
                            // 备品有效库存没有时,程序返回并提示错误信息
                            if (num < 1) {
                                throw new ControllerUtil.myException('第' + (indexNum + 1) +'行，没有足够有效库存，请刷新画面后重新操作');
                            }
                            // 20220118 ljh SFDC-C9V84U start
                            if(aSet.Ji_Zhong_Guan_Li_Ku_Cun__c <= 0){
                                throw new ControllerUtil.myException('第' + (indexNum + 1) +'行，集中库库存不足，请刷新画面后重新操作');
                            }
                            // 20220118 ljh SFDC-C9V84U end
                        }
                        //Asset变化的时候清空出库指示时间
                        robj.Shipment_request_time2__c = null;
                        robj.Shipment_request__c = false;
                        //aSet.Out_of_wh__c = aSet.Out_of_wh__c + 1;

                        //assetUpdateMap.put(aSet.Id, aSet);
                    }

                    String uniqueKeyStr = parentObj.RequestNoJoinStr2__c + ':'+ robj.Rental_Apply_Equipment_Set__c
                            + ':' + robj.FSD_Id__c + ':' + ((Integer) Math.round(robj.IndexFromUniqueKey__c));
                    robj.UniqueKey__c = uniqueKeyStr;
                    // 分配时间
                    robj.Select_Time__c = System.now();

                    // 备品智能化项目对应 20231122 by lc Start
                    if (!String.isBlank(sonObj.Intervention_Reason__c)) {
                        robj.Intervention_Reason__c = sonObj.Intervention_Reason__c;
                    }
                    // 备品智能化项目对应 20231122 by lc End

                    // 附属品为个体管理的情况下更新
                    // if (FixtureUtil.managetypeMap.get(FixtureUtil.Managetype.Ge_Ti_Guan_Li) == aSet.Manage_type__c) {
                    //     if (aSet.Last_Reserve_RAES_Detail__c != robj.Id) {
                    //         aSet.Last_Reserve_RAES_Detail__c = robj.Id;
                    //         assetUpdateMap.put(aSet.Id, aSet);
                    //     }
                    // }

                    mfUpsert.add(robj);

                    if (String.isBlank(robj.Id)
                        && !String.isBlank(uniqueKeyStr)) {
                        // 新規の場合、ここ単純に Id にて判断
                        clearUniqueKeySet.add(uniqueKeyStr);
                    }

                    // 1件しかない
                    //update assetUpdateMap.values();
                    break;
                }
            }

            // Upsert
            if (mfUpsert.size() > 0) {
                FixtureUtil.withoutUpsertRaesd(mfUpsert);
                // 附属品調整画面url
                PageReference ret = null;
                ret = new PageReference('/apex/AccessorySelect?pt_recid=' + parentId);
                return ret;
            }


        } catch (Exception ex) {
            System.debug(ex.getStackTraceString());
            ApexPages.addMessages(ex);
            Database.rollback(sp);
            // Id をクリア
            for (Rental_Apply_Equipment_Set_Detail__c robj : mfUpsert) {
                if (clearUniqueKeySet.contains(robj.UniqueKey__c)) {
                    robj.Id = null;
                }
            }
            return null;
        }

        return null;
    }


    public PageReference cancel() {
        PageReference ret = null;
        if (!String.isBlank(this.parentId)) {
            ret = new PageReference('/' + this.parentId);
        }
        return ret;
    }

    private String makeSoql(String keyword) {
        // 検索条件
        String dateToday = String.valueOf(Date.today());

        // from asset
        String soql = '';
        soql += 'where Asset_Owner__c = \'Olympus\' AND ' + FixtureUtil.getAssetSoqlBase();
        soql += '  and Asset_loaner_category__c != \'耗材\'';
        soql += '  and RecordTypeId = \''+System.Label.access_1+'\'';
        soql += '  and Loaner_accsessary__c = true';
        soql += '  and Equipment_Type__c != \'检测用备品\'';
        soql += '  and Delete_Flag__c = False ';
        soql += '  and Recall_Asset__c = False ';
        soql += '  and Freeze_sign_Abandoned_Flag__c = False';
        soql += '  and (Consumable_Guaranteen_end__c = null or Consumable_Guaranteen_end__c >=' + dateToday + ')';
        soql += '  and ((Fixture_OneToOne_Link__c = null';           // 附属品一对一的个体管理不能检索出来
        soql += '          and Ji_Zhong_Guan_Li_Ku_Cun__c > 0)';
        if (String.isBlank(o2oAssetId) == false) {
            soql += '      or Id IN ('+ o2oAssetId +')';         // 今画面に操作する付属品のFixture_Model_No_T__c と分配した本体と同じ組のOneToOneの付属品も検索対象
        }//niwu-01210000000kOPR access_1
        soql += '  )';

        // 不检索seledted的数据  在 CreateRelationListPagingCmpCtrl 里 已经 去除了 selectedFKIdLis

        if (!String.isBlank(keyword)) {
            String[] vals = keyword.split(' ');
            soql += ' and (';
            String fmodelno = '';
            for (String v : vals) {
                fmodelno    += ' Product2.Fixture_Model_No_T__c like \'%' + String.escapeSingleQuotes(v.replaceAll('%', '\\%')) + '%\' ';
                fmodelno    += ' or Product2.Name like \'%' + String.escapeSingleQuotes(v.replaceAll('%', '\\%')) + '%\'';
                fmodelno    += ' or Product2.OT_CODE_no_link__c like \'%' + String.escapeSingleQuotes(v.replaceAll('%', '\\%')) + '%\'';
                fmodelno    += ' or Product2.MDM_Model_No__c like \'%' + String.escapeSingleQuotes(v.replaceAll('%', '\\%')) + '%\'';
                fmodelno    += 'or';
            }
            fmodelno = fmodelno.removeEnd('or');
            soql += fmodelno + ' )';
        } else {
            soql += ' and Product2.Fixture_Model_No_T__c = \'' + String.escapeSingleQuotes(sonObj.FSD_Fixture_Model_No__c) + '\'';
        }

        //别存放地
        if (String.isNotBlank(bieCunFangDi) && bieCunFangDi != 'All') {
            soql += ' and Internal_asset_location__c = \'' + String.escapeSingleQuotes(bieCunFangDi) + '\'';
        }
        else {
            String cunfangdiStr = '';
            for (String cunfangdi : cunfangdiSet) {
                cunfangdiStr += ' Internal_asset_location__c = \'' + String.escapeSingleQuotes(cunfangdi) + '\' OR';
            }
            soql += ' and (' + cunfangdiStr.removeEnd('OR') + ')';
        }

        //别本部
        if (String.isNotBlank(bieBenBu)) {
            soql += ' and Salesdepartment__c = \'' + String.escapeSingleQuotes(bieBenBu) + '\'';
        }
        else {
            String benbuStr = '';
            for (String benbu : benbuSet) {
                benbuStr += ' Salesdepartment__c = \'' + String.escapeSingleQuotes(benbu) + '\' OR';
            }
            soql += ' and (' + benbuStr.removeEnd('OR') + ')';
        }

        system.debug('soql===' + soql);
        return soql;
    }

    public override void setViewList(List<sObject> queryList) {
        String wher = '';
        //别存放地
        if (String.isNotBlank(bieCunFangDi) && bieCunFangDi != 'All') {
            wher += ' and Internal_asset_location__c = \'' + String.escapeSingleQuotes(bieCunFangDi) + '\'';
        }

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

        viewList = new List<WrapperInfo>();
        List<Rental_Apply_Equipment_Set_Detail__c> groupByTargetList = new List<Rental_Apply_Equipment_Set_Detail__c>();
        if (selectedData.size() == 0) {
            throw new ControllerUtil.myException('没有进行正确的操作或者数据不正确。');
        }
        // 選択済みの明细
        if (selectedData.size() > 0) {
            for (Integer i = 0; i < selectedData.size(); i++) {
                /* not include the selected data num */
                // 501を超えた場合前500のみを出す
                //if (i == getSearchNumMax()) continue;
                Rental_Apply_Equipment_Set_Detail__c rsdObj = (Rental_Apply_Equipment_Set_Detail__c) selectedData[i];
                if (!String.isBlank(rsdObj.Asset__c)) {

                    viewList.add(new WrapperInfo(rsdObj, myComponentController));
                    viewList[viewList.size() - 1].lineNo = viewList.size() - 1;
                    viewList[viewList.size() - 1].check = true;
                    viewList[viewList.size() - 1].oldCheck = true;
                    groupByTargetList.add(rsdObj);
                }
            }
        }

        Savepoint sp = Database.setSavepoint();
        // 下にrollbackがあります
        System_UserSetting__c config = System_UserSetting__c.getOrgDefaults();
        config.RentalApply_ByPass__c = true;
        // 組織のカスタム設定が作成してないの可能性がありますのでここでupsert
        FixtureUtil.withoutUpsertObjects(new System_UserSetting__c[]{config});
        // 数式項目値を取れるのために、一回Insertする
        List<Rental_Apply_Equipment_Set_Detail__c> tempList = new List<Rental_Apply_Equipment_Set_Detail__c>();
        for (Integer i = 0; i < queryList.size(); i++) {
            // 501を超えた場合前500のみを出す
            if (i == getSearchNumMax()) { break; }
            Rental_Apply_Equipment_Set_Detail__c mf = ((Rental_Apply_Equipment_Set_Detail__c) selectedData[0]).clone(false);


            // ****************注意:这里不能随意清空字段,如果要清空一定要慎重再慎重,因为保存的时候可能会把有值的字段清空掉
            // 因为检索的时候需要显示检索出来的Asset信息，所以需要清除Clone出来的值，好让数据可以的Handler里面赋成当前Asset值
            // mf.Fixture_Model_No_text__c = null; OLY_OCM-431 不设定， 设定的话 画面会显示成 代替品
            mf.SerialNumber_text__c = null;
            mf.SalesProvince_before__c = null;
            mf.Salesdepartment_before__c = null;
            mf.Product_category_text__c = null;
            mf.Equipment_Type_text__c = null;
            mf.Asset_cost_del_before__c = null;
            mf.Internal_asset_location_before__c = null;
            mf.Fixture_Name_text__c = mf.FSD_Name_CHN__c;
            mf.EquipmentSet_Managment_Code_text__c = null;


            mf.Asset__c                             = queryList[i].Id;
            mf.DataMigration_Flag__c                = true;

            tempList.add(mf);
        }

        system.debug('Database inset before');
        System.debug('测试selectedData.size:' + selectedData.size());
        System.debug('测试queryList.size:' + queryList.size());
        System.debug('测试tempList:' + tempList);
        Database.SaveResult[] results = FixtureUtil.withoutInsert(tempList, false);

        final String soqlStr = 'Select {0} {1} ';
        String whereStr = ' FROM Rental_Apply_Equipment_Set_Detail__c WHERE ID in: tempList';
        String soql = String.format(soqlStr, new String[] {myComponentController.strColumus, whereStr});

        tempList = Database.query(soql);
        if (queryList.size() != tempList.size()) {
            //error message 検索処理正しくありません、システム管理者に連絡してください。
            Database.SaveResult dmlResult = results[0];
            if (!dmlResult.isSuccess()) {
                System.debug(System.LoggingLevel.ERROR, '第[' + (1) + ']条 insert error:' + dmlResult);
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,
                        '第[' + (1) + ']条 insert error:' + dmlResult));
            }
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,
                    System.Label.CreateRelationListSearchError));
            return;
        }

        // 強制ロールバック
        Database.rollback(sp);
        Map<String, SObject> fsDMap = new Map<String,SObject>();
        for(Rental_Apply_Equipment_Set_Detail__c fsd : tempList){
            Rental_Apply_Equipment_Set_Detail__c robj = fsd.clone(false);
            robj.DataMigration_Flag__c = false;
            fsDMap.put(fsd.Asset__c, robj);
        }

        for (Integer i = 0; i < queryList.size(); i++) {
            // 501を超えた場合前500のみを出す
            if (i == getSearchNumMax()) { break; }
            Rental_Apply_Equipment_Set_Detail__c mf = (Rental_Apply_Equipment_Set_Detail__c) fsDMap.get(queryList[i].Id);
            viewList.add(new WrapperInfo(mf, myComponentController));
            viewList[viewList.size() - 1].lineNo = viewList.size() - 1;
            groupByTargetList.add(mf);
        }

        Map<Rental_Apply_Equipment_Set_Detail__c, Map<String, FixtureUtil.groupBean>> rsdMap = FixtureUtil.raesdGroupBy(
                groupByTargetList, myComponentController.columus, wher);

        for (Rental_Apply_Equipment_Set_Detail__c rsdObj : groupByTargetList) {
            Map<String, FixtureUtil.groupBean> rsdGroupInfo = rsdMap.get(rsdObj);

            for (String apikey : rsdGroupInfo.keySet()) {
                if (apikey.indexOf('_Jia__c') >= 0 && apikey != 'Fu_Shu_Pin_Fen_Pei_Jia__c') {
                    rsdObj.put(apikey, rsdGroupInfo.get(apikey).gnum);
                }
                else  if (apikey == 'Fu_Shu_Pin_Fen_Pei_Jia__c') {
                    if (!String.isBlank(rsdObj.Asset__c) && rsdObj.Select_Time__c != null) {
                        rsdObj.put(apikey, FixtureUtil.assetFixtureStatusMap.get(FixtureUtil.assetFixtureStatus.Yi_Fen_Pei.ordinal()));
                    } else {
                        rsdObj.put(apikey, FixtureUtil.assetFixtureStatusMap.get(rsdGroupInfo.get(apikey).gnum));
                    }
                }
            }
        }

system.debug('●●●●● setViewList END ' );
}


}