/**
 * 备品配套选择
 */
public with sharing class ConsumFixtureSetSelectController extends CreateRelationListPagingCtrlBase {
    private List<LineExtraInfo> extraInfoList;  // viewList と同じ順番、同じ件数

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

    /* 選択されたデータ取得用Soql　Fromから*/
    public override String getSelectedDataSql() {
        // オブジェクトAPI名
        selectedDataSql = ' From Consum_Apply_Equipment_Set__c';
        selectedDataSql += ' where Consum_Apply__c = \'' + String.escapeSingleQuotes(parentId) + '\'';
        selectedDataSql += '   and Cancel_Select__c = False';
        // 跳转分配代替品画面--选中一览不在这里显示
        if (String.isNotBlank(inRaesId)) {
            selectedDataSql += ' and Id = null';
        }
        selectedDataSql += (' order by '
                        //+ 'Fixture_Set__r.Loaner_code__c,'
                        + 'IndexFromUniqueKey__c');
        myComponentController.columnRightRW.put('Model_No__c', 'r');
        myComponentController.columnRightRW.put('You_Xiao_Qi_Ku_Cun_Jia__c', 'r');
        myComponentController.columnRightRW.put('Yi_Guo_Qi_Ku_Cun_Jia__c', 'r');
        myComponentController.columnRightRW.put('You_Xiao_Ku_Cun_Jia__c', 'r');
        myComponentController.columnRightRW.put('Consum_Start_Date__c', 'r');
        for (Integer i = 0; i < myComponentController.titleRight.size(); i ++) {
            System.debug(myComponentController.titleRight[i]);
            if (myComponentController.titleRight[i] == Consum_Apply_Equipment_Set__c.You_Xiao_Ku_Cun_Jia__c.getDescribe().getLabel()) {
                myComponentController.titleRight[i] = '库存';
                break;
            }
        }
        return selectedDataSql;
    }

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

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

    public override List<String> getColumnFieldList() {
        // strColumus 里加 field
        return new List<String>{'Id', 'Consum_Apply__c', 'Consum_Apply__r.Status__c', 'Consum_Num__c',
                                //'Fixture_Set__r.Name',
                                'RetalFSetDetail_Cnt__c', 'Model_No__c', 'UniqueKey__c', 'VF_Consum_Num__c', 'Consum_Start_Date_After_15_Day__c'};
    }
    public override List<String> getHiddenFieldList() {
        //return new List<String>{'Substitute_Select_Again__c'};
        return new List<String>();
    }
    // 画面里直接可以输入的項目 List
    public override List<String> getWritableColumnFieldList() {
        return new List<String>{'Consum_Num__c', 'Irreplaceable_flag__c', 'Same_Accessory_flag__c'};
    }
    // getObjName 连 getOriginObjName 的 FK
    public override String getFKColumnField() {
        return '';
    }

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

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

        if(getIsNeedRunSearch()){
            sqlWhereStr = this.makeSoql(keywdSort, true);
        }

        return sqlWhereStr;

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

    public override Boolean getIsNeedRunSearch() {
        return isReset == false;
    }

    public override Boolean getShowRecordCountMSG() {
        return false;
    }

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

    public String inRaesId { get; set;}   // 分配代替品传入参数
    public boolean isRadio { get; set;}   // 分配代替品（true）--选择配套画面只能单选
    public List<Consum_Apply_Equipment_Set__c> selectedRaesList { get; set; }   // 选中一览，非ListView显示--分配代替品
    // substituteId 現状 保存 btn 部分refersh ではない、その部分のロジック使われってないです。
    private String substituteId;          // 保存 btn(部分 refersh), 的时候 退避 保存后 借出一览的Id, 画面上选别的行的时候可以拿Id更新

    public Boolean saveType { get; set; }
    public Consum_Apply__c parentObj { get; set; }
    public Consum_Apply_Equipment_Set__c caes { get; set; }
    public List<Consum_Apply_Equipment_Set__c> selectedGroupData { get; set; }

    private Map<Date, Date> after15DayMap = new Map<Date, Date>(); 
    private Map<Date, OlympusCalendar__c> calendarMap = new Map<Date, OlympusCalendar__c>();
    private Map<String, Integer> excludedModelWherMap = new Map<String, Integer>();
    private Set<String> excludedModelWherSelectSet = new Set<String>();
    private Set<String> resetSet = new Set<String>();
    private Boolean isReset = false;
    // Equipment_Type__c != '检测用备品' 的保佑设备才可以申请
    // BTreeIndexKey__c =
    // Asset_Owner__c
    // Asset_loaner_category__c
    // Freeze_sign_Abandoned_Flag__c
    // Delete_Flag__c
    // AssetManageConfirm__c
    private String assetWhereBase = ' BTreeIndexKey__c = \'Olympus:耗材:false:false:true\' AND Equipment_Type__c != \'检测用备品\' AND Fixture_OneToOne_Link__c = null AND Internal_asset_location__c != null  AND RecordTypeId = \'01210000000kOPR\' AND ' + FixtureUtil.getAssetSoqlBase();

    public ConsumFixtureSetSelectController(ApexPages.StandardController stdController) {
        this();
    }

    public ConsumFixtureSetSelectController() {
        parentId = ApexPages.currentPage().getParameters().get('pt_recid');
        inRaesId = ApexPages.currentPage().getParameters().get('raesid');
        isRadio = String.isBlank(this.inRaesId) ? false : true;   // 分配代替品--选择配套画面只能单选
        String typeTypeStr = ApexPages.currentPage().getParameters().get('saveType');
        if(typeTypeStr == 'true'){
            saveType = true;
        }
        else{
            saveType = false;
        }
        caes = new Consum_Apply_Equipment_Set__c();
        caes.Consum_Start_Date__c = Date.today();
        //备品配套下的所有明细
        if (!String.isBlank(this.parentId)) {
            List<Consum_Apply__c> parentObjs = [
                    SELECT Id
                         , Name
                         , Status__c
                         , RequestNoJoinStr2__c
                         , demo_purpose2__c
                         , Internal_asset_location_F__c
                         , Salesdepartment__c
                         , Person_In_Charge__c
                         , Salesdept__c
                         , WorkPlace__c
                         , Request_shipping_day__c
                         //, Asset_loaner_start_day__c
                      FROM Consum_Apply__c
                     WHERE Id = :parentId];
            if (parentObjs.size() > 0) {
                parentObj = parentObjs.get(0);
            }
        }

        if (parentObj == null) {
            throw new ControllerUtil.myException('沒有指定备品借出申请或者数据不正。');
        }

        // OLY_OCM-404 分配代替品，跳转页面显示原选中一览信息
        if (!String.isBlank(this.inRaesId)) {
            this.selectedRaesList = [
                    select Id
                         , Name
                         //, Fixture_Set__c
                         //, Loaner_code_F__c
                         //, Loaner_name_F__c
                         , RetalFSetDetail_Cnt__c
                    from Consum_Apply_Equipment_Set__c
                    where Id = :inRaesId];
            if (selectedRaesList.size() == 0) {
                throw new ControllerUtil.myException('沒有指定备品借出申请一览或者数据不正。');
            }
        }
    }

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

    private void searchOppSetParam() {
        keywdSort = keyword;
    }

    public PageReference searchOpp() {
        excludedModelWherMap = new Map<String, Integer>();
        excludedModelWherSelectSet = new Set<String>();
        if (viewList != null && viewList.size()>0){
            for(WrapperInfo winfo:viewList){
                if (winfo.check){
                    Consum_Apply_Equipment_Set__c caes = (Consum_Apply_Equipment_Set__c) winfo.sobj;
                    String modelNo = caes.Model_No__c;
                    excludedModelWherMap.put(modelNo, Integer.valueOf(caes.Consum_Num__c));
                }
            }
        }
        if (selectedData.size() > 0) {
            for (SObject sobj : selectedData) {
                Consum_Apply_Equipment_Set__c raesobj = (Consum_Apply_Equipment_Set__c) sobj;
                excludedModelWherSelectSet.add(raesobj.Model_No__c);
            }
        }
        saveType = false;

        searchOppSetParam();

        if(!getIsNeedRunSearch() && isReset == false){
            return null;
        }

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

        getSqlWhereStr();
        // コンポーネントにSoqlを発行して、ページングする
        myComponentController.searchAndPaging();
        isReset = false;
        String message = '按型号汇总后得到 ' + viewList.size() + ' 条数据';
        // message = '<strong style="color:red">' + message + '</strong>';
        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, message));
        return null;
    }

    // public List<SelectOption> getCategory2Ops() {
    //     return Consum_ApplyUtil.getPlickList('Product2', 'Category2__c');
    // }

    // public List<SelectOption> getCategory3Ops() {
    //     return Consum_ApplyUtil.getPlickList('Product2', 'Category3__c');
    // }

    public PageReference save() {

        //20170906 upsert by UniqueKey__c
        List<Consum_Apply_Equipment_Set__c> mfUpsert = new List<Consum_Apply_Equipment_Set__c>();
        List<Consum_Apply_Equipment_Set__c> mfUpsert1 = new List<Consum_Apply_Equipment_Set__c>(); //存打勾的一览
        List<Consum_Apply_Equipment_Set__c> mfUpsert2 = new List<Consum_Apply_Equipment_Set__c>(); // 存最终保留的一览
        isReset = ApexPages.currentPage().getParameters().get('reset') == 'YES';
        String chkIdsStr = '';
        Savepoint sp = Database.setSavepoint();
        Set<String> clearUniqueKeySet = new Set<String>();
        Map<Id, Consum_Apply_Equipment_Set__c> caesMap = new Map<Id, Consum_Apply_Equipment_Set__c>();
        List<Consum_Apply_Equipment_Set_Detail__c> carsdList = new List<Consum_Apply_Equipment_Set_Detail__c>();
        try {
            List<Consum_Apply__c> raUpdate = [
                    SELECT Id
                         , RequestNoJoinStr2__c
                         , Status__c
                      FROM Consum_Apply__c where Id = :parentId for Update];
            if (raUpdate.isEmpty()) {
                throw new ControllerUtil.myException('没有找到申请单。');
            }
            Set<String> selectAssetIdSet = new Set<String>();
            for (Consum_Apply_Equipment_Set_Detail__c caesd : [SELECT Id, Asset__c
                                                                 FROM Consum_Apply_Equipment_Set_Detail__c
                                                                WHERE Consum_Apply__c = :parentId]
            ) {
                if (String.isNotBlank(caesd.Asset__c)) {
                    selectAssetIdSet.add(caesd.Asset__c);
                }
            }

            Boolean haveCheck = false;
            Map<String, Integer> caesCountMap = new Map<String, Integer>();
            for (WrapperInfo wprInfo : viewList) {
                Consum_Apply_Equipment_Set__c robj = (Consum_Apply_Equipment_Set__c) wprInfo.sobj;
                if (wprInfo.check) {
                    if (String.isNotBlank(robj.Id)) {
                        caesCountMap.put(robj.Id , 0);
                    }
                    haveCheck = true;
                    if (isReset) {
                        robj.Consum_Num__c = null;
                        resetSet.add(robj.Model_No__c);
                    }
                }
            }

            if (haveCheck == false) {
                throw new ControllerUtil.myException('请选择需要操作的一览');
            }

            if (caesCountMap.isEmpty() == false) {
                List<AggregateResult> caesdGroup = [SELECT count(Id) cnt, Consum_Apply_Equipment_Set__c
                         FROM Consum_Apply_Equipment_Set_Detail__c
                        WHERE Consum_Apply_Equipment_Set__c in :caesCountMap.keySet()
                          AND Asset__c != null
                          AND Detail_Finish__c = false
                        GROUP BY Consum_Apply_Equipment_Set__c];
                for (AggregateResult a : caesdGroup) {
                    String carsId = String.valueOf(a.get('Consum_Apply_Equipment_Set__c'));
                    Integer caesdCount = Integer.valueOf(a.get('cnt'));
                    caesCountMap.put(carsId, caesdCount);
                }
            }

            Set<String> modelNoSet = new Set<String>();
            // 画面中チェックされた対象、確定ボタンを押下すると、一つずつ順番に明細を選択のため。
            List<WrapperInfo> targetViewList = new List<WrapperInfo>();
            String wher = ' and ( ';
            for (WrapperInfo wprInfo : viewList) {
                Consum_Apply_Equipment_Set__c robj = (Consum_Apply_Equipment_Set__c) wprInfo.sobj;
                // 没打勾的不作为处理对象
                if (wprInfo.check) {
                    if (raUpdate[0].Status__c != '草案中'
                            && robj.Consum_Num__c != robj.VF_Consum_Num__c) {
                        // 0の場合deleteされるので、入力規則がすりぬけるので、ここでもチェックが必要です
                        robj.Consum_Num__c.addError('只有在草案中的状态下可以变更数量');
                        return null;
                    }
                    Integer num = 0;
                    // 如果不是动物实验
                    //2021-04-30 mzy update  备品课题-1577  start
                    if (parentObj.demo_purpose2__c != '动物实验' && parentObj.demo_purpose2__c != 'ET展箱') {
                    //2021-04-30 mzy update  备品课题-1577  end
                        // 如果没有效期库存（有效期为空）
                        if (robj.You_Xiao_Qi_Ku_Cun_Jia__c == null) {
                            num = Integer.valueOf(robj.You_Xiao_Ku_Cun_Jia__c);
                        }
                        else {
                            // 有效期不为空
                            num = Integer.valueOf(robj.You_Xiao_Qi_Ku_Cun_Jia__c);
                        }
                    }
                    else {
                        num = Integer.valueOf(robj.You_Xiao_Ku_Cun_Jia__c);
                    }
                    System.debug(robj.Consum_Num__c);
                    System.debug(robj.VF_Consum_Num__c);
                    System.debug(num);
                    Integer caesdCount = 0;
                    if (String.isNotBlank(robj.Id)) {
                        caesdCount = caesCountMap.get(robj.Id);
                    }

                    if (robj.Consum_Num__c != null && (robj.Consum_Num__c - caesdCount) > num) {
                        throw new ControllerUtil.myException('型号' + robj.Model_No__c + '没有足够的有效库存,请重新选择');
                    }
                    if (String.isNotBlank(robj.Id)) {
                        caesMap.put(robj.Id, robj);
                    }
                     mfUpsert1.add(robj);
                    if (robj.Consum_Num__c > 0) {
                        targetViewList.add(wprInfo);
                        mfUpsert.add(robj);
                        // 有数量的不作为删除对象
                        mfUpsert2.add(robj);
                        if (modelNoSet.contains(robj.Model_No__c) == false) {
                            modelNoSet.add(robj.Model_No__c);
                            wher += ' (Fixture_Model_No_F__c like \'%' + String.escapeSingleQuotes(robj.Model_No__c.replaceAll('%', '\\%')) + '%\'';
                            if (parentObj.demo_purpose2__c != '动物实验' && robj.Consum_Start_Date__c != null && parentObj.demo_purpose2__c != 'ET展箱') { //2021-04-30 mzy update  备品课题-1577 
                                System.debug(after15DayMap);
                                System.debug(robj.Consum_Start_Date__c);
                                Date d;
                                if (after15DayMap.containsKey(robj.Consum_Start_Date__c)) {
                                    d = after15DayMap.get(robj.Consum_Start_Date__c);
                                    robj.Consum_Start_Date_After_15_Day__c = d;
                                }
                                else {
                                    d = Consum_ApplyUtil.getWD_addday(robj.Consum_Start_Date__c, 15);
                                    robj.Consum_Start_Date_After_15_Day__c = d;
                                    after15DayMap.put(robj.Consum_Start_Date__c, d);
                                }
                                wher += ' AND (Consumable_Guaranteen_end__c = null OR Consumable_Guaranteen_end__c > ' + String.valueOf(d.year()) + '-' + String.valueOf(d.month()).leftPad(2, '0') + '-' + String.valueOf(d.day()).leftPad(2, '0') + ' )';
                            }
                            wher += ') OR';
                        }
                    }
                }
                else {
                    // 没打勾的不作为删除对象
                    mfUpsert2.add(robj);
                }
            }

            if (caesMap.isEmpty() == false) {
                caesMap = new Map<Id, Consum_Apply_Equipment_Set__c>([SELECT Id
                            , Consum_Num__c
                         FROM Consum_Apply_Equipment_Set__c
                        WHERE Id = :caesMap.keySet()
                          FOR UPDATE]);
            }

            if (mfUpsert.size() > 0) {
                wher = wher.removeEnd('OR');
                Date day = Date.today();
                Consum_ApplyUtil.withoutUpsert(mfUpsert);
                String soql = 'SELECT Id'
                            + ' , Fixture_Model_No_F__c'
                            + ' , You_Xiao_Ku_Cun__c'
                            + ' FROM Asset'
                            + ' WHERE (Id != null'
                            + wher + ')'
                            + ' AND ' + assetWhereBase
                            + ' )';
                List<String> conditionList = new List<String>();
                conditionList.addAll(selectAssetIdSet);
                Consum_ApplyUtil.withoutQueryListWithConditionList(soql + ' OR Id = :conditionList ' + ' FOR UPDATE', conditionList);

                Map<String, List<Asset>> assetMap = new Map<String, List<Asset>>(); //型号->List<Asset>
                Map<String, Integer> assetCountMap = new Map<String, Integer>();  // AssetId->有效库存
                System.debug(soql);

                String soqlAssetDepart = soql + ' AND (Salesdepartment__c = \'' + parentObj.Salesdepartment__c + '\''
                                                 + 'OR Salesdepartment__c = \'0.备品中心\')'
                                              +' ORDER BY Salesdepartment__c DESC, Consumable_Guaranteen_end__c nulls LAST';

                List<sObject> assetListDepart = Consum_ApplyUtil.withoutQueryList(soqlAssetDepart);

                for (sObject sobj : assetListDepart) {
                    Asset ass = (Asset) sobj;
                    if (assetMap.containsKey(ass.Fixture_Model_No_F__c) == false) {
                        assetMap.put(ass.Fixture_Model_No_F__c, new List<Asset>());
                    }
                    assetMap.get(ass.Fixture_Model_No_F__c).add(ass);
                    assetCountMap.put(ass.Id, Integer.valueOf(ass.You_Xiao_Ku_Cun__c));
                }
                Integer g = 0;
                for (Consum_Apply_Equipment_Set__c caes : mfUpsert) {
                    LineExtraInfo extraInfo;
                    if (extraInfoList.size() > 0 && g < extraInfoList.size() ) {
                        extraInfo = extraInfoList[g];
                    }
                    Integer maxIndexInLoop = null;
                    Integer maxIndexDeLoop = null;
                    if (assetMap.containsKey(caes.Model_No__c) || caesCountMap.containsKey(caes.Id)) {
                        List<Asset> assList = assetMap.get(caes.Model_No__c);
                        Integer caesdCount = 0;
                        if (String.isNotBlank(caes.Id)
                            && caesCountMap.containsKey(caes.Id)) {
                            caesdCount = caesCountMap.get(caes.Id);
                        }
                        for (Integer i = 0; i < caes.Consum_Num__c; i ++) {
                            Consum_Apply_Equipment_Set_Detail__c carsd = new Consum_Apply_Equipment_Set_Detail__c();
                            carsd.Consum_Apply_Equipment_Set__c = caes.Id;
                            carsd.Consum_Apply__c = parentObj.Id;
                            carsd.IndexFromUniqueKey__c = i+1;
                            carsd.Degree_Of_Importance__c = i+1;
                            if (extraInfo != null) {
                                if (i < extraInfo.indexFromUniqueKeyList.size()) {
                                    carsd.IndexFromUniqueKey__c = extraInfo.indexFromUniqueKeyList[i];
                                } else if (extraInfo.maxIndexFromUniqueKey != null) {
                                    if (maxIndexInLoop == null) { maxIndexInLoop = extraInfo.maxIndexFromUniqueKey; }
                                    maxIndexInLoop++;
                                    carsd.IndexFromUniqueKey__c = maxIndexInLoop;
                                }

                                if (i < extraInfo.degree_Of_ImportanceList.size()) {
                                    carsd.Degree_Of_Importance__c = extraInfo.degree_Of_ImportanceList[i];
                                } else if (extraInfo.maxDegree_Of_Importance != null) {
                                    if (maxIndexDeLoop == null) { maxIndexDeLoop = extraInfo.maxDegree_Of_Importance; }
                                    maxIndexDeLoop++;
                                    carsd.Degree_Of_Importance__c = maxIndexDeLoop;
                                }
                            }
                            // 已经有的明细不再设置保有设备
                            if (i >= caesdCount
                                    && (caesMap.containsKey(caes.Id) == false
                                    || (caesMap.containsKey(caes.Id)
                                            && caesMap.get(caes.Id).Consum_Num__c < (i + 1)
                                        )
                                    || String.isBlank(carsd.Asset__c))
                                ) {
                                // carsd.Degree_Of_Importance__c = i + 1;
                                Boolean haveass = false;
                                for (Asset ass : assList) {
                                    if (assetCountMap.get(ass.Id) > 0) {
                                        carsd.Asset__c = ass.Id;
                                        assetCountMap.put(ass.Id, assetCountMap.get(ass.Id) - 1);
                                        haveass = true;
                                        break;
                                    }
                                }
                                if (haveass == false) {
                                    throw new ControllerUtil.myException('型号' + caes.Model_No__c + '没有足够的有效库存,请重新选择');
                                }
                            }
                            System.debug(carsd.Degree_Of_Importance__c);
                            carsd.UniqueKey__c = parentObj.RequestNoJoinStr2__c + ':'+ caes.Id + ':' + caes.Model_No__c + ':' + carsd.Degree_Of_Importance__c;
                            carsdList.add(carsd);
                        }
                    }
                    else {
                        throw new ControllerUtil.myException('型号' + caes.Model_No__c + '没有有效库存,请重新选择');
                    }
                    g ++;
                }
                if (carsdList.size() > 0) {
                    Consum_ApplyUtil.withoutUpsertCaesd(carsdList);
                }
            }
            else {
                if (selectAssetIdSet.size() > 0) {
                    String soql = 'SELECT Id'
                            + ' , Fixture_Model_No_F__c'
                            + ' , You_Xiao_Ku_Cun__c'
                            + ' FROM Asset'
                            + ' WHERE (Id != null'
                            + ' AND ' + assetWhereBase
                            + ' )';
                    List<String> conditionList = new List<String>();
                    conditionList.addAll(selectAssetIdSet);
                    Consum_ApplyUtil.withoutQueryListWithConditionList(soql + ' AND Id = :conditionList ' + ' FOR UPDATE', conditionList);
                }
            }

            Consum_ApplyUtil.delCAESD_excludedUpserted(mfUpsert1, carsdList);
            Consum_ApplyUtil.delCAES_excludedUpserted(parentObj, mfUpsert2);

            // Rental_Apply_Equipment_Set_Detail__c robj = (Rental_Apply_Equipment_Set_Detail__c) wprInfo.sobj;
            // LineExtraInfo extraInfo = extraInfoList.get(wprInfo.lineNo);
            // Integer maxIndexInLoop = null;
            // for (Integer i = 0; i < robj.Rental_Num__c; i++) {
            //     // sameRAES_objs には自分の明細か、申請 直後の明細しかないか の条件があります。
            //     // なので、直接cloneしてOKです。
            //     for (Rental_Apply_Equipment_Set__c sameRAES_obj : sameRAES_objs) {
            //         Rental_Apply_Equipment_Set_Detail__c rupsobj = robj.clone(false);
            //         // 借出申请RequestNoJoinStr2__c：借出申请配套一览Id：配套明细Id
            //         String uniqueKeyStr = raObj.RequestNoJoinStr2__c + ':' + sameRAES_obj.Id
            //                 + ':'+ robj.Fixture_Set_Detail__c + ':';
            //         // default値は最初に設定した
            //         rupsobj.IndexFromUniqueKey__c = i+1;
            //         if (i < extraInfo.indexFromUniqueKeyList.size()) {
            //             rupsobj.IndexFromUniqueKey__c = extraInfo.indexFromUniqueKeyList[i];
            //             uniqueKeyStr += rupsobj.IndexFromUniqueKey__c;
            //         } else if (extraInfo.maxIndexFromUniqueKey != null) {
            //             if (maxIndexInLoop == null) { maxIndexInLoop = extraInfo.maxIndexFromUniqueKey; }
            //             maxIndexInLoop++;
            //             uniqueKeyStr = raObj.RequestNoJoinStr2__c + ':' + sameRAES_obj.Id
            //                     + ':'+ robj.Fixture_Set_Detail__c + ':'+ maxIndexInLoop;
            //             rupsobj.IndexFromUniqueKey__c = maxIndexInLoop;
            //         } else {
            //             // uniqueKeyStr に default の IndexFromUniqueKey__c を使う
            //             uniqueKeyStr += rupsobj.IndexFromUniqueKey__c;
            //         }

            //         System.debug(rupsobj.IndexFromUniqueKey__c + '测试uniqueKeyStr:' + uniqueKeyStr);
            //         rupsobj.UniqueKey__c          = uniqueKeyStr;
            //         // 配套（or 申请）·から
            //         rupsobj.Rental_Apply_Equipment_Set__c = sameRAES_obj.Id;
            //         rupsobj.Rental_Apply__c               = sameRAES_obj.Rental_Apply__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);
            //         }
            //     }
            // }

        } catch (Exception ex) {
            ApexPages.addMessages(ex);
            System.debug(ex.getMessage() + ex.getStackTraceString());
            Database.rollback(sp);
            for (Consum_Apply_Equipment_Set__c caes : mfUpsert) {
                if (String.isNotBlank(caes.Id)
                        && caesMap.containsKey(caes.Id) == false
                    ) {
                    caes.Id = null;
                }
            }
            return null;
        }
        if (isReset) {
            Set<String> modelSet = new Set<String>();
            for (WrapperInfo wprInfo : viewList) {
                Consum_Apply_Equipment_Set__c robj = (Consum_Apply_Equipment_Set__c) wprInfo.sobj;
                if (wprInfo.check) {
                    robj.Id = null;
                }
                modelSet.add(robj.Model_No__c);
            }
            Integer selectSize = selectedData.size();
            for (Integer i = selectSize - 1; i >= 0 ; i --) {
                Consum_Apply_Equipment_Set__c raesobj = (Consum_Apply_Equipment_Set__c) selectedData[i];
                if (modelSet.contains(raesobj.Model_No__c)) {
                    selectedData.remove(i);
                }

            }
            searchOpp();
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '重置成功'));
            return null;
        }
        PageReference pa = new PageReference('/apex/ConsumFixtureSetSelect?pt_recid=' + parentId);
        pa.getParameters().put('message','保存成功');
        pa.getParameters().put('level','info');
        pa.getParameters().put('saveType','true');
        pa.setRedirect(true);
        // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '保存成功'));
        return pa;
    }

    // /**
    //  * 保存画面上的选择 -- 在非草案中执行,只会根据Id更新
    //  * @param targetViewList 画面上显示的WrapperInfo
    //  * @param mfUpsert 需要更新的一览List -- 保存出错清空ID的时候需要用,所以需要传进来
    //  */
    // private void updateRaesList(List<WrapperInfo> targetViewList, List<Consum_Apply_Equipment_Set__c> mfUpsert) {
    //     Map<String, Consum_Apply_Equipment_Set__c> needUpdateRaesMap = new Map<String, Consum_Apply_Equipment_Set__c>();
    //     for (WrapperInfo wprInfo : targetViewList) {
    //         Consum_Apply_Equipment_Set__c robj = (Consum_Apply_Equipment_Set__c) wprInfo.sobj;
    //         //画面上にチェックした
    //         if (wprInfo.check) {
    //             // 只有在草案中才可以勾选同一附属品、変更前の Same_Accessory_flag__c を確認
    //             if (wprInfo.additionalInfoMap.get('Same_Accessory_flag__c') == 'false'
    //                     && robj.Same_Accessory_flag__c == true) {
    //                 throw new ControllerUtil.myException('只有草案中可以勾选同一附属品。');
    //             }
    //             needUpdateRaesMap.put(robj.Fixture_Set__c, robj);
    //         }
    //     }
    //     // 检索申请书下所有一览
    //     List<Consum_Apply_Equipment_Set__c> raess = [SELECT Id, Consum_Apply__c, Fixture_Set__c
    //                                                    FROM Consum_Apply_Equipment_Set__c
    //                                                   WHERE Fixture_Set__c in:needUpdateRaesMap.keySet()
    //                                                     AND Fixture_Set__c != null
    //                                                     AND Consum_Apply__c = :parentId
    //                                                     AND Cancel_Select__c = false
    //                                                     FOR UPDATE];
    //     Map<String, Consum_Apply_Equipment_Set__c> raesMap = new Map<String, Consum_Apply_Equipment_Set__c>();
    //     for (Consum_Apply_Equipment_Set__c raes : raess) {
    //         Consum_Apply_Equipment_Set__c raes1 = needUpdateRaesMap.get(raes.Fixture_Set__c);
    //         Consum_Apply_Equipment_Set__c rupsobj = raes1.clone(false);
    //         // 因为要只是更新所以克隆然后设置Id
    //         rupsobj.Id = raes.Id;
    //         mfUpsert.add(rupsobj);
    //     }

    //     if (!mfUpsert.isEmpty()) {
    //         //update mfUpsert Id;
    //         FixtureUtil.withoutUpdate(mfUpsert);
    //     }
    // }


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

    private String makeSoql(String keyword, Boolean islike) {

        String soql ='';
        soql += 'where Id != null AND ';
        soql += assetWhereBase;
        // ToDo 以下两个条件是需要的。测试注释
        // if (String.isNotBlank(parentObj.Internal_asset_location_F__c)) {
            soql += ' AND Internal_asset_location__c = \'上海 备品中心\'';
        // }
        if (String.isNotBlank(parentObj.Salesdepartment__c)) {
            soql += ' AND (Salesdepartment__c = \'' + parentObj.Salesdepartment__c + '\' OR Salesdepartment__c = \'0.备品中心\')';
        }
        else {
            soql += ' AND Salesdepartment__c = \'0.备品中心\'';
        }

        if (String.isNotBlank(category3)) {
            soql += ' AND Category3__c = \'' + String.escapeSingleQuotes(category3) + '\'';
        }

        if (String.isNotBlank(category4)) {
            soql += ' AND Category4__c = \'' + String.escapeSingleQuotes(category4) + '\'';
        }

        if (!String.isBlank(keyword)) {
            String[] vals = keyword.split(' ');
            soql += ' and (';
            String fmodelno = '';
            for (String v : vals) {
                // 使用型号进行检索
                if (islike) {
                    fmodelno += ' Fixture_Model_No_F__c like \'%' + String.escapeSingleQuotes(v.replaceAll('%', '\\%')) + '%\' or';
                }
                else {
                    fmodelno += ' Fixture_Model_No_F__c = \'' + String.escapeSingleQuotes(v) + '\' or';
                }
                // fmodelno += ' Loaner_name__c like \'%' + String.escapeSingleQuotes(v.replaceAll('%', '\\%')) + '%\' or';
            }
            fmodelno = fmodelno.removeEnd('or');
            soql += fmodelno + ' )';
            // for (String v : vals) {
            //     soql += ' and Name like \'%' + String.escapeSingleQuotes(v.replaceAll('%', '\\%')) + '%\'';
            // }
        }

        system.debug(soql);
        return soql;
    }

    public void showMessage() {
        String level = ApexPages.currentPage().getParameters().get('level');
        String message = ApexPages.currentPage().getParameters().get('message');
        if(String.isNotBlank(level) && String.isNotBlank(message)){
            if(level == 'info'){
                ApexPages.Message vfApplyMsg = new ApexPages.Message(ApexPages.severity.INFO, message);
                ApexPages.addMessage(vfApplyMsg);
            }
            else if(level == 'warning'){
                ApexPages.Message vfApplyMsg = new ApexPages.Message(ApexPages.severity.WARNING, message);
                ApexPages.addMessage(vfApplyMsg);
            }
            else if(level == 'error'){
                ApexPages.Message vfApplyMsg = new ApexPages.Message(ApexPages.severity.ERROR, message);
                ApexPages.addMessage(vfApplyMsg);
            }
        }
    }

    public override void setViewList(List<sObject> queryList) {
        // 从保存跳转而来时，打印保存成功信息
        if(saveType){
            showMessage();
        }


        extraInfoList = new List<LineExtraInfo>();  // viewList と同じ順番、同じ件数
        Set<String> modelSet = new Set<String>();
        Map<Consum_ApplyUtil.CUCUNTYPE, Map<String, Integer>> countMap = new Map<Consum_ApplyUtil.CUCUNTYPE, Map<String, Integer>>();
        String wher = '';
        Date td = Date.today();
        selectedGroupData = new List<Consum_Apply_Equipment_Set__c>();
        Map<String, Date> fDateMap = new Map<String, Date>();
        if (selectedData.size() > 0) {
            List<Consum_Apply_Equipment_Set__c> cardList = (List<Consum_Apply_Equipment_Set__c>)selectedData;
            List<Consum_Apply_Equipment_Set_Detail__c> caesdList = [SELECT Id
                        , IndexFromUniqueKey__c
                        , Fixture_Model_No_F__c
                        , Cancel_Select__c
                        , UniqueKey__c
                        , Degree_Of_Importance__c
                     FROM Consum_Apply_Equipment_Set_Detail__c
                    WHERE Consum_Apply_Equipment_Set__c = :cardList
                    ORDER BY Degree_Of_Importance__c];
            Map<String, LineExtraInfo> sltExtraInfoMap = new Map<String, LineExtraInfo>();
            for (Consum_Apply_Equipment_Set_Detail__c caersd : caesdList) {
                if (!sltExtraInfoMap.containsKey(caersd.Fixture_Model_No_F__c)) {
                    if (!caersd.Cancel_Select__c) {
                        LineExtraInfo extraInfo = new LineExtraInfo(caersd);
                        sltExtraInfoMap.put(caersd.Fixture_Model_No_F__c, extraInfo);
                        extraInfoList.add(extraInfo);
                    }
                }
                else {
                    LineExtraInfo extraInfo = sltExtraInfoMap.get(caersd.Fixture_Model_No_F__c);
                    extraInfo.updateExtraInfo(caersd);
                }
            }
            Map<String, Consum_Apply_Equipment_Set__c> subsFixtureMap = new Map<String, Consum_Apply_Equipment_Set__c>();   // 用于存代替分配的一览
            // 20170906 グループリスト取得
            // order by Fixture_Set__c, Fixture_Set__r.Loaner_code__c, IndexFromUniqueKey__c
            Date minDate = Date.newInstance(4000, 12, 31);
            Date maxDate = Date.newInstance(1700, 1, 1);
            Map<Date, OlympusCalendar__c> calendarMap = Consum_ApplyUtil.getOlympusCalendarMAp(minDate, maxDate);
            for (SObject sobj : selectedData) {
                Consum_Apply_Equipment_Set__c raesobj = (Consum_Apply_Equipment_Set__c) sobj;
                modelSet.add(raesobj.Model_No__c);
                selectedGroupData.add(raesobj);
                wher += raesobj.Model_No__c + ' ';
                if (raesobj.Consum_Start_Date__c != null) {
                    if (raesobj.Consum_Start_Date__c > maxDate) {
                        maxDate = raesobj.Consum_Start_Date__c;
                    }
                    if (raesobj.Consum_Start_Date__c < minDate) {
                        minDate = raesobj.Consum_Start_Date__c;
                    }
                }
                if (raesobj.Consum_Start_Date__c != null) {
                    if (calendarMap.containsKey(raesobj.Consum_Start_Date__c)) {
                        fDateMap.put(raesobj.Model_No__c, calendarMap.get(raesobj.Consum_Start_Date__c).After_15_WorkDay__c);
                    }
                    else {
                         fDateMap.put(raesobj.Model_No__c, Consum_ApplyUtil.getWD_addday(raesobj.Consum_Start_Date__c, 15));
                    }
                }
                else {
                    fDateMap.put(raesobj.Model_No__c, td);
                }
                // wher += ') OR';
            }
        }

        // 把已勾选的加入
        if(viewList!=null && viewList.size()>0){
            for(WrapperInfo winfo : viewList){
                Consum_Apply_Equipment_Set__c raesobj = (Consum_Apply_Equipment_Set__c) winfo.sobj;
                wher += raesobj.Model_No__c + ' ';
                if (winfo.check && excludedModelWherSelectSet.contains(raesobj.Model_No__c) == false) {
                    selectedGroupData.add(raesobj);
                    if (raesobj.Consum_Start_Date__c != null) {
                        if (calendarMap.containsKey(raesobj.Consum_Start_Date__c)) {
                            fDateMap.put(raesobj.Model_No__c, calendarMap.get(raesobj.Consum_Start_Date__c).After_15_WorkDay__c);
                        }
                        else {
                             fDateMap.put(raesobj.Model_No__c, Consum_ApplyUtil.getWD_addday(raesobj.Consum_Start_Date__c, 15));
                        }
                    }
                    else {
                        fDateMap.put(raesobj.Model_No__c, td);
                    }
                }
            }
        }
        viewList = new List<WrapperInfo>();
        if (selectedGroupData.size() > 0) {
            category3 = '';
            category4 = '';
            // wher = wher.removeEnd('OR');
            String soql = 'SELECT Id'
                                + ' , Fixture_Model_No_F__c'
                                + ' , You_Xiao_Ku_Cun__c'
                                + ' , Consumable_Guaranteen_end__c'
                            + ' FROM Asset '
                            + makeSoql(wher, true)
                             + ' FOR UPDATE';
                             System.debug(soql);
            List<Asset> assList = Consum_ApplyUtil.withoutQueryList(soql);
            countMap = Consum_ApplyUtil.getAssetKucun(assList, fDateMap);
            for (SObject sobj : selectedGroupData) {
                Consum_Apply_Equipment_Set__c raesobj = (Consum_Apply_Equipment_Set__c) sobj;
                System.debug(countMap);
                if (countMap.get(Consum_ApplyUtil.CUCUNTYPE.You_Xiao_QI_Ku_Cun).containsKey(raesobj.Model_No__c)) {
                    raesobj.You_Xiao_Qi_Ku_Cun_Jia__c     = countMap.get(Consum_ApplyUtil.CUCUNTYPE.You_Xiao_QI_Ku_Cun).get(raesobj.Model_No__c);
                    raesobj.Yi_Guo_Qi_Ku_Cun_Jia__c       = countMap.get(Consum_ApplyUtil.CUCUNTYPE.Yi_Guo_Qi_Ku_Cun).get(raesobj.Model_No__c);
                }
                raesobj.You_Xiao_Ku_Cun_Jia__c        = countMap.get(Consum_ApplyUtil.CUCUNTYPE.You_Xiao_Ku_Cun).get(raesobj.Model_No__c);
                raesobj.Consum_Num__c = raesobj.RetalFSetDetail_Cnt__c;
                raesobj.VF_Consum_Num__c = raesobj.RetalFSetDetail_Cnt__c;
                if (excludedModelWherMap.containsKey(raesobj.Model_No__c)) {
                    raesobj.Consum_Num__c = excludedModelWherMap.get(raesobj.Model_No__c);
                    raesobj.VF_Consum_Num__c = raesobj.Consum_Num__c;
                }
                if (resetSet.contains(raesobj.Model_No__c)) {
                    raesobj.Consum_Num__c = null;
                    raesobj.VF_Consum_Num__c = raesobj.Consum_Num__c;
                    raesobj.Consum_Start_Date__c = null;
                }
                if (viewList.size() >= 500) {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '画面最大只能显示500种型号的备品,请设置检索条件后重试'));
                    return ;
                }
                viewList.add(new WrapperInfo(raesobj, myComponentController));
                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('Substitute_Select_Again__c', String.valueOf(raesobj.Substitute_Select_Again__c));
                // if (raesobj.You_Xiao_Ku_Cun_Jia__c == 0
                //         || (parentObj.demo_purpose2__c != '动物实验'
                //                 && (raesobj.You_Xiao_Qi_Ku_Cun_Jia__c == null
                //                         || raesobj.You_Xiao_Qi_Ku_Cun_Jia__c == 0
                //                     )
                //             )
                //     ) {
                //     viewList[viewList.size() - 1].check = false;
                //     viewList[viewList.size() - 1].oldCheck = false;
                //     // viewList[viewList.size() - 1].canEdit = false;
                // }
            }
        }
        if (queryList.size() == 0) {
            return;
        }

        // 数式項目値を取れるのために、一回Insertする
        Map<String, Integer> assetyouxiaoqiMap = new Map<String, Integer>();
        Map<String, Integer> assetguoqiMap = new Map<String, Integer>();
        Map<String, Integer> assetyouxiaoMap = new Map<String, Integer>();
        Date tod = Date.today();
        if (caes.Consum_Start_Date__c != null) {
            tod = caes.Consum_Start_Date__c;
        }
        Date tod15 = Date.today();
        Date todb22;
        if (calendarMap.containsKey(tod) == false) {
            calendarMap.putAll(Consum_ApplyUtil.getOlympusCalendarMAp(tod, tod));
        }
        //2021-04-30 mzy update  备品课题-1577   start
        if (parentObj.demo_purpose2__c != '动物实验' && parentObj.demo_purpose2__c != 'ET展箱' ) {
        //2021-04-30 mzy update  备品课题-1577   end
            if (calendarMap.containsKey(tod) && calendarMap.get(tod).After_15_WorkDay__c != null) {
                tod15 = calendarMap.get(tod).After_15_WorkDay__c;
            }
            else {
                tod15 = Consum_ApplyUtil.getWD_addday(tod, 15);
            }
        }
        if (calendarMap.containsKey(tod) && calendarMap.get(tod).Before_22_WorkDay__c != null) {
            todb22 = calendarMap.get(tod).Before_22_WorkDay__c;
        }
        else {
            todb22 = Consum_ApplyUtil.getWD_addday(tod, -22);
        }
        for (Integer i = 0; i < queryList.size(); i++) {
            Asset ass = (Asset)queryList[i];
            if(excludedModelWherMap.containsKey(ass.Fixture_Model_No_F__c)){
                continue;
            }
            if (assetyouxiaoMap.containsKey(ass.Fixture_Model_No_F__c) == false) {
                assetyouxiaoMap.put(ass.Fixture_Model_No_F__c, 0);
            }
            if (ass.Consumable_Guaranteen_end__c != null) {
                if (assetyouxiaoqiMap.containsKey(ass.Fixture_Model_No_F__c) == false) {
                    assetyouxiaoqiMap.put(ass.Fixture_Model_No_F__c, 0);
                    assetguoqiMap.put(ass.Fixture_Model_No_F__c, 0);
                }
                if (ass.Consumable_Guaranteen_end__c > tod15) {
                    assetyouxiaoqiMap.put(ass.Fixture_Model_No_F__c, assetyouxiaoqiMap.get(ass.Fixture_Model_No_F__c) + Integer.valueOf(ass.You_Xiao_Ku_Cun__c));
                }
                else {
                    assetguoqiMap.put(ass.Fixture_Model_No_F__c, assetguoqiMap.get(ass.Fixture_Model_No_F__c) + Integer.valueOf(ass.You_Xiao_Ku_Cun__c));
                }
            }
            assetyouxiaoMap.put(ass.Fixture_Model_No_F__c, assetyouxiaoMap.get(ass.Fixture_Model_No_F__c) + Integer.valueOf(ass.You_Xiao_Ku_Cun__c));
        }
        List<Consum_Apply_Equipment_Set__c> tempList = new List<Consum_Apply_Equipment_Set__c>();
        Integer j = 0;
        for (String key : assetyouxiaoMap.keySet()) {
            if (modelSet.contains(key)) {
                continue;
            }
            // 501を超えた場合前500のみを出す
            if (j == getSearchNumMax()) { break; }
            Consum_Apply_Equipment_Set__c mf = new Consum_Apply_Equipment_Set__c();
            mf.Consum_Apply__c               = parentId;
            mf.You_Xiao_Qi_Ku_Cun_Jia__c     = assetyouxiaoqiMap.get(key);
            mf.Yi_Guo_Qi_Ku_Cun_Jia__c       = assetguoqiMap.get(key);
            mf.You_Xiao_Ku_Cun_Jia__c        = assetyouxiaoMap.get(key);
            mf.Model_No__c                   = key;
            mf.DataMigration_Flag__c         = true;
            mf.Consum_Start_Date__c          = tod;
            mf.Consum_Can_Request_approval_Date__c = todb22;

            tempList.add(mf);
            j ++;
        }
        calAfter15Day(tod);

        // Database.SaveResult[] results = FixtureUtil.withoutInsert(tempList, false);
        // final String soqlStr = 'Select {0} {1} ';
        // String whereStr = ' FROM Consum_Apply_Equipment_Set__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 検索処理正しくありません、システム管理者に連絡してください。
        //     for (Integer i = 0; i < results.size(); i ++) {
        //         Database.SaveResult dmlResult = results[i];
        //         if (!dmlResult.isSuccess()) {
        //             System.debug(System.LoggingLevel.ERROR, '第[' + (i + 1) + ']条 insert error:' + dmlResult);
        //             ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,
        //             '第[' + (i + 1) + ']条 insert 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(Consum_Apply_Equipment_Set__c fsd : tempList){
            Consum_Apply_Equipment_Set__c robj = fsd.clone(false);
            // 根据OLY_OCM-404的需求设置默认数量为1
            robj.Consum_Num__c = null;
            robj.VF_Consum_Num__c = null;
            robj.DataMigration_Flag__c = false;
            fsDMap.put(fsd.Model_No__c, robj);
        }

        Integer addedNum = 0;
        for (Integer i = 0; i < tempList.size(); i++) {
            addedNum ++;
            // 501を超えた場合前500のみを出す
            if (addedNum == getSearchNumMax()) { break; }
            Consum_Apply_Equipment_Set__c mf = (Consum_Apply_Equipment_Set__c) fsDMap.get(tempList[i].Model_No__c);
            extraInfoList.add(new LineExtraInfo(null));
            if(excludedModelWherMap.containsKey(mf.Model_No__c)){
                continue;
            }
            if (viewList.size() >= 500) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '画面最大只能显示500种型号的备品,请设置检索条件后重试'));
                return ;
            }
            viewList.add(new WrapperInfo(mf, myComponentController));
            viewList[viewList.size() - 1].lineNo = viewList.size() - 1;
            //viewList[viewList.size() - 1].additionalInfoMap.put('Substitute_Select_Again__c', String.valueOf(mf.Substitute_Select_Again__c));
            //2021-04-30 mzy update  备品课题-1577  
            if (parentObj.demo_purpose2__c != '动物实验' && parentObj.demo_purpose2__c != 'ET展箱') {
                if (mf.You_Xiao_Ku_Cun_Jia__c == 0
                        || (mf.You_Xiao_Qi_Ku_Cun_Jia__c != null
                                && mf.You_Xiao_Qi_Ku_Cun_Jia__c <= 0
                           )
                ) {
                    viewList[viewList.size() - 1].canEdit = false;
                }
            }
            else if (mf.You_Xiao_Ku_Cun_Jia__c <= 0) {
                viewList[viewList.size() - 1].canEdit = false;
            }
        }
    }

    private Date calAfter15Day(Date d){
        if(!calendarMap.containsKey(d)){
            calendarMap.putAll(Consum_ApplyUtil.getOlympusCalendarMAp(d, d));
        }
        Date d1 = d;
        if (calendarMap.containsKey(d) && calendarMap.get(d).After_15_WorkDay__c != null) {
            d1 = calendarMap.get(d).After_15_WorkDay__c;
        }
        else {
            d1 = Consum_ApplyUtil.getWD_addday(d, 15);
        }
        if (after15DayMap.containsKey(d) == false) {
            after15DayMap.put(d, d1);
        }
        return d1;
    }


    public void reSetYouXiaoKuCun() {
        Savepoint sp = Database.setSavepoint();
        try {
            String index = ApexPages.currentPage().getParameters().get('index');
            String dateStr = ApexPages.currentPage().getParameters().get('date');
            if (caes.Consum_Start_Date__c != null) {
                Date today = Date.Today();                                   // 运行当天
                Date inputDate = caes.Consum_Start_Date__c; // 手填的预计使用日
                Date inputDate15 = calAfter15Day(inputDate);                 // 预计使用日后15个工作日
                // ToDo 谁说过动物实验时用今天计算有效期数量的?
                //2021-04-30  mzy  udpate 备品课题-1577  start                
                //Date dateForCompare = parentObj.demo_purpose2__c == '动物实验' ? today : inputDate15;
                Date dateForCompare = null;
                if(parentObj.demo_purpose2__c == '动物实验' || parentObj.demo_purpose2__c == 'ET展箱' ){
                    dateForCompare = today;
                }else {
                    dateForCompare = inputDate15;
                }        
                //2021-04-30  mzy update 备品课题-1577  end         
                Map<String, WrapperInfo> infoMap = new Map<String, WrapperInfo>();
                List<Consum_Apply_Equipment_Set__c> caesList = new List<Consum_Apply_Equipment_Set__c>();
                for (WrapperInfo info : viewList) {
                    if (info.check) {
                        Consum_Apply_Equipment_Set__c caes = (Consum_Apply_Equipment_Set__c)info.sobj;
                        if (String.isNotBlank(caes.Id)) {
                            caes.Consum_Num__c = 0;
                            caesList.add(caes);
                        }
                        caes.You_Xiao_Qi_Ku_Cun_Jia__c = null;
                        caes.Yi_Guo_Qi_Ku_Cun_Jia__c = null;
                        caes.You_Xiao_Ku_Cun_Jia__c = 0;
                        infoMap.put(caes.Model_No__c, info);
                    }
                }
                Consum_ApplyUtil.delCAESD_excludedUpserted(caesList, new List<Consum_Apply_Equipment_Set_Detail__c>());
                FixtureUtil.withoutDelete(caesList);
                // String model = '%' + String.escapeSingleQuotes(caes.Model_No__c.replaceAll('%', '\\%')) + '%';
                String soql = ' SELECT Id'
                        + ' , Fixture_Model_No_F__c'
                        + ' , Consumable_Guaranteen_end__c'
                        + ' , You_Xiao_Ku_Cun__c'
                     + ' FROM Asset '
                     + makeSoql(null, false);
                List<String> conditionList = new List<String>();
                conditionList.addAll(infoMap.keySet());
                soql += ' and Fixture_Model_No_F__c = :conditionList ';
                    // + ' WHERE ' + assetWhereBase
                    //   + ' AND Fixture_Model_No_F__c like \'%' + String.escapeSingleQuotes(caes.Model_No__c.replaceAll('%', '\\%')) + '%\'';
                System.debug(soql);
                System.debug(conditionList);
                List<Asset> assList = Consum_ApplyUtil.withoutQueryListWithConditionList(soql, conditionList);
                Map<String, List<Asset>> assMap = new Map<String, List<Asset>>();
                for (Asset ass : assList) {
                    if (assMap.containsKey(ass.Fixture_Model_No_F__c) == false) {
                        assMap.put(ass.Fixture_Model_No_F__c, new List<Asset>());
                    }
                    assMap.get(ass.Fixture_Model_No_F__c).add(ass);
                }
                System.debug(assList);
                for (String key : assMap.keySet()) {
                    Consum_Apply_Equipment_Set__c caes = (Consum_Apply_Equipment_Set__c)infoMap.get(key).sobj;
                    for (Asset ass : assMap.get(key)) {
                        if (ass.Consumable_Guaranteen_end__c != null) {
                            if (caes.You_Xiao_Qi_Ku_Cun_Jia__c == null) {
                                caes.You_Xiao_Qi_Ku_Cun_Jia__c = 0;
                                caes.Yi_Guo_Qi_Ku_Cun_Jia__c = 0;
                            }
                            if (ass.Consumable_Guaranteen_end__c > dateForCompare) {
                                caes.You_Xiao_Qi_Ku_Cun_Jia__c += ass.You_Xiao_Ku_Cun__c;
                            }
                            if (ass.Consumable_Guaranteen_end__c <= dateForCompare) {
                                caes.Yi_Guo_Qi_Ku_Cun_Jia__c += ass.You_Xiao_Ku_Cun__c;
                            }
                        }
                        caes.You_Xiao_Ku_Cun_Jia__c += ass.You_Xiao_Ku_Cun__c;
                    }
                     if (calendarMap.containsKey(inputDate) && calendarMap.get(inputDate).Before_22_WorkDay__c != null) {
                         caes.Consum_Can_Request_approval_Date__c = calendarMap.get(inputDate).Before_22_WorkDay__c;
                    }
                    else {
                        caes.Consum_Can_Request_approval_Date__c = Consum_ApplyUtil.getWD_addday(inputDate, -22);
                    }
                }
                // for (Asset ass : assList) {
                //     if (ass.Consumable_Guaranteen_end__c != null) {
                //         if (caes.You_Xiao_Qi_Ku_Cun_Jia__c == null) {
                //             caes.You_Xiao_Qi_Ku_Cun_Jia__c = 0;
                //             caes.Yi_Guo_Qi_Ku_Cun_Jia__c = 0;
                //         }
                //         if (ass.Consumable_Guaranteen_end__c > dateForCompare) {
                //             caes.You_Xiao_Qi_Ku_Cun_Jia__c += ass.You_Xiao_Ku_Cun__c;
                //         }
                //         if (ass.Consumable_Guaranteen_end__c <= dateForCompare) {
                //             caes.Yi_Guo_Qi_Ku_Cun_Jia__c += ass.You_Xiao_Ku_Cun__c;
                //         }
                //     }
                // }
                for (String key : infoMap.keySet()) {
                    WrapperInfo info = infoMap.get(key);
                    Consum_Apply_Equipment_Set__c caes = (Consum_Apply_Equipment_Set__c)info.sobj;
                    caes.Id = null;
                    caes.Consum_Start_Date__c = inputDate;
                }
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM, '适用成功'));
            }
        }
        catch(Exception e) {
            Database.rollback(sp);
            System.debug(e.getMessage() + e.getStackTraceString());
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, e.getMessage()));
        }
    }

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

        // Cancel_Select 処理しない
        public LineExtraInfo(Consum_Apply_Equipment_Set_Detail__c raesdobj) {
            // maxIndexFromUniqueKey を null にする
            raesdUniqueKeySet = new Set<String>();
            indexFromUniqueKeyList = new List<Decimal>();
            degree_Of_ImportanceList = 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.IndexFromUniqueKey__c);
            maxIndexFromUniqueKey = raesdobj.IndexFromUniqueKey__c.intValue();
            degree_Of_ImportanceList.add(raesdobj.Degree_Of_Importance__c);
            maxDegree_Of_Importance = raesdobj.Degree_Of_Importance__c.intValue();
        }

        // Cancel_Select も処理対象 (maxIndexFromUniqueKeyを更新するために)
        public void updateExtraInfo(Consum_Apply_Equipment_Set_Detail__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.IndexFromUniqueKey__c);
                degree_Of_ImportanceList.add(raesdobj.Degree_Of_Importance__c);
            }
            Integer indexFromUniqueKey = raesdobj.IndexFromUniqueKey__c.intValue();
            if (indexFromUniqueKey > maxIndexFromUniqueKey) {
                maxIndexFromUniqueKey = raesdobj.IndexFromUniqueKey__c.intValue();
            }

            Integer degree_Of_Importance = raesdobj.Degree_Of_Importance__c.intValue();
            if (degree_Of_Importance > maxDegree_Of_Importance) {
                maxDegree_Of_Importance = raesdobj.Degree_Of_Importance__c.intValue();
            }
        }
    }
}