public with sharing class ConsumEquipmentSetReceivedController extends CreateRelationListPagingCtrlBase{
    private String cesIdsStr;
    private List<String> cesIdList;
    public String c_apply_no { get; private set; }
    public Boolean done_flg { get;  set; }
    private String keywdSort = null;
    public FixtureDeliverySlip__c slip { get; set; }
    public String keepWher { get; set; }
    public String changeMessage { get; set; }
    public String keyword { get; set; }
    public String keywordDate { get; set; }
    public Boolean saveBtnDisabled { get; private set; }
    private List<Consum_Apply_Equipment_Set_Detail__c> useCaesdList;
    private Map<Id, String> whlocMap;
    private Boolean cancelAction;

    public ConsumEquipmentSetReceivedController() {
        cesIdsStr = ApexPages.currentPage().getParameters().get('id');
    }

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

    /* 選択されたデータ取得用Soql　Fromから*/
    public override String getSelectedDataSql() {
        // オブジェクトAPI名
        selectedDataSql = ' where Id != null ';
        selectedDataSql += '   and (';

        for (String caesStr : cesIdList) {
            selectedDataSql += ' Consum_Apply_Equipment_Set__r.Name = \'' + String.escapeSingleQuotes(caesStr) + '\' OR Consum_Apply_Equipment_Set__c = \'' + String.escapeSingleQuotes(caesStr) + '\' OR';
        }
        selectedDataSql = selectedDataSql.removeEnd('OR');
        selectedDataSql += ')';
        selectedDataSql += '   and Shipment_request_time2__c != null';
        selectedDataSql += '   and Cancel_Select__c = False';
        selectedDataSql += '   and Return_DeliverySlip__c != null';
        selectedDataSql += '   and Consum_Apply__r.AssetManageConfirm__c = true';
        //selectedDataSql += ' order by Id ASC nulls last';
        keepWher = selectedDataSql;
        selectedDataSql = ' From Consum_Apply_Equipment_Set_Detail__c' + selectedDataSql + ' order by Fixture_Model_No_F__c nulls last, Consumable_Guaranteen_end_F__c nulls last, name';
        myComponentController.columnRightRW.put('Hui_Ji_Jia__c', 'r');
        myComponentController.columnRightRW.put('WH_location__c', 'r');
        myComponentController.columnRightRW.put('Yi_Zhi_Bao_Fei_Jia__c', 'w');
        myComponentController.columnRightRW.put('Yi_Zhi_Guo_Qi_Jia__c', 'w');
        myComponentController.columnRightRW.put('Shang_Jia_Jia__c', 'w');

        return selectedDataSql;
    }

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

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

    public override List<String> getColumnFieldList() {
        // strColumus 里加 field
        // FixtureUtil#raesdGroupBy()の項目も必要
        return new List<String>{'Id', 'Asset__c', 'Asset__r.WH_location__c', 'Consum_Apply__r.demo_purpose2__c','Shipment_Saved_Flg__c', 'Shipment_request_time2__c', 'Consum_Apply_Equipment_Set__r.Yi_Shipment_request__c'};
    }
    public override List<String> getHiddenFieldList() {
        return new List<String>{'Product_Serial_No_F__c','Comment__c'};
    }
    // getObjName 连 getOriginObjName 的 FK
    public override String getFKColumnField() {
        return null;
    }

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

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

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

        return sqlWhereStr;

    }

    public override String getOrderbyStr() {
        return 'order by Fixture_Model_No_F__c nulls last, Consumable_Guaranteen_end_F__c nulls last,name';
    }

    public override Boolean getIsNeedRunSearch() {

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

    public void init() {

        Set<Id> rnsIdSet = new Set<Id>();
        String jsonStr;
        cancelAction = false;
        // 当前User
        String userid = Userinfo.getUserId();

        if (cesIdsStr != null) {
            cesIdList = cesIdsStr.split(',');

            // 借出耗材备品一览
            List<Consum_Apply_Equipment_Set__c> rnsList = [select Id, Consum_Apply__c, Consum_Apply__r.Name, Consum_Apply__r.Shipment_Slip_tmp__c
                                            from Consum_Apply_Equipment_Set__c
                                           where (Name in :cesIdList or Id in :cesIdList)
                                             ];

            if (rnsList.size() > 0) {
                for (Consum_Apply_Equipment_Set__c rns : rnsList) {
                    rnsIdSet.add(rns.Id);
                    c_apply_no = rns.Consum_Apply__r.Name;
                }
                parentId = rnsList[0].Consum_Apply__c;
            } else {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '借出耗材备品一览不存在'));
                saveBtnDisabled = true;
                return;
            }
        }
        slip = new FixtureDeliverySlip__c();
        slip.Wh_Staff__c = userid;

        searchOppSetParam();
        getSqlWhereStr();
    }

    private void searchOppSetParam() {
        keywdSort = keyword;
    }

    public void searchOpp() {
        searchOppSetParam();

        if (!getIsNeedRunSearch()) {
            return;
        }

        // 選択済みの製品を取得
        myComponentController.getSelectedDataInfo();
        getSqlWhereStr();
        // コンポーネントにSoqlを発行して、ページングする
        myComponentController.searchAndPaging();
    }

    public void save() {
        Map<String, Integer> baofeiAssetMap = new Map<String, Integer>();
        Map<String, Integer> guoqiAssetMap = new Map<String, Integer>();
        Map<String, Integer> shangjiaAssetMap = new Map<String, Integer>();
        Map<String, String> whLocationAssetMap = new Map<String, String>();
        for (WrapperInfo wi : viewList) {
            Consum_Apply_Equipment_Set_Detail__c caesd = (Consum_Apply_Equipment_Set_Detail__c)wi.sobj;
            if (!wi.check || !wi.canEdit) {
                continue;
            }
            Integer baofei = caesd.Yi_Zhi_Bao_Fei_Jia__c != null ? Integer.valueOf(caesd.Yi_Zhi_Bao_Fei_Jia__c) : 0;
            Integer guoqi = caesd.Yi_Zhi_Guo_Qi_Jia__c != null ? Integer.valueOf(caesd.Yi_Zhi_Guo_Qi_Jia__c) : 0;
            Integer shangjia = caesd.Shang_Jia_Jia__c != null ? Integer.valueOf(caesd.Shang_Jia_Jia__c) : 0;
            if (caesd.Hui_Ji_Jia__c != baofei + guoqi + shangjia) {
                String guaranteen_end = '';
                if (caesd.Consumable_Guaranteen_end_F__c != null) {
                    guaranteen_end = caesd.Consumable_Guaranteen_end_F__c.format();                     
                }
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '处理件数与回寄件数必须相同['+caesd.Fixture_Model_No__c+']('+guaranteen_end+')'));
                return;
            }
            if (caesd.Consumable_Guaranteen_end_F__c != null && Date.today().daysBetween(caesd.Consumable_Guaranteen_end_F__c) <= 0 && shangjia > 0) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '此备品已过期，如实物已寄回需移至过期区['+caesd.Fixture_Model_No__c+']('+caesd.Consumable_Guaranteen_end_F__c.format()+')'));
                return;
            }
            //update by youc 2021-12-08 start 之前是直接取保有设备和输入的值的 现在可以设置保有设备+小码为key 后面get的时候相同
            // baofeiAssetMap.put(caesd.Asset__c, baofei);
            // guoqiAssetMap.put(caesd.Asset__c, guoqi);
            // shangjiaAssetMap.put(caesd.Asset__c, shangjia);
             //add by yc 20220217 处理老数据开的口 start
            if (String.isEmpty(caesd.EquipmentManagementCode__c)) {
                baofeiAssetMap.put(caesd.Asset__c+caesd.EquipmentManagementCode_OldData__c, baofei);
                guoqiAssetMap.put(caesd.Asset__c+caesd.EquipmentManagementCode_OldData__c, guoqi);
                shangjiaAssetMap.put(caesd.Asset__c+caesd.EquipmentManagementCode_OldData__c, shangjia);
            }else{
                //update by youc 2021-12-08 start 之前是直接取保有设备和输入的值的 现在可以设置保有设备+小码为key 耗材追溯--发货修改
                baofeiAssetMap.put(caesd.Asset__c+caesd.ManagementCode__c+caesd.EquipmentManagementCode__c, baofei);
                guoqiAssetMap.put(caesd.Asset__c+caesd.ManagementCode__c+caesd.EquipmentManagementCode__c, guoqi);
                shangjiaAssetMap.put(caesd.Asset__c+caesd.ManagementCode__c+caesd.EquipmentManagementCode__c, shangjia);

            }  
            //add by yc 20220217 处理老数据开的口 end
        }

        List<Consum_Apply_Equipment_Set_Detail__c> updList = new List<Consum_Apply_Equipment_Set_Detail__c>();
        String userid = Userinfo.getUserId();
        Datetime nowtime = Datetime.now();
        Set<Id> assetIdSet = new Set<Id>();
        for (Consum_Apply_Equipment_Set_Detail__c caesd : useCaesdList) {
            //待报废
            //update by youc 2021-12-08 
            //add by yc 20220217 处理老数据开的口 start
            String asscodeX = caesd.Asset__c + caesd.ManagementCode__c+caesd.EquipmentManagementCode__c;
            if (String.isEmpty(caesd.EquipmentManagementCode__c)) {
                asscodeX = caesd.Asset__c + caesd.EquipmentManagementCode_OldData__c;
            }  
            //add by yc 20220217 处理老数据开的口 end
            
            // if (baofeiAssetMap.containsKey(caesd.Asset__c) && baofeiAssetMap.get(caesd.Asset__c) > 0) {
            if (baofeiAssetMap.containsKey(asscodeX) && baofeiAssetMap.get(asscodeX) > 0) {
                // Integer cnt_last = baofeiAssetMap.get(caesd.Asset__c) - 1;
                Integer cnt_last = baofeiAssetMap.get(asscodeX) - 1;
                caesd.Arrival_in_wh__c = true;
                caesd.Return_wh_chenk_staff__c = userid;
                caesd.Arrival_wh_time__c = nowtime;
                caesd.Inspection_result_after__c = 'NG';
                caesd.Inspection_result_after_NG__c = '废弃'; 
                // baofeiAssetMap.put(caesd.Asset__c, cnt_last);
                baofeiAssetMap.put(asscodeX, cnt_last);
                updList.add(caesd);
            //过期区
            // } else if (guoqiAssetMap.containsKey(caesd.Asset__c) && guoqiAssetMap.get(caesd.Asset__c) > 0) {
            } else if (guoqiAssetMap.containsKey(asscodeX) && guoqiAssetMap.get(asscodeX) > 0) {
                // Integer cnt_last = guoqiAssetMap.get(caesd.Asset__c) - 1;
                Integer cnt_last = guoqiAssetMap.get(asscodeX) - 1;
                caesd.Arrival_in_wh__c = true;
                caesd.Return_wh_chenk_staff__c = userid;
                caesd.Arrival_wh_time__c = nowtime;
                caesd.ExpiredArrival__c = true;
                // guoqiAssetMap.put(caesd.Asset__c, cnt_last);  
                guoqiAssetMap.put(asscodeX, cnt_last);  
                updList.add(caesd);
            //上架
            // } else if (shangjiaAssetMap.containsKey(caesd.Asset__c) && shangjiaAssetMap.get(caesd.Asset__c) > 0) {
            } else if (shangjiaAssetMap.containsKey(asscodeX) && shangjiaAssetMap.get(asscodeX) > 0) {
                // Integer cnt_last = shangjiaAssetMap.get(caesd.Asset__c) - 1;
                Integer cnt_last = shangjiaAssetMap.get(asscodeX) - 1;
                caesd.Arrival_in_wh__c = true;
                caesd.Return_wh_chenk_staff__c = userid;
                caesd.Arrival_wh_time__c = nowtime;
                // shangjiaAssetMap.put(caesd.Asset__c, cnt_last);
                shangjiaAssetMap.put(asscodeX, cnt_last);
                updList.add(caesd);
            }
            assetIdSet.add(caesd.Asset__c);
        }

        Savepoint sp = Database.setSavepoint();
        try {
            List<Asset> assetList = [
                SELECT Id
                  FROM Asset
                 WHERE Id IN:assetIdSet
                 FOR UPDATE
            ];
            FixtureUtil.withoutUpdate(updList);
            searchOpp();
            done_flg = true;
        } catch (Exception ex) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage()));
            Database.rollback(sp);
            done_flg = false;
        }
    }

    public void cancel() {
        keyword = null;
        keywordDate = null;
        cancelAction = true;
        searchOpp();
    }

    private String makeSoql() {
        // 検索条件

        // from asset
        String soql = keepWher;
        if (String.isNotBlank(keywordDate)) {
            soql += ' AND Consumable_Guaranteen_end_F__c = ' + String.escapeSingleQuotes(keywordDate.replaceAll('/', '-'));
        }
        if (String.isNotBlank(keyword)) {
            soql += ' AND Fixture_Model_No__c like \'%' + String.escapeSingleQuotes(keyword) + '%\'';
        }
        return soql;
    }

    public override void setViewList(List<Sobject> queryList) {
        viewList = new List<WrapperInfo>();
        if (queryList.size() > 0) {
            List<Consum_Apply_Equipment_Set_Detail__c> tmpList = (List<Consum_Apply_Equipment_Set_Detail__c>)queryList;
            Map<Id, Consum_Apply_Equipment_Set_Detail__c> smap = new Map<Id, Consum_Apply_Equipment_Set_Detail__c>((List<Consum_Apply_Equipment_Set_Detail__c>)selectedData);
            useCaesdList = new List<Consum_Apply_Equipment_Set_Detail__c>();
            for (Consum_Apply_Equipment_Set_Detail__c caeid : tmpList) {
                useCaesdList.add(smap.get(caeid.Id));
            }
        }
        else {
            useCaesdList = (List<Consum_Apply_Equipment_Set_Detail__c>)selectedData;
        }
        system.debug(useCaesdList+'zheli0'+queryList);
        Map<Id, List<Consum_Apply_Equipment_Set_Detail__c>> caesdMap = new Map<Id, List<Consum_Apply_Equipment_Set_Detail__c>>();
        Map<Id, Integer> cntMap_HuiJi = new Map<Id, Integer>();
        whlocMap = new Map<Id, String>();
        //Map<Id, Integer> cntShipmentReqMap = new Map<Id, Integer>();
        //add by youc 2021-12-07 start
        Map<Id,List<String>> assXiaoMaMap = new Map<Id,List<String>>(); 
        //add by youc 2021-12-07 end
        for (Consum_Apply_Equipment_Set_Detail__c caesd : useCaesdList) {
            if (caesdMap.containsKey(caesd.Asset__c) == false) {
                caesdMap.put(caesd.Asset__c, new List<Consum_Apply_Equipment_Set_Detail__c>());
            }
            caesdMap.get(caesd.Asset__c).add(caesd);

            if (caesd.Return_DeliverySlip__c != null) {
                Integer cnt = cntMap_HuiJi.containsKey(caesd.Asset__c) ? (cntMap_HuiJi.get(caesd.Asset__c) + 1) : 1;
                cntMap_HuiJi.put(caesd.Asset__c, cnt);
            }
            //add by youc 2021-12-07 start 存放小码
            if (caesd.EquipmentManagementCode__c != null && caesd.EquipmentManagementCode__c != '') {
                if (assXiaoMaMap.containsKey(caesd.Asset__c) == false) {
                    assXiaoMaMap.put(caesd.Asset__c, new List<String>());
                }
                assXiaoMaMap.get(caesd.Asset__c).add(caesd.ManagementCode__c+caesd.EquipmentManagementCode__c);
            }
            //add by youc 2021-12-07 end 存放小码
            whlocMap.put(caesd.Asset__c, caesd.Asset__r.WH_location__c);
        }
        for (Id assId : caesdMap.keySet()) {
            //update by youc 2021-12-07 start 之前是根据保有设备展示到页面上的 现在需要展示出明细 

            /*Consum_Apply_Equipment_Set_Detail__c wiInfo = caesdMap.get(assId)[0];
            if (cntMap_HuiJi.containsKey(wiInfo.Asset__c)) {
                wiInfo.Hui_Ji_Jia__c = cntMap_HuiJi.get(wiInfo.Asset__c);
            }
            wiInfo.WH_location__c = whlocMap.get(wiInfo.Asset__c); 
            WrapperInfo wi = new WrapperInfo(wiInfo, myComponentController);
            wi.additionalInfoMap.put('Product_Serial_No_F__c', wiInfo.Product_Serial_No_F__c);

            if (wiInfo.Hui_Ji_Jia__c == null || wiInfo.Yi_Zhi_Bao_Fei_Jia__c != null || wiInfo.Yi_Zhi_Guo_Qi_Jia__c != null || wiInfo.Shang_Jia_Jia__c != null) {
                wi.canEdit = false;
            } 
            viewList.add(wi);
            注释 之前是取的第一个明细 设置回寄件数并展示 现在可以直接取得该保有设备对应的明细 判断回寄单是否为空即可 */
            List<Consum_Apply_Equipment_Set_Detail__c> conTempList = caesdMap.get(assId);
            for (Integer i = 0; i < conTempList.size();i ++   ) {
                if (i == 0) {
                    //因为page页面是根据barcode去判断是否存在复数件的 所以我们在后端 同一个保有设备下只设置一个barcode即可 barcode是公式字段 可以建个文本字段来 这样在前端做会简单很多
                    conTempList[i].barcodeforReceipt__c = conTempList[i].Barcode_F__c;
                }
                if (cntMap_HuiJi.containsKey(conTempList[i].Asset__c)) {
                    conTempList[i].Hui_Ji_Jia__c = 1;
                }
                //货架号是取得保有设备的货架号 
                conTempList[i].WH_location__c = whlocMap.get(conTempList[i].Asset__c); 
                WrapperInfo wi = new WrapperInfo(conTempList[i], myComponentController);
                if (i == 0) {
                    wi.additionalInfoMap.put('Product_Serial_No_F__c', conTempList[i].Product_Serial_No_F__c);
                    //产品+机身编码同理
                }else {                
                    wi.additionalInfoMap.put('Product_Serial_No_F__c', '');
                }
                if (assXiaoMaMap.containsKey(conTempList[i].Asset__c)) {
                    String allXiaoma = String.join(assXiaoMaMap.get(conTempList[i].Asset__c), ',');
                    wi.additionalInfoMap.put('Comment__c',allXiaoma);
                }else {
                    wi.additionalInfoMap.put('Comment__c','');
                }
                if (conTempList[i].Hui_Ji_Jia__c == null || conTempList[i].Yi_Zhi_Bao_Fei_Jia__c != null || conTempList[i].Yi_Zhi_Guo_Qi_Jia__c != null || conTempList[i].Shang_Jia_Jia__c != null) {
                    wi.canEdit = false;
                }
                viewList.add(wi);
            }
            //update by youc 2021-12-07 end 之前是根据保有设备展示到页面上的 现在需要展示出明细 

        }

        if (cancelAction) {
            changeMessage = '取消';
            cancelAction = false;
        } else {
            changeMessage = ''+viewList.size();
        }
    }

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