/**
 * 备品配套选择
 */
public with sharing class ConsumDefaultSelectController extends CreateRelationListPagingCtrlBase {
    public override Integer getSearchNumMax() {
        //各ページに制御あれば、最大件数を指定する
        // searchNumMax = Integer.valueOf(Label.Product_Select_Limit);
        //TODO change
        // searchNumMax = 100;
        pagesize = '100';
        return searchNumMax;
    }

    /* 選択されたデータ取得用Soql　Fromから*/
    public override String getSelectedDataSql() {
        // オブジェクトAPI名
        selectedDataSql = ' From Consum_Apply_Equipment_Set_Detail__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_Model_No_F__c, Degree_Of_Importance__c';
        myComponentController.columnLeftRW.put('No_Jia__c', 'r');
        myComponentController.columnLeftRW.put('Request_Num_Jia__c', 'r');
        myComponentController.columnLeftRW.put('You_Xiao_Ku_Cun_Jia__c', 'r');
        myComponentController.columnLeftRW.put('You_Xiao_Qi_Ku_Cun_Jia__c', 'r');
        myComponentController.columnLeftRW.put('Yi_Guo_Qi_Ku_Cun_Jia__c', 'r');
        myComponentController.columnLeftRW.put('demo_purpose2__c', 'r'); // 20220309 ljh  SFDC-CC73U5 132 动物实验&ET展箱 锁定已过期库存 add start
        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_Detail__c';
        return objName;
    }
    public override String getColumnLeftFieldSetName() {
        // 左の項目セット
        columnLeftFieldSetName = 'ConsumDefaultSelect_L';
        return columnLeftFieldSetName;
    }
    public override String getColumnRightFieldSetName() {
        // 右の項目セット
        columnRightFieldSetName = 'ConsumDefaultSelect_R';
        return columnRightFieldSetName;
    }

    public override List<String> getColumnFieldList() {
        // strColumus 里加 field
        return new List<String>{'Id'
                , 'Consum_Apply__c'
                , 'Consum_Apply__r.Status__c'
                , 'UniqueKey__c'
                , 'SerialNumber__c'
                , 'Consum_Start_Date__c'
                , 'Select_Time__c'
                , 'GroupKey_F__c'
                , 'Asset__c'
                , 'demo_purpose2__c' // 20220309 ljh  SFDC-CC73U5 132 动物实验&ET展箱 锁定已过期库存 add start
                , 'Shipment_request_time2__c'
                , 'Consum_Start_Date_After_15_Day__c'
                , 'Consum_Apply_Equipment_Set__r.Model_No__c'
                , 'Consum_Apply_Equipment_Set__r.Consum_Start_Date__c'
                , 'Consum_Apply_Equipment_Set__r.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 = '';

        return sqlWhereStr;

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

    public override Boolean getIsNeedRunSearch() {
        return true;
    }

    /*****************ソート時再検索条件（画面からの入力条件を無視するため）******************/
    private String keywdSort = null;
    public String keyword { get; set; }
    public String category2 { get; set; }
    public String category3 { 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更新
    private String wherStr1;
    private static String wherStr;

    public String saveType { get; set; }
    public Boolean needOpenPage { get; set; }
    public Consum_Apply__c parentObj { get; set; }

    private static String assetWhereBase = ' Delete_Flag__c = False'
             + ' AND Asset_Owner__c = \'Olympus\''
             + ' AND Freeze_sign_Abandoned_Flag__c = False'
             + ' AND Asset_loaner_category__c = \'耗材\''
             + ' AND Equipment_Type__c != \'检测用备品\' '
             + ' AND Fixture_OneToOne_Link__c = null '
             + ' AND Internal_asset_location__c != null '
             + ' AND RecordTypeId = \'01210000000kOPR\'' + ' AND ' + FixtureUtil.getAssetSoqlBase();

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

    public ConsumDefaultSelectController() {
        parentId = ApexPages.currentPage().getParameters().get('pt_recid');
        inRaesId = ApexPages.currentPage().getParameters().get('raesid');
        savetype = ApexPages.currentPage().getParameters().get('savetype');
        isRadio = String.isBlank(this.inRaesId) ? false : true;   // 分配代替品--选择配套画面只能单选

        //备品配套下的所有明细
        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_date__c
                         , Campaign__c
                         , Wei_Assigned_Cnt__c
                         //, Repair__c
                         , Assigned_Not_Shipment__c
                         //, Contract_pdf_updated__c
                      FROM Consum_Apply__c
                     WHERE Id = :parentId];
            if (parentObjs.size() > 0) {
                parentObj = parentObjs.get(0);
                if (String.isBlank(parentObj.Internal_asset_location_F__c)) {
                    throw new ControllerUtil.myException('耗材申请的备品存放地不能为空');
                }
            }
        }

        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() {
        searchOppSetParam();
        getSqlWhereStr();
    }

    private void searchOppSetParam() {
        keywdSort = keyword;
    }

    public PageReference searchOpp() {
        searchOppSetParam();

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

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

        getSqlWhereStr();
        // コンポーネントにSoqlを発行して、ページングする
        myComponentController.searchAndPaging();
        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>();
        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>();
        try {

            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_date__c
                         , Campaign__c
                         , Wei_Assigned_Cnt__c
                         //, Repair__c
                         , Assigned_Not_Shipment__c
                         //, Contract_pdf_updated__c
                      FROM Consum_Apply__c
                     WHERE Id = :parentId
                       FOR UPDATE];
            if (parentObjs.size() > 0) {
                parentObj = parentObjs.get(0);
                if (String.isBlank(parentObj.Internal_asset_location_F__c)) {
                    throw new ControllerUtil.myException('耗材申请的备品存放地不能为空');
                }
            }
            Map<String, Integer> cancelMap = new Map<String, Integer>();
            for (WrapperInfo info : viewList) {
                if (info.check) {
                    Consum_Apply_Equipment_Set_Detail__c caesd = (Consum_Apply_Equipment_Set_Detail__c)info.sobj;
                    if (caesd.Qu_Xiao_Fen_Pei_Shu_Liang_Jia__c != null
                            && caesd.Qu_Xiao_Fen_Pei_Shu_Liang_Jia__c > 0) {
                        // 20220309 ljh  SFDC-CC73U5 132 动物实验&ET展箱 锁定已过期库存 add start
                        // String key = caesd.GroupKey_F__c;
                        String key = caesd.GroupKey_F__c+caesd.Fixture_Model_No__c;
                        // 20220309 ljh  SFDC-CC73U5 132 动物实验&ET展箱 锁定已过期库存 add end
                        System.debug(caesd.Consumable_Guaranteen_end_F__c);
                        System.debug(key);
                        if(caesd.Qu_Xiao_Fen_Pei_Shu_Liang_Jia__c>caesd.Jie_Chu_Fen_Pei_Jia__c){
                            throw new ControllerUtil.myException('取消分配数量不可超过已分配数');
                        }
                        cancelMap.put(key, Integer.valueOf(caesd.Qu_Xiao_Fen_Pei_Shu_Liang_Jia__c));
                    }
                }
            }

            String soql = 'SELECT Id'
                                + ' , SerialNumber'
                                + ' , Fixture_Model_No_F__c'
                                + ' , You_Xiao_Ku_Cun__c'
                                + ' , Consumable_Guaranteen_end__c'
                                + ' , GroupKey_F__c'
                            + ' FROM Asset'
                           + ' WHERE (Id != null '
                            + wherStr1
                             + ' AND ' + assetWhereBase + ' )';
            System.debug(soql);
            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);
                }
            }
            // 因为保有设备的借出分配数会变，所以需要Lock
            List<String> conditionList = new List<String>();
            conditionList.addAll(selectAssetIdSet);
            Consum_ApplyUtil.withoutQueryListWithConditionList(soql + ' OR Id = :conditionList' + ' FOR UPDATE', conditionList);

            List<Consum_Apply_Equipment_Set_Detail__c> carsdList = [SELECT Id
                     FROM Consum_Apply_Equipment_Set_Detail__c
                    WHERE Consum_Apply__c = :parentId
                      AND Cancel_Select__c = False
                      FOR UPDATE];

            carsdList = [SELECT Id
                        , Select_Time__c
                        , GroupKey_F__c
                        , Fixture_Model_No__c // 20220309 ljh  SFDC-CC73U5 132 动物实验&ET展箱 锁定已过期库存 add
                     FROM Consum_Apply_Equipment_Set_Detail__c
                    WHERE Consum_Apply__c = :parentId
                      AND Cancel_Select__c = False
                      AND Select_Time__c != null
                    ORDER BY Degree_Of_Importance__c DESC];
            Map<String, List<Consum_Apply_Equipment_Set_Detail__c>> caesdListMap = new Map<String, List<Consum_Apply_Equipment_Set_Detail__c>>();
            for (Consum_Apply_Equipment_Set_Detail__c caesd : carsdList) {
                // 20220309 ljh  SFDC-CC73U5 132 动物实验&ET展箱 锁定已过期库存 add start
                String key = caesd.GroupKey_F__c+caesd.Fixture_Model_No__c;
                // if (caesdListMap.containsKey(caesd.GroupKey_F__c) == false) {
                //     caesdListMap.put(caesd.GroupKey_F__c, new List<Consum_Apply_Equipment_Set_Detail__c>());
                // }
                // System.debug(caesd.GroupKey_F__c);
                // caesdListMap.get(caesd.GroupKey_F__c).add(caesd);
                List<Consum_Apply_Equipment_Set_Detail__c> tempCaesdL;
                if(caesdListMap.containsKey(key)){
                    tempCaesdL = caesdListMap.get(key);
                }else{
                    tempCaesdL = new List<Consum_Apply_Equipment_Set_Detail__c>();
                }
                tempCaesdL.add(caesd);                        
                caesdListMap.put(key,tempCaesdL);
                // 20220309 ljh  SFDC-CC73U5 132 动物实验&ET展箱 锁定已过期库存 add end
            }
            System.debug(caesdListMap);
            List<Consum_Apply_Equipment_Set_Detail__c> caesdList = new List<Consum_Apply_Equipment_Set_Detail__c>();
            for (String key : cancelMap.keySet()) {
                for (Integer i = 0; i < cancelMap.get(key); i ++) {
                    System.debug(key);
                    Consum_Apply_Equipment_Set_Detail__c caesd = caesdListMap.get(key)[i];
                    caesd.Select_Time__c = null;
                    caesd.Asset__c = null;
                    caesdList.add(caesd);
                }
            }
            if (caesdList.size() > 0) {
                FixtureUtil.withoutUpdate(caesdList);
            }
        } catch (Exception ex) {
            ApexPages.addMessages(ex);
            System.debug(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;
        }
        PageReference pa = new PageReference('/apex/ConsumDefaultSelect?pt_recid=' + parentId + '&savetype=1');
        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;
    }
    public void copyNum(){
        for (WrapperInfo info : viewList) {
            if (info.check) {
                Consum_Apply_Equipment_Set_Detail__c caesd = (Consum_Apply_Equipment_Set_Detail__c)info.sobj;
                caesd.Qu_Xiao_Fen_Pei_Shu_Liang_Jia__c = caesd.Jie_Chu_Fen_Pei_Jia__c;
            }
        }
    }
    public override void setViewList(List<sObject> queryList) {
        System.Savepoint sp = Database.setSavepoint();
        try {

            viewList = new List<WrapperInfo>();
            Map<Consum_ApplyUtil.CUCUNTYPE, Map<String, Integer>> countMap = new Map<Consum_ApplyUtil.CUCUNTYPE, Map<String, Integer>>();
            if (selectedData.size() > 0) {
                // 20170906 グループリスト取得
                // order by Fixture_Set__c, Fixture_Set__r.Loaner_code__c, IndexFromUniqueKey__c
                // wherStr = '';
                // Date minDate = Date.newInstance(4000, 12, 31);
                // Date maxDate = Date.newInstance(1700, 1, 1);
                // // Map<Date, OlympusCalendar__c> calendarMap = Consum_ApplyUtil.getOlympusCalendarMAp(minDate, maxDate);
                // Map<String, Date> fDateMap = new Map<String, Date>();
                // Date td = Date.today();
                // for (SObject sobj : selectedData) {
                //     Consum_Apply_Equipment_Set_Detail__c caesdobj = (Consum_Apply_Equipment_Set_Detail__c) sobj;
                //     if (modelSet.contains(caesdobj.Consum_Apply_Equipment_Set__r.Model_No__c) == false) {
                //         if (String.isBlank(wherStr)) {
                //             wherStr = ' AND (';
                //         }
                //         wherStr += ' (';
                //         wherStr += '(Fixture_Model_No_F__c  = \'' + String.escapeSingleQuotes(caesdobj.Consum_Apply_Equipment_Set__r.Model_No__c) + '\'';
                //         Date d1 = caesdobj.Consum_Start_Date_After_15_Day__c == null ? Date.today() : caesdobj.Consum_Start_Date_After_15_Day__c;
                //         wherStr += ' AND Consumable_Guaranteen_end__c >= ' + d1.year() + '-' + String.valueOf(d1.month()).leftPad(2,'0') + '-' + String.valueOf(d1.day()).leftPad(2,'0') + ' )';
                //         wherStr += ' OR Consumable_Guaranteen_end__c = null';
                //         wherStr += ' ) OR';
                //         // key = caesdobj.GroupKey_F__c;
                //         modelSet.add(caesdobj.Consum_Apply_Equipment_Set__r.Model_No__c);
                //     }
                // }

                // if (String.isNotBlank(wherStr)) {
                //     wherStr = wherStr.removeEnd('OR');
                //     wherStr += ')';
                // }
                // // if (String.isNotBlank(parentObj.Internal_asset_location_F__c)) {
                //     wherStr += ' AND Internal_asset_location__c = \'上海 备品中心\'';
                // // }
                // if (String.isNotBlank(parentObj.Salesdepartment__c)) {
                //     wherStr += ' AND (Salesdepartment__c = \'' + parentObj.Salesdepartment__c + '\' OR Salesdepartment__c = \'0.备品中心\')';
                // }
                // else {
                //     wherStr += ' AND Salesdepartment__c = \'0.备品中心\'';
                // }

                // // 检索出保有设备，如果默认分配时间过期的话重新分配
                // String soql = 'SELECT Id'
                //                     + ' , SerialNumber'
                //                     + ' , Fixture_Model_No_F__c'
                //                     + ' , You_Xiao_Ku_Cun__c'
                //                     + ' , Consumable_Guaranteen_end__c'
                //                     + ' , GroupKey_F__c'
                //                 + ' FROM Asset'
                //                + ' WHERE Id != null '
                //                 + wherStr
                //                  + ' AND ' + assetWhereBase;

                // System.debug(soql);
                // // 因为保有设备的借出分配数会变，所以需要Lock
                // Database.query(soql + ' FOR UPDATE');
                // List<Asset> assList1 = Database.query(soql +  + ' ORDER BY Salesdepartment__c DESC, Fixture_Model_No_F__c, Consumable_Guaranteen_end__c nulls Last');
                // Map<String, List<AssetBean>> assetMap = new Map<String, List<AssetBean>>();
                // for (Asset ass : assList1) {
                //     if (assetMap.containsKey(ass.Fixture_Model_No_F__c) == false) {
                //         assetMap.put(ass.Fixture_Model_No_F__c, new List<AssetBean>());
                //     }
                //     Integer num = ass.You_Xiao_Ku_Cun__c == null ? 0 : Integer.valueOf(ass.You_Xiao_Ku_Cun__c);
                //     assetMap.get(ass.Fixture_Model_No_F__c).add(new AssetBean(ass.Id, num));
                // }

                // Boolean haveChangeAss = false;

                // List<Consum_Apply_Equipment_Set_Detail__c> caesdList = new List<Consum_Apply_Equipment_Set_Detail__c>();
                // for (SObject sobj : selectedData) {
                //     Consum_Apply_Equipment_Set_Detail__c caesdobj = (Consum_Apply_Equipment_Set_Detail__c) sobj;
                //     // String key;
                //     if (String.isBlank(savetype)) {
                //         if (caesdobj.Select_Time__c == null) {
                //             if (String.isNotBlank(caesdobj.Asset__c)) {
                //                 Date d;
                //                 if (parentObj.demo_purpose2__c != '动物实验' && caesdobj.Consum_Start_Date__c != null) {
                //                     d = caesdobj.Consum_Start_Date_After_15_Day__c;
                //                 }
                //                 else {
                //                     d = td;
                //                 }
                //                 System.debug(d);
                //                 System.debug(caesdobj.Consumable_Guaranteen_end_F__c);
                //                 if (caesdobj.Consumable_Guaranteen_end_F__c == null
                //                         // || caesdobj.Consumable_Guaranteen_end_F__c >= fDateMap.get(key)) {
                //                         || caesdobj.Consumable_Guaranteen_end_F__c >= d
                //                         || parentObj.demo_purpose2__c == '动物实验'
                //                 ) {
                //                     caesdobj.Select_Time__c = Datetime.now();
                //                 }
                //                 else {
                //                     caesdobj.Asset__c = null;
                //                     if (assetMap.containsKey(caesdobj.Consum_Apply_Equipment_Set__r.Model_No__c)) {
                //                         for (AssetBean assBean : assetMap.get(caesdobj.Consum_Apply_Equipment_Set__r.Model_No__c)) {
                //                             if (assBean.you_Xiao_Ku_Cun > 0) {
                //                                 caesdobj.Asset__c = assBean.assId;
                //                                 caesdobj.Select_Time__c = Datetime.now();
                //                                 assBean.you_Xiao_Ku_Cun -= 1;
                //                                 haveChangeAss = true;
                //                                 break;
                //                             }
                //                         }
                //                     }
                //                 }
                //                 System.debug(caesdobj.Asset__c);
                //                 caesdList.add(caesdobj);
                //             }
                //         }
                //     }
                // }
                // オブジェクトAPI名
                List<Consum_Apply_Equipment_Set_Detail__c> caesdList = new List<Consum_Apply_Equipment_Set_Detail__c>();
                Boolean haveChangeAss = false;
                haveChangeAss = reSetAsset((List<Consum_Apply_Equipment_Set_Detail__c>)selectedData, caesdList, parentObj, true, String.isBlank(savetype));
                if (caesdList.size() > 0) {
                    if (String.isBlank(savetype)) {
                        System.debug(caesdList);
                        Database.SaveResult[] results = FixtureUtil.withoutUpdate(caesdList, false);
                        for (Database.SaveResult sr : results) {
                            if (sr.isSuccess() == false) {
                                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,
                                '明细:' + sr.getId() + ' 自动分配 error:' + sr));
                                Database.rollback(sp);
                                return;
                            }
                        }
                        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '自动分配保存成功'));
                    }
                }
                else if (String.isBlank(savetype)) {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '没有需要自动分配的明细'));
                }

                String selectedDataSql1 = ' From Consum_Apply_Equipment_Set_Detail__c';
                selectedDataSql1 += ' where Consum_Apply__c = \'' + String.escapeSingleQuotes(parentId) + '\'';
                selectedDataSql1 += ' and Cancel_Select__c = False';
                // 跳转分配代替品画面--选中一览不在这里显示
                if (String.isNotBlank(inRaesId)) {
                    selectedDataSql1 += ' and Id = null';
                }
                selectedDataSql1 += ' order by Fixture_Model_No_F__c, Consumable_Guaranteen_end_F__c nulls last';

                final String soqlStr = 'Select {0} {1} ';
                String soql1 = String.format(soqlStr, new String[] {myComponentController.strColumus , selectedDataSql1});
                selectedData = Consum_ApplyUtil.withoutQueryList(soql1);
                System.debug('zheli:'+selectedData.size());
                if (String.isNotBlank(wherStr1) && String.isBlank(wherStr)) {
                    wherStr = wherStr1;
                }

                String soql = 'SELECT Id'
                                    + ' , SerialNumber'
                                    + ' , Fixture_Model_No_F__c'
                                    + ' , You_Xiao_Ku_Cun__c'
                                    + ' , Consumable_Guaranteen_end__c'
                                    + ' , GroupKey_F__c'
                                + ' FROM Asset'
                               + ' WHERE Id != null '
                                + wherStr
                                 + ' AND ' + assetWhereBase
                                 + ' ORDER BY Salesdepartment__c DESC, Fixture_Model_No_F__c, Consumable_Guaranteen_end__c nulls Last';
                System.debug(soql);
                wherStr1 = wherStr;
                List<Asset> assList = Consum_ApplyUtil.withoutQueryList(soql);
                countMap = Consum_ApplyUtil.getAssetKucun1(assList, null, true, true);
                Map<String, Consum_Apply_Equipment_Set_Detail__c> keyMap = new Map<String, Consum_Apply_Equipment_Set_Detail__c>();
                Boolean haveChange = false;
                Set<String> modelKeySet = new Set<String>();
                System.debug('zheli598:'+selectedData.size());
                for (SObject sobj : selectedData) {
                    Consum_Apply_Equipment_Set_Detail__c caesdobj = (Consum_Apply_Equipment_Set_Detail__c) sobj;
                    if (caesdobj.Asset__c == null) {
                        continue;
                    }
                    // 20220309 ljh  SFDC-CC73U5 132 动物实验&ET展箱 锁定已过期库存 add start
                    // String key = caesdobj.GroupKey_F__c;
                    String key = caesdobj.GroupKey_F__c+caesdobj.Fixture_Model_No__c;
                    // 20220309 ljh  SFDC-CC73U5 132 动物实验&ET展箱 锁定已过期库存 add end
                    if (keyMap.containsKey(key)) {
                        Consum_Apply_Equipment_Set_Detail__c caesd = keyMap.get(key);
                        keyMap.get(key).Request_Num_Jia__c ++;
                        if (caesdobj.Select_Time__c != null) {
                            keyMap.get(key).Jie_Chu_Fen_Pei_Jia__c += 1;
                        }
                        System.debug('zheli598:'+selectedData.size());
                        continue;
                    }
                    keyMap.put(key, caesdobj);
                    if (countMap.get(Consum_ApplyUtil.CUCUNTYPE.You_Xiao_QI_Ku_Cun).containsKey(key)) {
                        caesdobj.You_Xiao_Qi_Ku_Cun_Jia__c = countMap.get(Consum_ApplyUtil.CUCUNTYPE.You_Xiao_QI_Ku_Cun).get(key);
                        caesdobj.Yi_Guo_Qi_Ku_Cun_Jia__c   = countMap.get(Consum_ApplyUtil.CUCUNTYPE.Yi_Guo_Qi_Ku_Cun).get(key);
                    }
                    caesdobj.You_Xiao_Ku_Cun_Jia__c        = countMap.get(Consum_ApplyUtil.CUCUNTYPE.You_Xiao_Ku_Cun).get(key);
                    if (caesdobj.Select_Time__c != null) {
                        caesdobj.Jie_Chu_Fen_Pei_Jia__c = 1;
                    }
                    else {
                        caesdobj.Jie_Chu_Fen_Pei_Jia__c = 0;
                    }

                    caesdobj.Request_Num_Jia__c = 1;
                    caesdobj.No_Jia__c = viewList.size() + 1;
                    viewList.add(new WrapperInfo(caesdobj, 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(caesdobj.Substitute_Select_Again__c));
                }
            }
            System.debug('zheli634:'+viewList.size());
            if (savetype == '1') {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '保存成功'));
            }
        }
        catch(Exception e) {
            Database.rollback(sp);
            // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, e.getStackTraceString() + soql ));
            ApexPages.addmessages(e);
        }
    }

    public static Boolean reSetAsset(List<Consum_Apply_Equipment_Set_Detail__c> selectedData, List<Consum_Apply_Equipment_Set_Detail__c> caesdList, Consum_Apply__c parentObj, Boolean isdef, Boolean needSet) {
        // 20170906 グループリスト取得
        // order by Fixture_Set__c, Fixture_Set__r.Loaner_code__c, IndexFromUniqueKey__c
        wherStr = '';
        String wherStr2 = '';
        Set<String> modelSet = new Set<String>();
        Map<String, Date> fDateMap = new Map<String, Date>();
        Date td = Date.today();
        Map<Date, OlympusCalendar__c> calendarMap = Consum_ApplyUtil.getOlympusCalendarMAp(td, td);
        if (calendarMap.containsKey(td) && calendarMap.get(td).After_15_WorkDay__c != null) {
            td = calendarMap.get(td).After_15_WorkDay__c;
        }
        else {
            td = Consum_ApplyUtil.getWD_addday(td, 15);
        }
        for (Consum_Apply_Equipment_Set_Detail__c caesdobj : selectedData) {
            if (modelSet.contains(caesdobj.Consum_Apply_Equipment_Set__r.Model_No__c) == false) {
                if (String.isBlank(wherStr2)) {
                    wherStr = ' AND (';
                    wherStr2 = ' AND (';
                }
                // wherStr += ' (';
                wherStr2 += ' (';
                wherStr += '(Fixture_Model_No_F__c  = \'' + String.escapeSingleQuotes(caesdobj.Consum_Apply_Equipment_Set__r.Model_No__c) + '\'';
                wherStr2 += 'Fixture_Model_No_F__c  = \'' + String.escapeSingleQuotes(caesdobj.Consum_Apply_Equipment_Set__r.Model_No__c) + '\'';
                // 20220309 ljh  SFDC-CC73U5 132 动物实验&ET展箱 锁定已过期库存 add start
                if (parentObj.demo_purpose2__c != '动物实验' 
                    //2021-04-30  mzy 备品课题-1577 start
                    &&parentObj.demo_purpose2__c != 'ET展箱') {
                    //2021-04-30  mzy 备品课题-1577 end
                // if (caesdobj.demo_purpose2__c != '动物实验' 
                //     && caesdobj.demo_purpose2__c != 'ET展箱') {
                // 20220309 ljh  SFDC-CC73U5 132 动物实验&ET展箱 锁定已过期库存 add end    
                    // Date d1 = caesdobj.Consum_Start_Date_After_15_Day__c == null ? td : caesdobj.Consum_Start_Date_After_15_Day__c;
                    // wherStr += ' AND Consumable_Guaranteen_end__c >= ' + d1.year() + '-' + String.valueOf(d1.month()).leftPad(2,'0') + '-' + String.valueOf(d1.day()).leftPad(2,'0') + ' )';
                    wherStr2 += ' AND (Consumable_Guaranteen_end__c >= ' + td.year() + '-' + String.valueOf(td.month()).leftPad(2,'0') + '-' + String.valueOf(td.day()).leftPad(2,'0');
                    // wherStr += ' OR Consumable_Guaranteen_end__c = null';
                    wherStr2 += ' OR Consumable_Guaranteen_end__c = null)';
                }
                wherStr += ' ) OR';
                wherStr2 += ' ) OR';
                // key = caesdobj.GroupKey_F__c;
                modelSet.add(caesdobj.Consum_Apply_Equipment_Set__r.Model_No__c);
            }
        }

        if (String.isNotBlank(wherStr2)) {
            wherStr = wherStr.removeEnd('OR');
            wherStr2 = wherStr2.removeEnd('OR');
            wherStr += ')';
            wherStr2 += ')';
        }
        // if (String.isNotBlank(parentObj.Internal_asset_location_F__c)) {
            wherStr += ' AND Internal_asset_location__c = \'上海 备品中心\'';
            wherStr2 += ' AND Internal_asset_location__c = \'上海 备品中心\'';
        // } 
        if (String.isNotBlank(parentObj.Salesdepartment__c)) {
            wherStr += ' AND (Salesdepartment__c = \'' + parentObj.Salesdepartment__c + '\' OR Salesdepartment__c = \'0.备品中心\')';
            wherStr2 += ' AND (Salesdepartment__c = \'' + parentObj.Salesdepartment__c + '\' OR Salesdepartment__c = \'0.备品中心\')';
        }
        else {
            wherStr += ' AND Salesdepartment__c = \'0.备品中心\'';
            wherStr2 += ' AND Salesdepartment__c = \'0.备品中心\'';
        }

        // 检索出保有设备，如果默认分配时间过期的话重新分配
        String soql = 'SELECT Id'
                            + ' , SerialNumber'
                            + ' , Fixture_Model_No_F__c'
                            + ' , You_Xiao_Ku_Cun__c'
                            + ' , Consumable_Guaranteen_end__c'
                            + ' , GroupKey_F__c'
                        + ' FROM Asset'
                       + ' WHERE Id != null '
                        + wherStr2
                         + ' AND ' + assetWhereBase;
                         System.debug(wherStr);

        System.debug(soql);
        // 因为保有设备的借出分配数会变，所以需要Lock
        Consum_ApplyUtil.withoutQueryList(soql + ' FOR UPDATE');
        List<Asset> assList1 = Consum_ApplyUtil.withoutQueryList(soql +  + ' ORDER BY Salesdepartment__c DESC, Fixture_Model_No_F__c, Consumable_Guaranteen_end__c nulls Last');
        Map<String, List<AssetBean>> assetMap = new Map<String, List<AssetBean>>();
        for (Asset ass : assList1) {
            if (assetMap.containsKey(ass.Fixture_Model_No_F__c) == false) {
                assetMap.put(ass.Fixture_Model_No_F__c, new List<AssetBean>());
            }
            Integer num = ass.You_Xiao_Ku_Cun__c == null ? 0 : Integer.valueOf(ass.You_Xiao_Ku_Cun__c);
            assetMap.get(ass.Fixture_Model_No_F__c).add(new AssetBean(ass.Id, num));
        }

        Boolean haveChangeAss = false;

        for (Consum_Apply_Equipment_Set_Detail__c caesdobj : selectedData) {
            if (caesdobj.Shipment_request_time2__c != null) {
                continue;
            }
            // String key;
            if (needSet) {
                // if (caesdobj.Select_Time__c == null) {
                    // if (String.isNotBlank(caesdobj.Asset__c)) {
                        Date d;
                        // if (parentObj.demo_purpose2__c != '动物实验' && caesdobj.Consum_Start_Date__c != null) {
                        //     d = caesdobj.Consum_Start_Date_After_15_Day__c;
                        // }
                        // else {
                        //     d = td;
                        // }
                        d = td;
                        System.debug(d);
                        System.debug(caesdobj.Consumable_Guaranteen_end_F__c);
                        if (String.isNotBlank(caesdobj.Asset__c)
                                && (caesdobj.Consumable_Guaranteen_end_F__c == null
                                    // || caesdobj.Consumable_Guaranteen_end_F__c >= fDateMap.get(key)) {
                                    || caesdobj.Consumable_Guaranteen_end_F__c >= d
                                    // 20220309 ljh  SFDC-CC73U5 132 动物实验&ET展箱 锁定已过期库存 add start
                                    || parentObj.demo_purpose2__c == '动物实验'
                                    //2021-04-30  mzy 备品课题-1577 start
                                    || parentObj.demo_purpose2__c == 'ET展箱'
                                    //2021-04-30  mzy 备品课题-1577 end
                                    // || caesdobj.demo_purpose2__c == '动物实验'
                                    // || caesdobj.demo_purpose2__c == 'ET展箱'
                                    // 20220309 ljh  SFDC-CC73U5 132 动物实验&ET展箱 锁定已过期库存 add end
                                   )
                        ) {
                            if (caesdobj.Select_Time__c == null) {
                                caesdobj.Select_Time__c = Datetime.now();
                                caesdList.add(caesdobj);
                            }
                        }
                        else {
                            String oasId = caesdobj.Asset__c;
                            caesdobj.Asset__c = null;
                            if (assetMap.containsKey(caesdobj.Consum_Apply_Equipment_Set__r.Model_No__c)) {
                                for (AssetBean assBean : assetMap.get(caesdobj.Consum_Apply_Equipment_Set__r.Model_No__c)) {
                                    if (assBean.you_Xiao_Ku_Cun > 0
                                        && (caesdobj.Consumable_Guaranteen_end_F__c == null
                                            // || caesdobj.Consumable_Guaranteen_end_F__c >= fDateMap.get(key)) {
                                            || caesdobj.Consumable_Guaranteen_end_F__c > d
                                            // 20220309 ljh  SFDC-CC73U5 132 动物实验&ET展箱 锁定已过期库存 add start
                                            || parentObj.demo_purpose2__c == '动物实验'
                                            //2021-04-30  mzy 备品课题-1577 start
                                            || parentObj.demo_purpose2__c == 'ET展箱'
                                            //2021-04-30  mzy 备品课题-1577 end
                                            // || caesdobj.demo_purpose2__c == '动物实验'
                                            // || caesdobj.demo_purpose2__c == 'ET展箱'
                                            // 20220309 ljh  SFDC-CC73U5 132 动物实验&ET展箱 锁定已过期库存 add end
                                            )
                                    ) {
                                        caesdobj.Asset__c = assBean.assId;
                                        caesdobj.Select_Time__c = Datetime.now();
                                        assBean.you_Xiao_Ku_Cun -= 1;
                                        haveChangeAss = true;
                                        break;
                                    }
                                }
                            }
                            if (oasId != caesdobj.Asset__c) {
                                caesdList.add(caesdobj);
                            }
                        }
                        System.debug(caesdobj.Asset__c);
                        
                    // }
                // }
            }
        }
        return haveChangeAss;
    }

    public void setShipment_request() {
        needOpenPage = false;
        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_date__c
                         , Campaign__c
                         , Campaign__r.Status
                         , Wei_Assigned_Cnt__c
                         //, Repair__c
                         , Assigned_Not_Shipment__c
                         //, Contract_pdf_updated__c
                      FROM Consum_Apply__c
                     WHERE Id = :parentId
                       FOR UPDATE
                     ];
        if (parentObjs.size() == 0) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '耗材申请不正确。请刷新画面重试。'));
            return ;
        }
        else {
            parentObj = parentObjs[0];
        }
        String errorMsg = '';
        if (String.isNotBlank(parentObj.Campaign__c)
            && parentObj.Campaign__r.Status == '取消') {
            errorMsg = '学会取消，不可出库指示';
        }
        // else if (parentObj.Status__c == '已出库指示'
        //     && parentObj.Assigned_Not_Shipment__c == 0) {
        //     errorMsg = '所有的耗材备品一览都进行过出库指示了';
        // }
        // else if (parentObj.Assigned_Not_Shipment__c == 0) {
        //     errorMsg = '没有可以出库指示的明细';
        // }

        if (String.isNotBlank(errorMsg)) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, errorMsg));
            return ;
        }
        String msg = ConsumApplyWebService.setShipment_request(parentObj.Id);
        needOpenPage = (msg == '状态更新到已出库指示');
        ApexPages.addmessage(new ApexPages.message(msg == '状态更新到已出库指示' ? ApexPages.severity.CONFIRM : ApexPages.severity.ERROR, msg));
    }

    public class AssetBean {
        public Id assId;
        public Integer you_Xiao_Ku_Cun;

        public AssetBean(Id assId1, Integer you_Xiao_Ku_Cun1) {
            assId = assId1;
            you_Xiao_Ku_Cun = you_Xiao_Ku_Cun1;
        }
    }

}