/*
 * 借出备品配套明细选择画面
 * 只显示Fixture_Set_Detail__c有值的明细
 */
public with sharing class ReceivingNoteDetailSelectController extends CreateRelationListPagingCtrlBase {
    private List<LineExtraInfo> extraInfoList;  // viewList と同じ順番、同じ件数
    private String raesid;  // 保存清单配套选择画面传来的值
    private String returl {get;set;}
    public Boolean isAcceptance {get;set;}

    public override Integer getSearchNumMax() {
        //各ページに制御あれば、最大件数を指定する
        searchNumMax = Integer.valueOf(Label.Product_Select_Limit);
        //TODO change
        searchNumMax = 100;
        return searchNumMax;
    }

    public override Boolean getIsNeedRunSearch() {
        return true;
        //isNeedRunSearch = true;
        //return isNeedRunSearch;
    }
    /* 選択されたデータ取得用Soql　Fromから*/
    public override String getSelectedDataSql() {
        // オブジェクトAPI名
        selectedDataSql = ' From ReceivingNoteDetail__c';
        selectedDataSql += ' where ReceivingNoteSummary__c = \'' + String.escapeSingleQuotes(parentId) + '\'';
        //Fixture_Set_Detail__c没有值不能检索出数据
        selectedDataSql += '   and Fixture_Set_Detail__c != null';
        // OLY_OCM-286 まず全部selectして group by Fixture_Set_Detail__c のlogicにてcountしたいですが
        // Fixture_Set_Detail__c を検索時、全部キャンセルした明細の行が表示しなくなるため、
        // and Cancel_Select__c = False を必ず有効にしてください。
        // selectedDataSql += '   and Cancel_Select__c = False';
        selectedDataSql += '   and Delete_Flag__c = False';
        selectedDataSql += '   and Change_Point__c != \'删除\'';
        selectedDataSql += ' order by RNDAssert__c nulls last, Fixture_Set_Detail__r.SortInt__c, UniqueKey__c';
        return selectedDataSql;
    }

    // 検索元対象オブジェクトAPI名
    public override String getOriginObjName() {
        // オブジェクトAPI名
        originObjName = 'Fixture_Set_Detail__c';
        return originObjName;
    }
    public override String getOriginObjColumns() {
        // 項目セット
        //rentx add Fixture_Set_New_Quantity__c at 20210827
        originObjColumns =  'Id, Quantity__c, Is_Body__c, Is_Optional__c, LastModifiedDate, Fixture_Set_New_Quantity__c';
        return originObjColumns;
    }

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

    public override List<String> getColumnFieldList() {
        // strColumus 里加 field
        return new List<String>{'Id'
                                , 'Is_Body__c'
                                , 'UniqueKey__c'
                                , 'Rental_Num__c'
                                //, 'VF_Rental_Num__c'
                                //, 'RNDAssert__c'
                                , 'passNo3__c'
                                , 'Fixture_Set_Detail__r.SortInt__c'
                                , 'Fixture_Set_Detail__r.Is_Optional__c'
                                , 'EquipmentSet_Managment_Code__c'
                                , 'Salesdepartment__c'
                                , 'SalesProvince__c'
                                , 'Product_category__c'
                                , 'Equipment_Type__c'
                                , 'Manage_type__c'
                                , 'unknow_serial_NO_product__c'
                                , 'Loaner_accsessary__c'
                                , 'DataConfirmation__c'
                                , 'Is_First_RND_F__c'
                                , 'Product_Old_Model_F__c'
                                , 'Fixture_Set_Detail__r.Product2__c'
                                , 'Fixture_Set_Detail__r.Fixture_Model_No_F__c'
                                , 'Set_Arrival_Product__c'
                                , 'Fixture_Arrival_Product__c'
                                , 'Default_Fixture_Arrival_Product__c'
                                , 'Product_Arrival_Product__c'
                                //add by rentx 20210728 start 新品收货_集中备品_建立新品入库标准配套
                                , 'Fixture_Set_Detail__r.Fixture_Set_New__c'
                                , 'Fixture_Set_Detail__r.Fixture_Set_New_Quantity__c'
                                , 'Fixture_Set_New_Quantity__c'
                                , 'Fixture_Set_Detail__r.LastModifiedDate'
                                , 'LastModifiedDate'
                                , 'Fixture_Set_Detail__r.Quantity__c'
                                //add by rentx 20210728 end 新品收货_集中备品_建立新品入库标准配套
                            };
    }

    // 画面里直接可以输入的項目 List
    public override List<String> getWritableColumnFieldList() {
        //update by rentx 20210728 start 新品收货_集中备品_建立新品入库标准配套
        // return new List<String>{'Rental_Num__c'};
        return new List<String>{'Fixture_Set_New_Quantity__c'};
        //update by rentx 20210728 end 新品收货_集中备品_建立新品入库标准配套
    }
    // getObjName 连 getOriginObjName 的 FK
    public override String getFKColumnField() {
        return 'Fixture_Set_Detail__c';
    }

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

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

        sqlWhereStr = this.makeSoql();

        return sqlWhereStr;
    }
    public override String getOrderbyStr() {
        return 'order by SortInt__c';
    }

    /*****************ソート時再検索条件（画面からの入力条件を無視するため）******************/
    private List<String> sidList;
    public String saveType { get; set; }
    public ReceivingNoteSummary__c parentObj { get; set; }
    public ReceivingNoteDetail__c sonObj { get; set; }
    public List<ReceivingNoteDetail__c> selectedGroupData { get; set; }
    private String deleteAdd_ApprovalErrorMessage = '第{0}行 付属品{1}件（草案中的追加付属品 {2}件） 更新失败 减少的数量大于草案中的追加付属品的数量';
    private String deleteAdd_ApprovalMessage = '第{0}行 付属品{1}件（草案中的追加付属品 {2}件） 成功更新成 付属品{3}件（草案中的追加付属品 {4}件）';

    public ReceivingNoteDetailSelectController() {
        isNeedRunSearch = true;
        String sids = ApexPages.currentPage().getParameters().get('sids'); // 一览Id
        raesid = ApexPages.currentPage().getParameters().get('raesid');    // 清单Id
        returl = ApexPages.currentPage().getParameters().get('returl');
        isAcceptance = String.isNotBlank(returl);

        sidList = sids.split(',');
        if(sidList.size()>0) {
            // 借出备品配套
            //02517%3Aa2P0k000000PEkjEAG%3A1
            parentId = sidList.get(0);
            //备品配套下的所有明细
            if (!String.isBlank(this.parentId)) {
                //画面上ヘタ表示の項目はここで追加
                List<ReceivingNoteDetail__c> sonObjs = [SELECT Id
                            , Name
                            , ReceivingNoteSummary__c
                            , ReceivingNoteSummary__r.Id
                            , ReceivingNoteSummary__r.Name
                            , ReceivingNoteSummary__r.ReceivingNote__c
                            , ReceivingNoteSummary__r.Fixture_Set__r.Loaner_name__c
                         FROM ReceivingNoteDetail__c
                        WHERE ReceivingNoteSummary__c = :parentId
                          AND Delete_Flag__c = false];
                if (sonObjs.size() > 0) {
                    parentObj = sonObjs.get(0).ReceivingNoteSummary__r;
                    sonObj = sonObjs.get(0);
                    if (String.isBlank(parentObj.Fixture_Set__c )) {
                        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '收货一览没有指定备品配套,不能进行操作!'));
                        return ;
                    }
                } else {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '没有找到收货一览,请进行正确的操作!'));
                    return ;
                }
            }
        }
    }

    public void init() {
        isNeedSearchFirst = true;
        viewList = new List<WrapperInfo>();
        extraInfoList = new List<LineExtraInfo>();  // viewList と同じ順番、同じ件数
        getSqlWhereStr();
    }

    public PageReference searchOpp() {

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

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

    public PageReference save() {
        //update by rentx 20210729 start 新品收货_集中备品_建立新品入库标准配套
        //新品配套数量若有变化(目前: 为了防止好几个人在同时修改此数据)，保存时报错提示：重新刷新画面
        //需要按照init的条件再查一次 在和现在画面上展示的数量作比对 若数量不一致 则保存提示 重新刷新画面
        //获取当前备品收货清单配套一览 获取所有有备品配套明细一览的 收货清单明细
        // 配套有任何更新（不局限数量、新品数量字段修改，比如主体、选配字段有修改也算更新）都check，错误提示改成【备品配套已更新，请重新刷新页面】
        if (parentObj != null) {
            List<ReceivingNoteDetail__c> sonObjs = [SELECT Id
                            , Name
                            , ReceivingNoteSummary__c
                            , SortInt_F__c
                            , Fixture_Set_Detail__r.Fixture_Set_New_Quantity__c
                            , Fixture_Set_Detail__r.LastModifiedDate 
                         FROM ReceivingNoteDetail__c
                        WHERE ReceivingNoteSummary__c = :parentObj.Id
                          AND Delete_Flag__c = false];
            if (sonObjs != null && sonObjs.size() > 0) {
                Map<String,Datetime> checkMap = new Map<String,Datetime>();
                for (ReceivingNoteDetail__c detail : sonObjs) {
                    Datetime tempTime = detail.Fixture_Set_Detail__r.LastModifiedDate;
                    checkMap.put(detail.SortInt_F__c, tempTime );
                }
                for (WrapperInfo wprInfo : viewList) {
                    ReceivingNoteDetail__c robj = (ReceivingNoteDetail__c) wprInfo.sobj;
                    if (checkMap.containsKey(robj.SortInt_F__c)) {
                        Datetime ttime = robj.Fixture_Set_Detail__r.LastModifiedDate;
                        if (checkMap.get(robj.SortInt_F__c) != ttime ) {
                            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '备品配套已更新，请重新刷新页面!' ));
                        return null;
                        }
                    }
                }
            }
        }
        //update by rentx 20210729 end 新品收货_集中备品_建立新品入库标准配套

        //20170906 upsert by UniqueKey__c
        List<ReceivingNoteDetail__c> mfUpsert = new List<ReceivingNoteDetail__c>();
        List<ReceivingNoteDetail__c> mfUpdate = new List<ReceivingNoteDetail__c>();
        Savepoint sp = Database.setSavepoint();
        Set<String> clearUniqueKeySet = new Set<String>();
        // 有删除未审批的追加附属品
        Boolean haveAdd_ApprovalDelete = false;

        try {
            // 同一附属品 一括設定する
            // if (parentObj.Same_Accessory_flag__c) {
            //     if ([SELECT Id
            //            FROM ReceivingNoteSummary__c
            //           WHERE ReceivingNote__c = :parentObj.ReceivingNote__c
            //             AND Fixture_Set__c = :parentObj.Fixture_Set__c
            //             AND Same_Accessory_flag__c = true
            //             AND Cancel_Select__c = false
            //             AND Id IN (
            //                     SELECT ReceivingNoteSummary__c
            //                       FROM ReceivingNoteDetail__c
            //                      WHERE Rental_Apply_Equipment_Set__r.ReceivingNote__c = :parentObj.ReceivingNote__c
            //                        AND Rental_Apply_Equipment_Set__r.Fixture_Set__c = :parentObj.Fixture_Set__c
            //                        AND Rental_Apply_Equipment_Set__r.Same_Accessory_flag__c = true
            //                        AND Rental_Apply_Equipment_Set__r.Cancel_Select__c = false
            //                        AND Is_Body__c = false
            //                        AND Cancel_Select__c = true
            //                        AND Cancel_Reason__c != '重新分配' // OLY_OCM-163#comment-20120592 通过取消理由判断
            //                 )
            //             ].size() > 0) {

            //         // 申請から進んだ明細がある場合
            //         ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,
            //                 System.Label.SameAccessory_CannotSync));
            //         return null;
            //     }
            // }

            // 画面中チェックされた対象、確定ボタンを押下すると、一つずつ順番に明細を選択のため。
            List<ReceivingNoteSummary__c> sameRAES_objs = null;

            // 申請書ロック(Add_Approval_Status__c 更新のため)
            List<ReceivingNote__c> raObjs = [
                SELECT Id, Name
                       // Status__c,
                       // Add_Approval_Status__c,
                       // RequestNoJoinStr2__c
                  FROM ReceivingNote__c
                 WHERE Id = :parentObj.ReceivingNote__c
                   FOR UPDATE];
            if (raObjs.size() == 0) {
                throw new ControllerUtil.myException('没有检索出正确的收货清单,不能进行操作');
            }
            ReceivingNote__c raObj = raObjs[0];
            // parentObj のみ ロック
            //sameRAES_objs = [
            //    SELECT Id
            //         , Name
            //           // Fixture_Set_Idx__c,
            //           // ReceivingNote__r.RequestNoJoinStr2__c,
            //           // Rental_Num__c, Same_Accessory_flag__c,
            //           // Loaner_name__c,
            //           // Loaner_name_F__c,
            //           // Loaner_code__c,
            //           // Fixture_Set__c,
            //         , ReceivingNote__c
            //         , First_RND__c
            //           // First_RAESD__c,
            //           // Loaner_code_F__c,
            //           // UniqueKey__c
            //      FROM ReceivingNoteSummary__c
            //     WHERE Id = :parentObj.Id
            //       FOR UPDATE];

            // if (sameRAES_objs[0].Rental_Num__c > 1 && sameRAES_objs[0].Same_Accessory_flag__c) {
                // 同一付属品の一覧もロック
             sameRAES_objs = [
                 SELECT Id, Name
                        // Fixture_Set_Idx__c,
                        // ReceivingNote__r.RequestNoJoinStr2__c,
                        // Rental_Num__c,Same_Accessory_flag__c,
                        // Loaner_name__c,
                        // Loaner_name_F__c,
                        // Loaner_code__c,
                        // Fixture_Set__c,
                      , ReceivingNote__c
                      , First_RND__c
                        // Loaner_code_F__c,
                        // UniqueKey__c
                   FROM ReceivingNoteSummary__c
                  WHERE ReceivingNote__c = :parentObj.ReceivingNote__c
                    AND Fixture_Set__c = :parentObj.Fixture_Set__c
                    AND Id IN: sidList
                    // AND Same_Accessory_flag__c = true
                    // AND Cancel_Select__c = false
                    FOR UPDATE];
            if (sameRAES_objs.size() == 0) {
                throw new ControllerUtil.myException('没有检索出正确的收货清单一览,不能进行操作!');
            }

            Map<Id, Map<String, ReceivingNoteDetail__c>> rndMapSet = new Map<Id, Map<String, ReceivingNoteDetail__c>>();
            Map<Id, ReceivingNoteDetail__c> rndfirstMap = new Map<Id, ReceivingNoteDetail__c>();
            String soql ='';
            final String soqlStr = 'Select {0} {1} ';
            String strColumus1 = myComponentController.strColumus;
            if (strColumus1.contains(',passNo2__c') == false || strColumus1.contains('passNo2__c,') == false) {
                strColumus1 += ',passNo2__c';
            }

            if (strColumus1.contains(',ReceivingNoteSummary__c') == false || strColumus1.contains('ReceivingNoteSummary__c,') == false) {
                strColumus1 += ',ReceivingNoteSummary__c';
            }

            soql += String.format(soqlStr, new String[] {strColumus1 , ' From ReceivingNoteDetail__c WHERE ReceivingNoteSummary__c = :sameRAES_objs'});
            for (ReceivingNoteDetail__c rnd : Database.query(soql)) {
                if (rndMapSet.containsKey(rnd.ReceivingNoteSummary__c) == false) {
                    rndMapSet.put(rnd.ReceivingNoteSummary__c, new Map<String, ReceivingNoteDetail__c>());
                }
                if (rndfirstMap.containsKey(rnd.ReceivingNoteSummary__c) == false && rnd.Is_First_RND_F__c) {
                    rndfirstMap.put(rnd.ReceivingNoteSummary__c, rnd);
                }
                rndMapSet.get(rnd.ReceivingNoteSummary__c).put(rnd.UniqueKey__c, rnd);
            }
            // }
            // SUM出没有还没有批准的追加附属品和已经批准或者不是追加附属品的数量
            // 因为 #getSelectedDataSql() 用 Fixture_Set_Detail__c
            // 所以这里也用 AND Fixture_Set_Detail__c != null
            //List<AggregateResult> appendedGroupBy = [
            //        SELECT Fixture_Set_Detail__c, Count(Id) cnt
            //          FROM ReceivingNoteDetail__c
            //         WHERE ReceivingNoteSummary__c = :parentObj.Id
            //           AND Delete_Flag__c = false
            //           // AND Cancel_Select__c = false
            //           // AND Fixture_Set_Detail__c != null
            //         GROUP BY Fixture_Set_Detail__c];
            /* Key Fixture_Set_Detail__c value↓
             *                           Draft_Appended -> 未批准的追加附属品数量
             *                           Not_Draft_Appended -> 不是未批准的追加附属品数量
             *                           Accsessarys -> 所有的附属品数量
             */
            // Map<String, Map<String, Integer>> add_ApprovalMaps = new Map<String, Map<String, Integer>>();
            // for (AggregateResult a : appendedGroupBy) {
            //     Integer Draft_Appended = a.get('Draft_Appended__c') == null ? 0 : Integer.valueOf(a.get('Draft_Appended__c'));
            //     Integer Not_Draft_Appended = a.get('Not_Draft_Appended__c') == null ? 0 : Integer.valueOf(a.get('Not_Draft_Appended__c'));
            //     add_ApprovalMaps.put(String.valueOf(a.get('Fixture_Set_Detail__c')),
            //         new Map<String, Integer>{
            //             'Draft_Appended' => Draft_Appended,
            //             'Not_Draft_Appended' => Not_Draft_Appended,
            //             'Accsessarys' => a.get('cnt') == null ? 0 : Integer.valueOf(a.get('cnt'))
            //         });
            // }
            List<WrapperInfo> targetViewList = new List<WrapperInfo>();
            // 删除未审批追加附属品ERROR信息
            String deleteAdd_ApprovalErrorMessages = '';
            // 删除未审批追加附属品信息
            // 因为有Error的时候不现实成功信息所以需要分开保存最后判断显示什么信息
            String deleteAdd_ApprovalMessages = '';
            Boolean haveError = false;
            Integer j = 0;

            for (WrapperInfo wprInfo : viewList) {
                ReceivingNoteDetail__c robj = (ReceivingNoteDetail__c) wprInfo.sobj;
                // targetViewList.add(wprInfo);
                if (j == 0 && robj.Fixture_Set_New_Quantity__c < 1) {
                // if (j == 0 && robj.Fixture_Set_New_Quantity__c < 1) {
                // From 王硕 20180104 没有强制要求必须申请标配的备品。 非选配的也可以不申请。
                   // robj.Rental_Num__c.addError('非追加附属品,数量不能为0');
                   robj.Fixture_Set_New_Quantity__c.addError('非追加附属品,数量不能为0');
                   return null;
                }
                // 当数量大于0或者数量为0但是是草案中的追加附属品的话可以修改数量
                // if (robj.Rental_Num__c > 0 || robj.Draft_Appended__c == 1) {
                //     if (add_ApprovalMaps.containsKey(robj.Fixture_Set_Detail__c)) {
                //         Map<String, Integer> add_ApprovalMap = add_ApprovalMaps.get(robj.Fixture_Set_Detail__c);
                //         //有删除操作。并且未审批追加附属品大于0
                //         if (robj.Rental_Num__c < add_ApprovalMap.get('Accsessarys') && add_ApprovalMap.get('Draft_Appended') > 0) {
                //             haveAdd_ApprovalDelete = true;
                //             // 明细数量小于已批准的追加附属品加上非追加附属品
                //             if (robj.Rental_Num__c < add_ApprovalMap.get('Not_Draft_Appended')
                //                     && raObj.Status__c != FixtureUtil.raStatusMap.get(FixtureUtil.RaStatus.Cao_An_Zhong.ordinal())
                //                     && raObj.Add_Approval_Status__c == FixtureUtil.raStatusMap.get(FixtureUtil.RaStatus.Cao_An_Zhong.ordinal())) {
                //                 deleteAdd_ApprovalErrorMessages += String.format(deleteAdd_ApprovalErrorMessage,
                //                                                 new String[]{String.valueOf(wprInfo.lineNo + 1),
                //                                                              String.valueOf(add_ApprovalMap.get('Accsessarys')),
                //                                                              String.valueOf(add_ApprovalMap.get('Draft_Appended'))});
                //                 deleteAdd_ApprovalErrorMessages += '\n';
                //                 haveError = true;
                //             }
                //             // 有删除操作并且明细数量大于等于已批准的追加附属品加上非追加附属品
                //             else if (robj.Rental_Num__c >= add_ApprovalMap.get('Not_Draft_Appended')
                //                     && raObj.Status__c != FixtureUtil.raStatusMap.get(FixtureUtil.RaStatus.Cao_An_Zhong.ordinal())
                //                     && raObj.Add_Approval_Status__c == FixtureUtil.raStatusMap.get(FixtureUtil.RaStatus.Cao_An_Zhong.ordinal())) {
                //                 deleteAdd_ApprovalMessages += String.format(deleteAdd_ApprovalMessage,
                //                                                 new String[]{String.valueOf(wprInfo.lineNo + 1),
                //                                                              String.valueOf(add_ApprovalMap.get('Accsessarys')),
                //                                                              String.valueOf(add_ApprovalMap.get('Draft_Appended')),
                //                                                              String.valueOf(robj.Rental_Num__c),
                //                                                              String.valueOf(add_ApprovalMap.get('Draft_Appended') - (add_ApprovalMap.get('Accsessarys') - robj.Rental_Num__c))});
                //                 deleteAdd_ApprovalMessages += '\n';
                //             }
                //         }
                //     }
                //     targetViewList.add(wprInfo);
                // } else if (String.isNotBlank(robj.Id)) {
                //     if (raObj.Status__c != FixtureUtil.raStatusMap.get(FixtureUtil.RaStatus.Cao_An_Zhong.ordinal())) {
                //         if (!parentObj.Substitute_flag__c) {
                //             robj.Rental_Num__c.addError('只有在草案中的状态下可以减少数量');
                //             return null;
                //         } else if (parentObj.Yi_Assigned_Cnt__c > 0) {
                //             // 分配代替品后，选择配套明细--'已分配件数 Yi_Assigned_Cnt__c'>0且状态为'草案中'时减少数量，报error
                //             robj.Rental_Num__c.addError('有明细已分配，不能减少数量');
                //             return null;
                //         }
                //     }
                // }
                j ++;
            }

            if (haveError) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, deleteAdd_ApprovalErrorMessages));
                return null;
            }

            //OLY_OCM-171 与可以选择存放地的简档一致
            Boolean is2B = System.Label.ProfileId_EquCenAdmin.contains(Userinfo.getProfileId())
                                   || Userinfo.getProfileId() == System.Label.ProfileId_SystemAdmin;
                                // || System.Label.ProfileId_EquCenCheckAndDepot.contains(Userinfo.getProfileId())
                                // || Userinfo.getProfileId() == System.Label.ProfileId_EquipmentCenter;

            Map<Id, ReceivingNoteDetail__c> setIdFirstDetailMap = new Map<Id, ReceivingNoteDetail__c>();
            Integer index = 0;

            for (WrapperInfo wprInfo : viewList) {
                ReceivingNoteDetail__c robj = (ReceivingNoteDetail__c) wprInfo.sobj;
                LineExtraInfo extraInfo = extraInfoList.get(wprInfo.lineNo);
                Integer maxIndexInLoop = null;
                System.debug(robj.Rental_Num__c);
                //update byr entx 20210728 新品收货_集中备品_建立新品入库标准配套 start
                // for (Integer i = 0; i < robj.Rental_Num__c; i++) {
                for (Integer i = 0; i < robj.Fixture_Set_New_Quantity__c; i++) {
                //update byr entx 20210728 新品收货_集中备品_建立新品入库标准配套 end
                    // sameRAES_objs には自分の明細か、申請 直後の明細しかないか の条件があります。
                    // なので、直接cloneしてOKです。
                    for (ReceivingNoteSummary__c sameRAES_obj : sameRAES_objs) {
                        System.debug(sameRAES_obj);

                        // default是 clone, 但是 下面的Logic有对 rupsobj = xxx; 设值的地方
                        ReceivingNoteDetail__c rupsobj = robj.clone(false);

                        if (index == 0 && i == 0) {
                            rupsobj = rndfirstMap.get(sameRAES_obj.Id);
                            resetrnd(robj, rupsobj);
                            rupsobj.Is_Body__c = robj.Is_Body__c;
                            rupsobj.Fixture_Set_Detail__c = robj.Fixture_Set_Detail__c;
                            //addby rentx start
                            // rupsobj.Rental_Num__c = robj.Rental_Num__c;
                            rupsobj.Fixture_Set_New_Quantity__c = robj.Fixture_Set_New_Quantity__c;
                            //add by rentx end
                            rupsobj.Id = sameRAES_obj.First_RND__c;
                            rupsobj.passNo3__c = String.valueOf(i+1);
                            mfUpdate.add(rupsobj);

                        }
                        else {
                            // 借出申请RequestNoJoinStr2__c：借出申请配套一览Id：配套明细Id
                            String uniqueKeyStr = raObj.Id + ':' + sameRAES_obj.Id
                                    + ':'+ robj.Fixture_Set_Detail__c + ':';
                            String uk = uniqueKeyStr;
                            String passNo3 = String.valueOf(i+1);
                            // default値は最初に設定した
                            if (i < extraInfo.indexFromUniqueKeyList.size()) {
                                // rupsobj.passNo3__c = String.valueOf(extraInfo.indexFromUniqueKeyList[i]);
                                passNo3 = String.valueOf(extraInfo.indexFromUniqueKeyList[i]);
                                uk = uniqueKeyStr + (extraInfo.indexFromUniqueKeyList[i] - 1);
                                uniqueKeyStr += passNo3;
                            } else if (extraInfo.maxIndexFromUniqueKey != null) {
                                if (maxIndexInLoop == null) { maxIndexInLoop = extraInfo.maxIndexFromUniqueKey; }
                                maxIndexInLoop++;
                                uniqueKeyStr = raObj.Id + ':' + sameRAES_obj.Id
                                        + ':'+ robj.Fixture_Set_Detail__c + ':'+ maxIndexInLoop;
                                uk = raObj.Id + ':' + sameRAES_obj.Id
                                        + ':'+ robj.Fixture_Set_Detail__c + ':'+ (maxIndexInLoop - 1);
                                // rupsobj.passNo3__c = String.valueOf(maxIndexInLoop);
                                passNo3 = String.valueOf(maxIndexInLoop);
                            } else {
                                // uniqueKeyStr に default の passNo3__c を使う
                                uk = uniqueKeyStr + String.valueOf(i);
                                uniqueKeyStr += passNo3;
                            }

                            if (rndMapSet.get(sameRAES_obj.Id).containsKey(uniqueKeyStr)) {
                                rupsobj = rndMapSet.get(sameRAES_obj.Id).get(uniqueKeyStr).clone(false);

                            }
                            else if (rndMapSet.get(sameRAES_obj.Id).containsKey(uk)) {
                                rupsobj = rndMapSet.get(sameRAES_obj.Id).get(uk).clone(false);
                            }
                            else if (i == 0) {
                                rupsobj.DataConfirmation__c = false;
                                rupsobj.EquipmentSet_Managment_Code__c = null;
                                rupsobj.Salesdepartment__c = null;
                                rupsobj.SalesProvince__c = null;
                                rupsobj.Product_category__c = null;
                                rupsobj.Equipment_Type__c = null;
                                rupsobj.Manage_type__c = null;
                                rupsobj.unknow_serial_NO_product__c = null;
                                rupsobj.Loaner_accsessary__c = null;
                            }
                            rupsobj.Is_Body__c = robj.Is_Body__c;
                            rupsobj.Fixture_Set_Detail__c = robj.Fixture_Set_Detail__c;
                            //add by rentx start
                            // rupsobj.Rental_Num__c = robj.Rental_Num__c;
                            rupsobj.Fixture_Set_New_Quantity__c = robj.Fixture_Set_New_Quantity__c;
                            //add by rentx end
                            resetrnd(robj, rupsobj);

                            if (String.isNotBlank(passNo3)) {
                                rupsobj.passNo3__c = passNo3;
                            }
                            else {
                                rupsobj.passNo3__c = String.valueOf(i+1);
                            }
                            rupsobj.Id = null;
                            System.debug(uniqueKeyStr);
                            System.debug(rupsobj.Id);
                            System.debug(rupsobj.passNo3__c + '测试uniqueKeyStr:' + uniqueKeyStr);
                            rupsobj.UniqueKey__c          = uniqueKeyStr;
                            rndMapSet.get(sameRAES_obj.Id).put(uniqueKeyStr, rupsobj);
                            // 配套（or 申请）·から
                            rupsobj.ReceivingNoteSummary__c = sameRAES_obj.Id;

                            // rupsobj.ReceivingNote__c               = sameRAES_obj.ReceivingNote__c;

                            mfUpsert.add(rupsobj);
                            if (setIdFirstDetailMap.containsKey(sameRAES_obj.Id) == false || rupsobj.Is_Body__c == true) {
                                setIdFirstDetailMap.put(sameRAES_obj.Id, rupsobj);
                            }
                            if (String.isBlank(rupsobj.Id)
                                    && !String.isBlank(uniqueKeyStr)) {
                                // IdあるのレコードをIdクリアSetに追加
                                clearUniqueKeySet.add(uniqueKeyStr);
                            }
                        }
                    }
                }
                index ++;
            }
            System.debug(mfUpsert);
            if (mfUpsert.isEmpty() && mfUpdate.isEmpty()) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,
                        '请输入明细的数量。'));
                return null;
            }
            else {
                if (isAcceptance) {
                    Set<String> fsdIdSet = new Set<String>();
                    List<ReceivingNoteDetail__c> rndList = [SELECT Id
                                , UniqueKey__c
                                , AcceptanceResult__c
                                , Fixture_Set_Detail__c
                                , Change_Point__c
                                , ReceivingNoteSummary__c
                                , Manage_type__c
                             FROM ReceivingNoteDetail__c
                            WHERE ReceivingNoteSummary__c IN :sidList
                              AND Delete_Flag__c = false];
                    Map<String, ReceivingNoteDetail__c> rndMap = new Map<String, ReceivingNoteDetail__c>();
                    for (ReceivingNoteDetail__c rnd : rndList) {
                        rndMap.put(rnd.UniqueKey__c, rnd);
                        if (String.isNotBlank(rnd.Fixture_Set_Detail__c)
                            && rnd.Change_Point__c != '新建') {
                            fsdIdSet.add(''+rnd.ReceivingNoteSummary__c+rnd.Fixture_Set_Detail__c);
                        }
                    }
                    for (ReceivingNoteDetail__c rnd : mfUpsert) {
                        if (rndMap.containsKey(rnd.UniqueKey__c)) {
                            if (rndMap.get(rnd.UniqueKey__c).Change_Point__c == '删除') {
                                rnd.Change_Point__c = '';
                            }
                        }
                        else {
                            if (fsdIdSet.contains(''+rnd.ReceivingNoteSummary__c+rnd.Fixture_Set_Detail__c)) {
                                rnd.Change_Point__c = '增加';
                            }
                            else {
                                rnd.Change_Point__c = '新建';
                                //rnd.DataConfirmation__c = false;
                                //rnd.EquipmentSet_Managment_Code__c = null;
                                //rnd.Salesdepartment__c = null;
                                //rnd.SalesProvince__c = null;
                                //rnd.Product_category__c = null;
                                //rnd.Equipment_Type__c = null;
                                //rnd.Manage_type__c = null;
                                //rnd.unknow_serial_NO_product__c = null;
                                //rnd.Loaner_accsessary__c = null;

                            }
                        }
                    }
                }
                //upsert mfUpsert UniqueKey__c;
                // Upsert
                if (mfUpsert.size() > 0) {
                    FixtureUtil.withoutUpsertRnd(mfUpsert);
                }
                if (mfUpdate.size() > 0) {
                    FixtureUtil.withoutUpdate(mfUpdate);
                }

                // 削除
                FixtureUtil.delRND_excludedUpserted(sameRAES_objs, mfUpsert, mfUpdate, isAcceptance);
                // System.debug('备品配套借出一览明细保存成功');
                // for (ReceivingNoteSummary__c sameRAES_obj: sameRAES_objs) {
                //     ReceivingNoteDetail__c rupsobj = setIdFirstDetailMap.get(sameRAES_obj.Id);
                //     sameRAES_obj.First_RND__c = rupsobj.Id;
                // }
                //update sameRAES_objs;
                // FixtureUtil.withoutUpdate(sameRAES_objs);
            }

            //申请书的追加附属品状态需
            //因为是申请的状态所以需要要看是不是申请书下所有的追加附属品(不只是这一个一览下的)
            // List<AggregateResult> add_Approvals = [Select Count(Id) cnt, SUM(Draft_Appended__c) Draft_Appended__c
            //         From ReceivingNoteDetail__c
            //        Where ReceivingNote__c = :parentObj.ReceivingNote__c
            //          AND Cancel_Select__c = false
            //          AND Fixture_Set_Detail__c != null
            //          AND ApplyPersonAppended_F__c = true
            //        Group by ReceivingNote__c];
            // Integer Draft_Appended = 0;
            // Integer add_ApprovalCount = 0;
            // if (!add_Approvals.isEmpty()) {
            //     Draft_Appended = add_Approvals[0].get('Draft_Appended__c') == null ? 0 : Integer.valueOf(add_Approvals[0].get('Draft_Appended__c'));
            //     add_ApprovalCount = add_Approvals[0].get('cnt') == null ? 0 : Integer.valueOf(add_Approvals[0].get('cnt'));
            // }

            List<ReceivingNote__c> raList = new List<ReceivingNote__c>();
            // 有草案中的追加附属品并且申请书的状态不是草案中，&& 不是分配代替品 的需要改变状态为草案中
            // if (Draft_Appended > 0
            //         && raObj.Add_Approval_Status__c != FixtureUtil.raStatusMap.get(FixtureUtil.RaStatus.Cao_An_Zhong.ordinal())
            //         && (raObj.Status__c == FixtureUtil.raStatusMap.get(FixtureUtil.RaStatus.Yi_Pi_Zhun.ordinal())
            //             || raObj.Status__c == FixtureUtil.raStatusMap.get(FixtureUtil.RaStatus.Yi_Chu_Ku_Zhi_Shi.ordinal()))
            //         && parentObj.Substitute_Select_Again__c == false) {
            //     raObj.Add_Approval_Status__c = FixtureUtil.raStatusMap.get(FixtureUtil.RaStatus.Cao_An_Zhong.ordinal());
            //     raList.add(raObj);
            // }
            // 申请书单位已经没有草案中的附属品
            // else if (Draft_Appended == 0) {
            //     //没有追加附属品状态为空
            //     if (add_ApprovalCount == 0 && String.isNotBlank(raObj.Add_Approval_Status__c)) {
            //         raObj.Add_Approval_Status__c = '';
            //     }
            //     // 有追加附属品状态为草案中
            //     else if (add_ApprovalCount > 0  && raObj.Add_Approval_Status__c != FixtureUtil.raStatusMap.get(FixtureUtil.RaStatus.Yi_Pi_Zhun.ordinal())) {
            //         raObj.Add_Approval_Status__c = FixtureUtil.raStatusMap.get(FixtureUtil.RaStatus.Yi_Pi_Zhun.ordinal());
            //     }
            //     raList.add(raObj);
            // }
            if (!raList.isEmpty()) {
                FixtureUtil.withoutUpdate(raList);
            }
            // 更新成功才添加成功信息
            if (haveAdd_ApprovalDelete == true) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, deleteAdd_ApprovalMessages));

            }

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

        // 因为不能更新sidList所以需要在更新sidList前return
        if (haveAdd_ApprovalDelete == true) {
            return null;
        }

        if (saveType == '1') {
            searchOpp();
            saveType = '';
            return null;
        } else if (saveType == '2') {
        // ソート時の変更ある
            myComponentController.getSelectedDataInfo();
            getSqlWhereStr();
            myComponentController.sortTable();
            saveType = '';
            return null;
        } else {
            //借出备品配套明细选择画面
            List<String> uniqStrs = parentId.split(':');
            //画面参数为多个配套明细的UniqueKey__c，同一附属品情况下，一括设定该备品配套（group）下的所有借出备品配套明细
            //非同一附属品情况下，依次设定该备品配套所存在的借出备品配套明细的设定
            //判断是否同一附属品
            // if(parentObj.Same_Accessory_flag__c){
                sidList.remove(0);
            // }
            // else{
            //     system.debug('●●●●● uniqStrs  ' + uniqStrs );

            //     String tempSize = uniqStrs.get(uniqStrs.size()-1);
            //     // 分配代替品画面
            //     if (parentObj.Substitute_Select_Again__c) {
            //         tempSize = tempSize.substring(0, 1);
            //     }

            //     if(Integer.valueOf(tempSize) < parentObj.Rental_Num__c){
            //         List<String> uniqStrsTemp = new List<String> ();
            //         uniqStrsTemp.addall(uniqStrs);
            //         uniqStrsTemp.remove(uniqStrsTemp.size()-1);
            //         Integer currObjBan = Integer.valueOf(tempSize);
            //         uniqStrsTemp.add( (currObjBan + 1) + '');
            //         String uniqStrsNew = String.join(uniqStrsTemp, ':');
            //         sidList.set(0, uniqStrsNew);
            //     }else{
            //         sidList.remove(0);
            //     }

            // }

            // if (sidList.size() > 0) {
            //     String chkIdsStr = String.join(sidList, ',');
            //     PageReference pg = new PageReference('/apex/RentalFixtureSetDetilSelect');
            //     pg.getParameters().put('sids',chkIdsStr);
            //     pg.setRedirect(true);
            //     return pg;
            // } else {
                String returl1 = '/apex/ReceivingNoteWaitingReceipt?parId='+ parentObj.ReceivingNote__c;
                if (isAcceptance) {
                    returl1 = returl;
                }
                // 借出申请页面
                PageReference pg = new PageReference(returl1);
                pg.setRedirect(true);
                return pg;
            // }
        }
    }

    /**
     * メッセージ追加
     * @param robj 借出备品配套明细选择画面里显示的明细
     * @param rupsobj 实际需要Upsert的明细
    */
    private void resetrnd(ReceivingNoteDetail__c robj, ReceivingNoteDetail__c rupsobj) {
        // 配套入库产品
        rupsobj.Set_Arrival_Product__c = robj.Fixture_Set_Detail__r.Product2__c;
        if (null == rupsobj.Product_Arrival_Product__c) {
            rupsobj.Product_Arrival_Product__c = rupsobj.Default_Fixture_Arrival_Product__c;
            rupsobj.Product_Arrival_Product__c = rupsobj.Default_Fixture_Arrival_Product__c;
        }
        // 配套后，产品没变则清空
        if (rupsobj.Is_First_RND_F__c
            && rupsobj.Product_Old_Model_F__c == robj.Fixture_Set_Detail__r.Fixture_Model_No_F__c
        ) {
            rupsobj.Fixture_Arrival_Product__c = null;
            rupsobj.Fixture_Arrival_Process__c = null;
            rupsobj.Fixture_Arrival_Product__c = null;
            rupsobj.Fixture_Arrival_Process__c = null;
        }
        // 配套后，产品变了则设为变体
        else if (rupsobj.Is_First_RND_F__c
            && rupsobj.Product_Old_Model_F__c != robj.Fixture_Set_Detail__r.Fixture_Model_No_F__c
        ) {
            // 20231027 DB202310498138 【系统调查】紧急！新品收货操作报错 lc Start
            //rupsobj.Fixture_Arrival_Product__c = robj.Set_Arrival_Product__c;
            rupsobj.Fixture_Arrival_Product__c = robj.Fixture_Set_Detail__r.Product2__c;
            // 20231027 DB202310498138 【系统调查】紧急！新品收货操作报错 lc End
            rupsobj.Fixture_Arrival_Process__c = '变体';
        }
    }


    public PageReference cancel() {
        PageReference ret = null;
        if (!String.isBlank(parentObj.ReceivingNote__c)) {
            ret = new PageReference('/apex/ReceivingNoteWaitingReceipt?parId=' + parentObj.ReceivingNote__c);
        }
        return ret;
    }

    public PageReference goBack() {
        PageReference ret = null;
        if (isAcceptance) {
            ret = new PageReference(returl);
        }
        else if (!String.isBlank(parentObj.ReceivingNote__c)) {
            ret = new PageReference('/apex/ReceivingNoteSummarySelect?pt_recid=' + parentObj.ReceivingNote__c + '&raesid=' + raesid);
        }
        return ret;
    }

    private String makeSoql() {

        String soql ='';
        soql += 'where Id != null';

        //备品配套下的所有明细
        if (!String.isBlank(this.parentId)) {
system.debug('●●●●● parentObj ' + parentObj );
            soql += ' and Fixture_Set__c = \'' + parentObj.Fixture_Set__c + '\'';
        }
        // soql += ' order by SortInt__c';
        system.debug(soql);
        return soql;
    }

    public override void setViewList(List<sObject> queryList) {
        viewList = new List<WrapperInfo>();                             // selectedGroupData と同じ順番、同じ件数
        extraInfoList = new List<LineExtraInfo>();  // viewList と同じ順番、同じ件数
        Set<Id> selectedFSDSet = new Set<Id>();
        // 選択済みの明细
        if (selectedData.size() > 0) {
            selectedGroupData = new List<ReceivingNoteDetail__c>();
            Map<Integer, ReceivingNoteDetail__c> sltFixtureMap = new Map<Integer, ReceivingNoteDetail__c>();
            Map<Integer, Integer> sltFixtureCnt = new Map<Integer, Integer>();
            Map<Integer, LineExtraInfo> sltExtraInfoMap = new Map<Integer, LineExtraInfo>();
            // グループリスト取得
            // group by Fixture_Set_Detail__c
            // order by Fixture_Set_Detail__r.SortInt__c
            for (SObject sobj : selectedData) {
                ReceivingNoteDetail__c raesdobj = (ReceivingNoteDetail__c) sobj;
                //设置新品配套数 by rentx 20210825 start 
                raesdobj.Fixture_Set_New_Quantity__c = raesdobj.Fixture_Set_Detail__r.Fixture_Set_New_Quantity__c;
                //设置新品配套数 by rentx 20210825 end
                //之前数量的逻辑不要了  直接取备品配套明细上的数量就可以 add by rentx 20210827 start
                raesdobj.Rental_Num__c = raesdobj.Fixture_Set_Detail__r.Quantity__c;
                //之前数量的逻辑不要了  直接取备品配套明细上的数量就可以 add by rentx 20210827 end 


                if (!sltFixtureMap.containsKey(raesdobj.Fixture_Set_Detail__r.SortInt__c.intValue())) {
                    // if (!raesdobj.Cancel_Select__c) {
                        sltFixtureMap.put(raesdobj.Fixture_Set_Detail__r.SortInt__c.intValue(), raesdobj);
                        selectedGroupData.add(raesdobj);
                        sltFixtureCnt.put(raesdobj.Fixture_Set_Detail__r.SortInt__c.intValue(), 0);
                        LineExtraInfo extraInfo = new LineExtraInfo(raesdobj);
                        extraInfoList.add(extraInfo);
                        sltExtraInfoMap.put(raesdobj.Fixture_Set_Detail__r.SortInt__c.intValue(), extraInfo);
                    }
                // } else {
                //     LineExtraInfo extraInfo = sltExtraInfoMap.get(raesdobj.Fixture_Set_Detail__r.SortInt__c.intValue());
                //     extraInfo.updateExtraInfo(raesdobj);
                // }
                // if (raesdobj.Cancel_Select__c) {
                //     // 念のため追加した
                //     continue;
                // }

                /*注释 by rentx 20210827   ReceivingNoteDetail__c nobj = sltFixtureMap.get(raesdobj.Fixture_Set_Detail__r.SortInt__c.intValue());
                Integer nCnt = sltFixtureCnt.get(raesdobj.Fixture_Set_Detail__r.SortInt__c.intValue());
                nCnt++;
                sltFixtureCnt.put(raesdobj.Fixture_Set_Detail__r.SortInt__c.intValue(), nCnt);
                nobj.Rental_Num__c = nCnt;
                //nobj.VF_Rental_Num__c = nCnt;*/
                selectedFSDSet.add(raesdobj.Fixture_Set_Detail__c);
            }
            for (Integer i = 0; i < selectedGroupData.size(); i++) {
                // 501を超えた場合前500のみを出す
                if (i >= getSearchNumMax()) { break; }
                ReceivingNoteDetail__c raesdobj = selectedGroupData[i];
                WrapperInfo info = new WrapperInfo(raesdobj, myComponentController);
                //if (String.isNotBlank(raesdobj.RNDAssert__c)) {
                    // info.canEdit = false;
                //}
                viewList.add(info);
                viewList[viewList.size() - 1].lineNo = viewList.size() - 1;
                raesdobj.passNo2__c = raesdobj.Fixture_Set_Detail__r.SortInt__c.format().leftpad(2, '0');
            }
        }
        if (queryList.size() == 0) {
            return;
        }

        Savepoint sp = Database.setSavepoint();
        ReceivingNoteDetail__c rnd;
        // 数式項目値を取れるのために、一回Insertする
        List<ReceivingNoteDetail__c> tempList = new List<ReceivingNoteDetail__c>();
        for (Integer i = 0; i < queryList.size(); i++) {
            // 501を超えた場合前500のみを出す
            if (i == getSearchNumMax()) { break; }
            ReceivingNoteDetail__c mf = new ReceivingNoteDetail__c();
            mf.Fixture_Set_Detail__c                = queryList[i].Id;
            Fixture_Set_Detail__c fsdobj            = (Fixture_Set_Detail__c) queryList[i];
            mf.Is_Body__c                           = fsdobj.Is_Body__c;

            //设置新品配套数 start 20210825 
            mf.Fixture_Set_New_Quantity__c = fsdobj.Fixture_Set_New_Quantity__c;
            //设置数量
            mf.Rental_Num__c                        = fsdobj.Quantity__c;
            //设置新品配套数 end 20210825 
            /*注释 by rentx 20210827 if (selectedData.size() > 0) {
                fsdobj.Quantity__c = 0;
            } else {
                fsdobj.Quantity__c = fsdobj.Quantity__c == null ? 0 : fsdobj.Quantity__c;
            }*/
            System.debug(fsdobj.Is_Optional__c);
            System.debug(fsdobj.Quantity__c);
            /*if 注释 by rentx 20210827 (fsdobj.Is_Optional__c == false) {
                mf.Rental_Num__c                        = fsdobj.Quantity__c;
                //mf.VF_Rental_Num__c                     = fsdobj.Quantity__c;
                System.debug('aaaaaa');
            }
            else {
                mf.Rental_Num__c                        = 0;
                //mf.VF_Rental_Num__c                     = 0;
                System.debug('bbbbbb');
            }*/
            mf.DataMigration_Flag__c                = true;
            if (viewList.size() == 0
                    && i == 0) {
                mf.Id = sonObj.Id;
                rnd = mf;
            }
            else {
                mf.ReceivingNoteSummary__c        = parentObj.Id;
                mf.ReceivingNote__c                      = parentObj.ReceivingNote__c;
                tempList.add(mf);
            }
        }

        if (rnd != null) {
            Database.SaveResult[] results = FixtureUtil.withoutupdate(new ReceivingNoteDetail__c[]{rnd}, false);
        }

        Database.SaveResult[] results = FixtureUtil.withoutInsert(tempList, false);

        final String soqlStr = 'Select {0} {1} ';
        String whereStr = ' FROM ReceivingNoteDetail__c WHERE (ID in: tempList ' + (rnd == null ? '' : ' OR Id = \'' + rnd.Id+ '\'') + ' ) AND Delete_Flag__c = false ';
        String soql = String.format(soqlStr, new String[] {myComponentController.strColumus , whereStr});
        System.debug(soql);
        tempList = Database.query(soql);
        System.debug(tempList);
        if (queryList.size() != tempList.size()) {
            //error message 検索処理正しくありません、システム管理者に連絡してください。
            for (Integer i = 0; i < results.size(); i ++) {
                Database.SaveResult dmlResult = results[i];
                if (!dmlResult.isSuccess()) {
                    System.debug(System.LoggingLevel.ERROR, '第[' + (i + 1) + ']条 upsert error:' + dmlResult);
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,
                            '第[' + (i + 1) + ']条 upsert error:' + dmlResult));
                    // 1件目だけlogに出す
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,
                            System.Label.CreateRelationListSearchError));
                    Database.rollback(sp);
                    return;
                }
            }
        }
        // 強制ロールバック
        Database.rollback(sp);
        Map<String, SObject> fsDMap = new Map<String,SObject>();
        for(ReceivingNoteDetail__c fsd : tempList){
            ReceivingNoteDetail__c robj;
            if (fsd.Id != sonObj.Id) {
                robj = fsd.clone(false);
            }
            else {
                robj = fsd;
            }
            robj.DataMigration_Flag__c = false;
            //add by rentx 20210825 start 新品配套数赋值
            robj.Fixture_Set_New_Quantity__c = robj.Fixture_Set_Detail__r.Fixture_Set_New_Quantity__c;
            //add by rentx 20210825 end 新品配套数赋值

            fsDMap.put(fsd.Fixture_Set_Detail__c, robj);
        }

        Integer addedNum = 0;
        Map<Integer, ReceivingNoteDetail__c> sltFixtureMap = new Map<Integer, ReceivingNoteDetail__c>();
        for (Integer i = 0; i < queryList.size(); i++) {

            addedNum ++;
            // 501を超えた場合前500のみを出す
            if (addedNum == getSearchNumMax()) { break; }

            if (selectedFSDSet.contains(queryList[i].Id)) {
                continue;
            }

            SObject mf = fsDMap.get(queryList[i].Id);
            ReceivingNoteDetail__c raesdobj = (ReceivingNoteDetail__c) mf;
            System.debug('raesdobj = ' + raesdobj);
            System.debug('raesdobj = ' + raesdobj.Fixture_Set_Detail__r);
            System.debug('raesdobj = ' + raesdobj.Fixture_Set_Detail__r.SortInt__c);
            if (!sltFixtureMap.containsKey(raesdobj.Fixture_Set_Detail__r.SortInt__c.intValue())) {
                sltFixtureMap.put(raesdobj.Fixture_Set_Detail__r.SortInt__c.intValue(), raesdobj);
                // 2回目以降、設定してない行は0にする
                // if (!selectedData.isEmpty()) {
                // OLY_OCM-404: 选择配套明细里，无论主体还是附属品，都设置默认数量为0。
                // raesdobj.Rental_Num__c    = 0;
                // raesdobj.VF_Rental_Num__c = 0;
                // }
                WrapperInfo info = new WrapperInfo(raesdobj, myComponentController);
                if (viewList.size() == 0) {
                    // info.canEdit = false;
                }
                viewList.add(info);
                extraInfoList.add(new LineExtraInfo(null));
                viewList[viewList.size() - 1].lineNo = viewList.size() - 1;
                raesdobj.passNo2__c = raesdobj.Fixture_Set_Detail__r.SortInt__c.format().leftpad(2, '0');
                //raesdobj.IndexFromUniqueKey_Text__c = viewList.size().format().leftpad(2, '0');
            }
        }

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


    public class LineExtraInfo {
        public Integer maxIndexFromUniqueKey;           // { get; set; }
        public List<Decimal> indexFromUniqueKeyList;    // { get; set; }
        public Set<String> raesdUniqueKeySet;           // { get; set; }

        // Cancel_Select 処理しない
        public LineExtraInfo(ReceivingNoteDetail__c raesdobj) {
            // maxIndexFromUniqueKey を null にする
            raesdUniqueKeySet = new Set<String>();
            indexFromUniqueKeyList = new List<Decimal>();
            if (raesdobj == null || String.isBlank(raesdobj.Id)) {
                // 新規行、空のインスタンスを返す
                return;
            }
            // if (raesdobj.Cancel_Select__c) {
            //     throw new ControllerUtil.myException('raesdobj is Canceled.');
            // }
            // raesdUniqueKeySet.add(raesdobj.UniqueKey__c);
            // indexFromUniqueKeyList.add(raesdobj.passNo3__c);
            // maxIndexFromUniqueKey = raesdobj.passNo3__c.intValue();
        }

        // Cancel_Select も処理対象 (maxIndexFromUniqueKeyを更新するために)
        public void updateExtraInfo(ReceivingNoteDetail__c raesdobj) {
            if (raesdobj == null || String.isBlank(raesdobj.Id)
                    || maxIndexFromUniqueKey == null) {
                // 新規行、なにも更新しない
                return;
            }
            // if (raesdUniqueKeySet.contains(raesdobj.UniqueKey__c)) {
            //     return;
            // }
            // if (!raesdobj.Cancel_Select__c) {
            //     raesdUniqueKeySet.add(raesdobj.UniqueKey__c);
            //     indexFromUniqueKeyList.add(raesdobj.passNo3__c);
            // }
            // Integer indexFromUniqueKey = raesdobj.passNo3__c.intValue();
            // if (indexFromUniqueKey > maxIndexFromUniqueKey) {
            //     maxIndexFromUniqueKey = raesdobj.passNo3__c.intValue();
            // }
        }
    }
    public void sendEmail() {
        Savepoint sp = Database.setSavepoint();
        try{
            String emailBody = System.currentPageReference().getParameters().get('emailBody');
            String templateBody = '【自由填写内容】\n{0}\n';
                   templateBody += '备品配套：\n';
            emailBody = String.format(templateBody, new List<String> {emailBody});
            String emailMsg = '';
            List<ReceivingNoteSummary__c> selectedRnsList = [
                    SELECT Id
                         , No_Matching_Reminder_Email_Text__c
                         , Fixture_Set__r.Name
                      FROM ReceivingNoteSummary__c
                     WHERE Id =:parentId
                     FOR UPDATE
                    ];
            for (ReceivingNoteSummary__c rns : selectedRnsList) {
                rns.No_Matching_Reminder_Email_Text__c = null;
            }
            update selectedRnsList;
            for (ReceivingNoteSummary__c rns : selectedRnsList) {
                rns.No_Matching_Reminder_Email_Text__c = emailBody + rns.Fixture_Set__r.Name;
            }
            update selectedRnsList;
            ApexPages.Message vfApplyMsg = new ApexPages.Message(ApexPages.severity.INFO, '已发送');
            ApexPages.addMessage(vfApplyMsg);
        }
        catch (Exception e) {
            Database.rollback(sp);
            ApexPages.addMessages(e);
        }
    }
}