/**
 * 备品配套选择
 */
public with sharing class ConsumSelectController 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_Equipment_Set__c = \'' + String.escapeSingleQuotes(parentId) + '\'';
        // selectedDataSql += ' AND Asset__c != null ';
        selectedDataSql += ' and Cancel_Select__c = False';
        // 跳转分配代替品画面--选中一览不在这里显示
        if (String.isNotBlank(inRaesId)) {
            selectedDataSql += ' and Id = null';
        }
        selectedDataSql += ' order by Degree_Of_Importance__c DESC, IndexFromUniqueKey__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');
        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 = 'ConsumSelect_L';
        return columnLeftFieldSetName;
    }
    public override String getColumnRightFieldSetName() {
        // 右の項目セット
        columnRightFieldSetName = 'ConsumSelect_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'
                , 'Salesdepartment__c'
                , 'Consum_Apply_Equipment_Set__r.Model_No__c'
                , 'Consum_Apply_Equipment_Set__r.Consum_Start_Date__c'
                , 'Asset__r.You_Xiao_Ku_Cun__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', 'Fen_Pei_Shu_Liang_Jia__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更新

    public String saveType { get; set; }
    public Consum_Apply_Equipment_Set__c parentObj { get; set; }

    private 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 =\'' + System.Label.Asset_RecordType + '\' AND ' + FixtureUtil.getAssetSoqlBase();//niwu change to custom label

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

    public ConsumSelectController() {
        parentId = ApexPages.currentPage().getParameters().get('recid');
        inRaesId = ApexPages.currentPage().getParameters().get('raesid');
        savetype = ApexPages.currentPage().getParameters().get('savetype');
        isRadio = String.isBlank(this.inRaesId) ? false : true;   // 分配代替品--选择配套画面只能单选
        System.debug('-----------------parentId-------------------');
        System.debug(parentId);
        System.debug('-----------------inRaesId-------------------');
        System.debug(inRaesId);
        System.debug('-----------------savetype-------------------');
        System.debug(savetype);
        //备品配套下的所有明细
        if (!String.isBlank(this.parentId)) {
            List<Consum_Apply_Equipment_Set__c> parentObjs = [
                    SELECT Id
                         , Name
                         , Model_No__c
                         , Internal_asset_location__c
                         , Wei_Assigned_Cnt__c
                         , RetalFSetDetail_Cnt__c
                         , Consum_Apply__r.Status__c
                         , Consum_Apply__r.RequestNoJoinStr2__c
                         , Consum_Apply__r.demo_purpose2__c
                         , Consum_Apply__r.Internal_asset_location_F__c
                         , Consum_Apply__r.Salesdepartment__c
                         , Consum_Apply__r.Person_In_Charge__c
                         , Consum_Apply__r.Salesdept__c
                         , Consum_Apply__r.WorkPlace__c
                         , Consum_Apply__r.Request_shipping_day__c
                         , Consum_Apply__r.Asset_loaner_start_date__c
                         , Consum_Apply__c
                      FROM Consum_Apply_Equipment_Set__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];
            System.debug('-----------------selectedRaesList-------------------');
            System.debug(this.selectedRaesList);
            if (selectedRaesList.size() == 0) {
                throw new ControllerUtil.myException('沒有指定备品借出申请一览或者数据不正。');
            }
        }
        System.debug('ConsumSelectController');
    }

    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 {
            Map<String, Integer> selectMap = new Map<String, Integer>();
            Integer totalSelectCount = 0;
            for (WrapperInfo info : viewList) {
                if (info.check) {
                    Consum_Apply_Equipment_Set_Detail__c caesd = (Consum_Apply_Equipment_Set_Detail__c)info.sobj;
                    String key = caesd.GroupKey_F__c;
                    System.debug(caesd.Consumable_Guaranteen_end_F__c);
                    System.debug(key);
                    selectMap.put(key, Integer.valueOf(caesd.Fen_Pei_Shu_Liang_Jia__c == null ? 0 : caesd.Fen_Pei_Shu_Liang_Jia__c));
                    totalSelectCount += selectMap.get(key);
                    if (Integer.valueOf(info.additionalInfoMap.get('SelectCount')) > caesd.Fen_Pei_Shu_Liang_Jia__c) {
                        throw new ControllerUtil.myException('分配数量不能减少。');
                    }
                }
            }

            String wher = ' AND Fixture_Model_No_F__c  = \'' + String.escapeSingleQuotes(parentObj.Model_No__c) + '\'';
            // if (String.isNotBlank(parentObj.Consum_Apply__r.Internal_asset_location_F__c)) {
                wher += ' AND Internal_asset_location__c = \'上海 备品中心\'';
            // }
            // if (String.isNotBlank(parentObj.Consum_Apply__r.Salesdepartment__c)) {
            //     wher += ' AND (Salesdepartment__c = \'' + parentObj.Consum_Apply__r.Salesdepartment__c + '\' OR Salesdepartment__c = \'0.备品中心\')';
            // }
            // else {
            //     wher += ' 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'
                                + ' , Salesdepartment__c'
                            + ' FROM Asset'
                           + ' WHERE Id != null AND You_Xiao_Ku_Cun__c > 0 '
                            + wher
                             + ' AND ' + assetWhereBase;
                             // + ' ORDER BY Salesdepartment__c , Fixture_Model_No_F__c, Consumable_Guaranteen_end__c';
            System.debug(soql);
            Database.query(soql + ' FOR UPDATE');
            List<Asset> assList = Database.query(soql + ' ORDER BY Salesdepartment__c , Fixture_Model_No_F__c, Consumable_Guaranteen_end__c');
            List<Asset> assetListDepartSelf = new List<Asset>();
            List<Asset> assetListDepart0 = new List<Asset>();
            List<Asset> assetListDepartOther = new List<Asset>();
            for(Asset ass : assList){
                if(ass.Salesdepartment__c == '0.备品中心'){
                    assetListDepart0.add(ass);
                }
                else if( ass.Salesdepartment__c == parentObj.Consum_Apply__r.Salesdepartment__c){
                    assetListDepartSelf.add(ass);
                }
                else{
                    assetListDepartOther.add(ass);
                }
            }
            assList = new List<Asset>();
            assList.addAll(assetListDepartSelf);
            assList.addAll(assetListDepart0);
            assList.addAll(assetListDepartOther);

            Map<String, List<Map<String, String>>> assetMap = new Map<String, List<Map<String, String>>>();
            for (Asset ass : assList) {
                if (assetMap.containsKey(ass.GroupKey_F__c) == false) {
                    assetMap.put(ass.GroupKey_F__c, new List<Map<String, String>>());
                }
                assetMap.get(ass.GroupKey_F__c).add(new Map<String, String>{'ID' => ass.Id, 'You_Xiao_Ku_Cun' => String.valueOf(ass.You_Xiao_Ku_Cun__c)});
            }

            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
                     FROM Consum_Apply_Equipment_Set_Detail__c
                    WHERE Consum_Apply_Equipment_Set__c = :parentId
                      AND Cancel_Select__c = False
                    ORDER BY Degree_Of_Importance__c];
            System.debug('-----------------carsdList-------------------');
            System.debug(carsdList);
            if(totalSelectCount > carsdList.size()) {
                throw new ControllerUtil.myException('分配总数量大于明细数量！');
            }
            Map<String, List<Consum_Apply_Equipment_Set_Detail__c>> caesdSelectMap = new Map<String, List<Consum_Apply_Equipment_Set_Detail__c>>();
            Map<String, List<Consum_Apply_Equipment_Set_Detail__c>> caesdNoSelectMap = new Map<String, List<Consum_Apply_Equipment_Set_Detail__c>>();
            List<Consum_Apply_Equipment_Set_Detail__c> caesdsList = new List<Consum_Apply_Equipment_Set_Detail__c>();
            Map<Id, Consum_Apply_Equipment_Set_Detail__c> caesdMap = new Map<Id, Consum_Apply_Equipment_Set_Detail__c>(); // 待更新的明细
            System.debug(carsdList);
            for (Consum_Apply_Equipment_Set_Detail__c caesd : carsdList) {
                if (caesd.GroupKey_F__c != null) {
                    if (caesd.Select_Time__c != null) {
                        if (caesdSelectMap.containsKey(caesd.GroupKey_F__c) == false) {
                            caesdSelectMap.put(caesd.GroupKey_F__c, new List<Consum_Apply_Equipment_Set_Detail__c>());
                        }
                        caesdSelectMap.get(caesd.GroupKey_F__c).add(caesd); //已分配的明细
                    }
                    else {
                        if (caesdNoSelectMap.containsKey(caesd.GroupKey_F__c) == false) {
                            caesdNoSelectMap.put(caesd.GroupKey_F__c, new List<Consum_Apply_Equipment_Set_Detail__c>());
                        }
                        caesdNoSelectMap.get(caesd.GroupKey_F__c).add(caesd); //暂定分配的明细
                    }
                }
                else {
                    caesdsList.add(caesd); // 待分配的明细
                }
                //caesdMap.put(caesd.Id, caesd);
            }

            List<Consum_Apply_Equipment_Set_Detail__c> needUpdateList = new List<Consum_Apply_Equipment_Set_Detail__c>();
            Datetime no = Datetime.now();
            // 依据将重要程度值，取消分配
            for (String key : selectMap.keySet()) {
                Integer unAssignedCount = 0;
                if(caesdSelectMap.containsKey(key)){
                    // 新填的数值小于已分配的数，需要取消分配
                    unAssignedCount = caesdSelectMap.get(key).size() - selectMap.get(key);
                }
                for (Integer i = 0; i < unAssignedCount; i ++) {
                    if (caesdSelectMap.containsKey(key) ){
                        Integer size = caesdSelectMap.get(key).size();
                        if(size > 0) {
                            // 下标越大，越不重要
                            Consum_Apply_Equipment_Set_Detail__c caesd = caesdSelectMap.get(key)[size - 1];
                            caesd.Asset__c = null;
                            caesd.Select_Time__c = null;
                            caesdsList.add(caesd);
                            caesdMap.put(caesd.Id,caesd);
                            caesdSelectMap.get(key).remove(size - 1);
                        }
                    }
                }
            }
            // 按新的填写数执行分配
            for (String key : selectMap.keySet()) {
                for (Integer i = 0; i < selectMap.get(key); i ++) {
                    // 已经分配
                    if (caesdSelectMap.containsKey(key)) {
                        List<Consum_Apply_Equipment_Set_Detail__c> caesdList = caesdSelectMap.get(key);
                        if (caesdList.size() > 0) {
                            //caesdMap.remove(caesdList[0].Id);
                            caesdList.remove(0);
                            continue;
                        }
                    }

                    // 暂定分配
                    if (caesdNoSelectMap.containsKey(key)) {
                        List<Consum_Apply_Equipment_Set_Detail__c> caesdList = caesdNoSelectMap.get(key);
                        if (caesdList.size() > 0) {
                            caesdList[0].Select_Time__c = no;
                            //needUpdateList.add(caesdList[0]);
                            //caesdMap.remove(caesdList[0].Id);
                            caesdMap.put(caesdList[0].Id,caesdList[0]);
                            caesdList.remove(0);
                            continue;
                        }
                    }

                    // 待分配
                    if (caesdsList.size() > 0) {
                        if (assetMap.containsKey(key) == false) {
                            throw new ControllerUtil.myException('保有设备有变动,请刷新画面重试');
                        }
                        List<Map<String, String>> assList1 = assetMap.get(key);
                        if (assList1.size() == 0) {
                            throw new ControllerUtil.myException('分配数量大于可分配数量,请刷新画面重试');
                        }
                        Map<String, String> asMa = assList1[0];
                        Integer You_Xiao_Ku_Cun = Integer.valueOf(asMa.get('You_Xiao_Ku_Cun'));
                        caesdsList[0].Asset__c = asMa.get('ID');
                        caesdsList[0].Select_Time__c = no;
                        //needUpdateList.add(caesdsList[0]);
                        You_Xiao_Ku_Cun -= 1;
                        if (You_Xiao_Ku_Cun == 0) {
                            assList1.remove(0);
                        }
                        else {
                            asMa.put('You_Xiao_Ku_Cun', String.valueOf(You_Xiao_Ku_Cun));
                        }
                        //caesdMap.remove(caesdsList[0].Id);
                        caesdMap.put(caesdsList[0].Id,caesdsList[0]);
                        caesdsList.remove(0);
                    }
                }

                //if (caesdSelectMap.containsKey(key)) {
                //    List<Consum_Apply_Equipment_Set_Detail__c> caesdList = caesdSelectMap.get(key);
                //    for (Consum_Apply_Equipment_Set_Detail__c caesd : caesdList) {
                //        caesd.Asset__c = null;
                //        caesd.Select_Time__c = null;
                //        caesdsList.add(caesd);
                //    }
                //        //List<Consum_Apply_Equipment_Set_Detail__c> cList = caesdList;
                //        //cList.addAll(caesdsList);
                //        //caesdsList = cList;
                //}
            }

            System.debug('qyj+caesdMap'+caesdMap);
            for (String key : caesdMap.keySet()) {
                Consum_Apply_Equipment_Set_Detail__c caesd = caesdMap.get(key);
                //if(selectMap.containsKey(caesd.GroupKey_F__c)){
                    //caesd.Asset__c = null;
                    //caesd.Select_Time__c = null;
                    needUpdateList.add(caesd);
                //}
            }
            System.debug('qyj+needUpdateList'+needUpdateList);
            if (needUpdateList.size() > 0) {
                FixtureUtil.withoutUpdate(needUpdateList);
            }

        } catch (Exception ex) {
            ApexPages.addMessages(ex);
            System.debug(ex.getStackTraceString());
            Database.rollback(sp);
            return null;
        }
        PageReference pa = new PageReference('/apex/ConsumSelect?recid=' + parentId + '&savetype=1');
        pa.setRedirect(true);
        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(parentObj.Consum_Apply__c)) {
            ret = new PageReference('/' + parentObj.Consum_Apply__c);
        }
        return ret;
    }

    public override void setViewList(List<sObject> queryList) {
        System.debug('---------------setViewList----------------');
        System.Savepoint sp = Database.setSavepoint();
        try {

            viewList = new List<WrapperInfo>();
            Set<String> modelSet = new Set<String>();
            Map<String, Integer> assetCountMap = new Map<String, Integer>();
            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
                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();
                List<Consum_Apply_Equipment_Set_Detail__c> caesdList = new List<Consum_Apply_Equipment_Set_Detail__c>();
                Map<String, Integer> groupMap = new Map<String, Integer>();
                Set<Id> assetIdSet = new Set<Id>();
                for (SObject sobj : selectedData) {
                    Consum_Apply_Equipment_Set_Detail__c caesdobj = (Consum_Apply_Equipment_Set_Detail__c) sobj;
                    if (String.isNotBlank(caesdobj.Asset__c)
                        && caesdobj.Select_Time__c == null) {
                        throw new ControllerUtil.myException('请在默认分配后再做分配操作。');
                    }
                    if (groupMap.containsKey(caesdobj.GroupKey_F__c) == false) {
                        groupMap.put(caesdobj.GroupKey_F__c, 0);
                    }
                    if (caesdobj.Select_Time__c != null) {
                        groupMap.put(caesdobj.GroupKey_F__c, groupMap.get(caesdobj.GroupKey_F__c) + 1);
                    }
                    if (String.isNotBlank(caesdobj.Asset__c)) {
                        assetIdSet.add(caesdobj.Asset__c);
                    }
                    // String key;
                    // if (modelSet.contains(caesdobj.Consum_Apply_Equipment_Set__r.Model_No__c) == false) {
                        // if (String.isBlank(wher)) {
                            // wher = ' AND (';
                        // }
                        // Date d1 = caesdobj.Consum_Apply_Equipment_Set__r.Consum_Start_Date__c == null ? Date.today() : caesdobj.Consum_Apply_Equipment_Set__r.Consum_Start_Date__c;
                        // wher += ' AND Consumable_Guaranteen_end__c >= ' + d1.year() + '-' + String.valueOf(d1.month()).leftPad(2,'0') + '-' + String.valueOf(d1.day()).leftPad(2,'0') + ' )';
                        // wher += ' OR Consumable_Guaranteen_end__c = null';
                        // wher += ' ) OR';
                        // key = caesdobj.GroupKey_F__c;
                        // modelSet.add(caesdobj.Consum_Apply_Equipment_Set__r.Model_No__c);
                    // }
                    // 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;
                    //             }
                    //             if (caesdobj.Consumable_Guaranteen_end_F__c == null
                    //                     // || caesdobj.Consumable_Guaranteen_end_F__c >= fDateMap.get(key)) {
                    //                     || caesdobj.Consumable_Guaranteen_end_F__c >= d) {
                    //                 caesdobj.Select_Time__c = Datetime.now();
                    //             }
                    //             else {
                    //                 caesdobj.Asset__c = null;
                    //             }
                    //             caesdList.add(caesdobj);
                    //         }
                    //     }
                    // }
                }

                // if (String.isBlank(savetype) && caesdList.size() > 0) {
                //     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;
                //         }
                //     }
                // }
                String wher = ' AND Fixture_Model_No_F__c  = \'' + String.escapeSingleQuotes(parentObj.Model_No__c) + '\'';
                // if (String.isNotBlank(parentObj.Consum_Apply__r.Internal_asset_location_F__c)) {
                    wher += ' AND Internal_asset_location__c = \'上海 备品中心\'';
                // }
                // if (String.isNotBlank(parentObj.Consum_Apply__r.Salesdepartment__c)) {
                //     wher += ' AND (Salesdepartment__c = \'' + parentObj.Consum_Apply__r.Salesdepartment__c + '\' OR Salesdepartment__c = \'0.备品中心\')';
                // }
                // else {
                //     wher += ' AND Salesdepartment__c = \'0.备品中心\'';
                // }
                // 2021-04-30 mzy update  备品课题-1577  start
                if(parentObj.Consum_Apply__r.demo_purpose2__c != '动物实验'&& parentObj.Consum_Apply__r.demo_purpose2__c != 'ET展箱') {
                // 2021-04-30 mzy update  备品课题-1577  end    
                    wher += ' AND (Consumable_Guaranteen_end__c > ' + td.year() + '-' + String.valueOf(td.month()).leftPad(2,'0') + '-' + String.valueOf(td.day()).leftPad(2,'0') ;
                    wher += ' OR Consumable_Guaranteen_end__c = null)';
                }
                String soql = 'SELECT Id'
                                    + ' , SerialNumber'
                                    + ' , Fixture_Model_No_F__c'
                                    + ' , You_Xiao_Ku_Cun__c'
                                    + ' , Consumable_Guaranteen_end__c'
                                    + ' , GroupKey_F__c'
                                    + ' , Salesdepartment__c'
                                + ' FROM Asset'
                               + ' WHERE Id != null AND (You_Xiao_Ku_Cun__c > 0 OR Id = :assetIdSet)'
                                + wher
                                 + ' AND ' + assetWhereBase
                                 + ' ORDER BY Salesdepartment__c, Fixture_Model_No_F__c, Consumable_Guaranteen_end__c';
                System.debug(soql);
                List<Asset> assList = Database.query(soql);
                List<Asset> assetListDepartSelf = new List<Asset>();
                List<Asset> assetListDepart0 = new List<Asset>();
                List<Asset> assetListDepartOther = new List<Asset>();
                for(Asset ass : assList){
                    if(ass.Salesdepartment__c == '0.备品中心'){
                        assetListDepart0.add(ass);
                    }
                    else if( ass.Salesdepartment__c == parentObj.Consum_Apply__r.Salesdepartment__c){
                        assetListDepartSelf.add(ass);
                    }
                    else{
                        assetListDepartOther.add(ass);
                    }
                }
                assList = new List<Asset>();
                assList.addAll(assetListDepartSelf);
                assList.addAll(assetListDepart0);
                assList.addAll(assetListDepartOther);
                System.debug(assList);
                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>();
                List<Consum_Apply_Equipment_Set_Detail__c> tempList = new List<Consum_Apply_Equipment_Set_Detail__c>();
                Map<String, Consum_Apply_Equipment_Set_Detail__c> tempMap = new Map<String, Consum_Apply_Equipment_Set_Detail__c>();
                for (Integer i = 0; i < assList.size(); i++) {
                    // 501を超えた場合前500のみを出す
                    if (i == getSearchNumMax()) { break; }
                    Asset ass = (Asset)assList[i];
                    if (tempMap.containsKey(ass.GroupKey_F__c)) {
                        continue;
                    }

                    // 一覧のsize
                    // ここnewではない、makeSelectedDataInfoのdataをcloneしてください。
                    Consum_Apply_Equipment_Set_Detail__c mf = ((Consum_Apply_Equipment_Set_Detail__c) selectedData[0]).clone(false);

                    // ****************注意:这里不能随意清空字段,如果要清空一定要慎重再慎重,因为保存的时候可能会把有值的字段清空掉
                    // 因为检索的时候需要显示检索出来的Asset信息，所以需要清除Clone出来的值，好让数据可以的Handler里面赋成当前Asset值
                    // mf.Fixture_Model_No_text__c = null; OLY_OCM-431 不设定， 设定的话 画面会显示成 代替品
                    mf.SerialNumber_text__c = null;
                    mf.SalesProvince_before__c = null;
                    mf.Salesdepartment_before__c = null;
                    mf.Product_category_text__c = null;
                    mf.Equipment_Type_text__c = null;
                    mf.Asset_cost_del_before__c = null;
                    mf.Internal_asset_location_before__c = null;
                    mf.EquipmentSet_Managment_Code_text__c = null;
                    mf.You_Xiao_Ku_Cun_Jia__c = countMap.get(Consum_ApplyUtil.CUCUNTYPE.You_Xiao_Ku_Cun).get(ass.GroupKey_F__c);
                    mf.Asset__c                             = ass.Id;
                    mf.UniqueKey__c = null;
                    /* ---------------- OLY_OCM-603 Start 最新预定归还日显示保有设备新建的公式字段 */
                    // if (ass.Last_Reserve_RAES_Detail__c != null) {
                        //有last的话一览为最新借出一览明细的一览(显示最新预计归还日)
                        // mf.Rental_Apply_Equipment_Set__c = ass.Last_Reserve_RAES_Detail__r.Rental_Apply_Equipment_Set__c;
                    // } else {
                        //没有last的话一览为新建的一览(最新预计归还日为空)
                        mf.Consum_Apply_Equipment_Set__c = parentObj.Id;
                    // }
                    /* ---------------- OLY_OCM-603 End */
                    mf.DataMigration_Flag__c                = true;
                    tempMap.put(ass.GroupKey_F__c, mf);
                    tempList.add(mf);
                }
                
                Database.SaveResult[] results = FixtureUtil.withoutInsert(tempList, false);

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

                tempList = (List<Consum_Apply_Equipment_Set_Detail__c>)Consum_ApplyUtil.queryTempList(soql, tempList);
                if (countMap.get(Consum_ApplyUtil.CUCUNTYPE.You_Xiao_Ku_Cun).keySet().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;
                        }
                    }
                }

                // 強制ロールバックしますが、数式の値が取れたインスタンスがfsDMapに保持
                Database.rollback(sp);

                List<Consum_Apply_Equipment_Set_Detail__c> caesdListsame = new List<Consum_Apply_Equipment_Set_Detail__c>();
                List<Consum_Apply_Equipment_Set_Detail__c> caesdList0 = new List<Consum_Apply_Equipment_Set_Detail__c>();
                List<Consum_Apply_Equipment_Set_Detail__c> caesdListother = new List<Consum_Apply_Equipment_Set_Detail__c>();

                for (Consum_Apply_Equipment_Set_Detail__c caesd : tempList) {
                    if (caesd.Salesdepartment__c == parentObj.Consum_Apply__r.Salesdepartment__c) {
                        caesdListsame.add(caesd);
                    }
                    else if (caesd.Salesdepartment__c == '0.备品中心') {
                        caesdList0.add(caesd);
                    }
                    else {
                        caesdListother.add(caesd);
                    }
                }

                tempList = new List<Consum_Apply_Equipment_Set_Detail__c>();
                tempList.addAll(caesdListsame);
                tempList.addAll(caesdList0);
                tempList.addAll(caesdListother);
                System.debug('---------------tempList----------------');
                System.debug(tempList);
                for (Integer i = 0; i < tempList.size(); i++) {
                    // 501を超えた場合前500のみを出す
                    if (i == getSearchNumMax()) { break; }

                    Consum_Apply_Equipment_Set_Detail__c mf = (Consum_Apply_Equipment_Set_Detail__c) tempList[i];
                    mf.Fen_Pei_Shu_Liang_Jia__c = groupMap.containsKey(mf.GroupKey_F__c) ? groupMap.get(mf.GroupKey_F__c) : 0;
                    WrapperInfo info = new WrapperInfo(mf, myComponentController);
                    viewList.add(new WrapperInfo(mf, myComponentController));
                    viewList[viewList.size() - 1].canEdit = (parentObj.Wei_Assigned_Cnt__c  > 0 && mf.Asset__r.You_Xiao_Ku_Cun__c > 0);
                    viewList[viewList.size() - 1].lineNo = viewList.size() - 1;
                    //viewList[viewList.size() - 1].additionalInfoMap.put('Substitute_Select_Again__c', '');
                    viewList[viewList.size() - 1].additionalInfoMap.put('SelectCount', String.valueOf(mf.Fen_Pei_Shu_Liang_Jia__c));
                    if (mf.Fen_Pei_Shu_Liang_Jia__c > 0) {
                        viewList[viewList.size() - 1].check = true;
                    }
                }
                System.debug('---------------viewList----------------');
                System.debug(viewList);
                // for (SObject sobj : selectedData) {
                //     Consum_Apply_Equipment_Set_Detail__c caesdobj = (Consum_Apply_Equipment_Set_Detail__c) sobj;
                //     if (caesdobj.Asset__c == null) {
                //         continue;
                //     }
                //     String key = caesdobj.GroupKey_F__c;
                //     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;
                //         }
                //         continue;
                //     }
                //     keyMap.put(key, caesdobj);
                //     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));
                // }
            }
            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()));
            ApexPages.addmessages(e);
        }
    }

    public void setShipment_request() {
        String msg = ConsumApplyWebService.setShipment_request(parentObj.Id);
        ApexPages.addmessage(new ApexPages.message(msg == '状态更新到已出库指示' ? ApexPages.severity.INFO : ApexPages.severity.ERROR, msg));
    }

    @TestVisible private static void test() {
        if (false == Test.isRunningTest()) return;
        Integer i = 0;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
    }
}