/**
 * 备品配套选择
 */
public with sharing class ReceivingNoteSummarySelectController 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 ReceivingNoteSummary__c';
        selectedDataSql += ' where Id != null';
        selectedDataSql += ' AND Fixture_Set__c != null AND (';
        Boolean isf = true;
        for (ReceivingNoteSummary__c rns : selectedRnsList) {
            if (isf == false) {
                selectedDataSql += ' OR ';
            }
            selectedDataSql += ' Id = \'' + rns.Id + '\' ';
            isf = false;
        }
        selectedDataSql += ') order by Name';
        return selectedDataSql;
    }

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

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

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

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

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

        if(getIsNeedRunSearch()){
            sqlWhereStr = this.makeSoql(keywdSort);
        }
        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; }
    private Boolean isFirst = true;
    public boolean firstTimeCheck { get; set;} 

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

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

        // OLY_OCM-404 分配代替品，跳转页面显示原选中一览信息
        if (!String.isBlank(this.inRaesId)) {
            List<String> idList = inRaesId.split(',');
            this.selectedRnsList = [
                    select Id
                         , Name
                         , Fixture_Set__c
                         , ReceivingNote__c
                         , Fixture_Model_No__c
                         , Fixture_Model_No_F__c
                         , Fixture_Set__r.Name
                         , Fixture_Set__r.Loaner_name__c
                         , Wei_DataConfirmation_Cnt__c
                         , ReceivingNoteDetail_Cnt__c
                    from ReceivingNoteSummary__c
                    where Id = :idList];
            if (selectedRnsList.size() == 0) {
                throw new ControllerUtil.myException('沒有指定收货一览或者数据不正确。');
            }
            // 如果分两次选择备品配套的话是不能一起进到这个画面的所以取下表0
            firstTimeCheck = String.isBlank(selectedRnsList[0].Fixture_Set__c);
        }
    }

    public void init() {
        isNeedSearchFirst = true;
        isNeedCheckEvent = false;
        if (selectedRnsList == null) {
            System.debug('init 沒有指定收货一览或者数据不正确。');
            return;
        }
        keyword = selectedRnsList[0].Fixture_Model_No_F__c;
        searchOppSetParam();
        getSqlWhereStr();

    }

    private void searchOppSetParam() {
        keywdSort = keyword;
    }

    public PageReference searchOpp() {
        searchOppSetParam();

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

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

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

        for (WrapperInfo wi:viewList){
            ReceivingNoteSummary__c rns = (ReceivingNoteSummary__c) wi.sobj;
            if(rns.Fixture_Set__r.Name == keyword ){
                wi.check = true;
                isFirst = false;
                //return save();
            }
        }

        isFirst = false;
        return null;
    }

    public void sendEmail() {
        Savepoint sp = Database.setSavepoint();
        try{
            String emailBody = System.currentPageReference().getParameters().get('emailBody');
            String templateBody = '【自由填写内容】\n{0}\n';
                   templateBody += '备品配套：\n';
            emailBody = String.format(templateBody, new List<String> {emailBody});
            String emailMsg = '';
            for (ReceivingNoteSummary__c rns : selectedRnsList) {
                rns.No_Matching_Reminder_Email_Text__c = null;
                // 选择配套时，多个一览的型号一定是相同的，只需要发一次型号提醒邮件
                break;
            }
            update selectedRnsList;
            for (ReceivingNoteSummary__c rns : selectedRnsList) {
                rns.No_Matching_Reminder_Email_Text__c = emailBody + rns.Fixture_Set__r.Name;
                break;
            }
            update selectedRnsList;
            ApexPages.Message vfApplyMsg = new ApexPages.Message(ApexPages.severity.INFO, '已发送');
            ApexPages.addMessage(vfApplyMsg);
        }
        catch (Exception e) {
            Database.rollback(sp);
            ApexPages.addMessages(e);
        }
    }
    // 清空一览的配套，明细的清空在trigger里做
    public PageReference cleanFixtureSet(){
        List<ReceivingNoteSummary__c> updateRNSList = new List<ReceivingNoteSummary__c>();
        for(ReceivingNoteSummary__c rns:this.selectedRnsList) {
            if(rns.Wei_DataConfirmation_Cnt__c != rns.ReceivingNoteDetail_Cnt__c) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '【' + rns.Name + '】数据确认后不可修改配套，请取消数据确认后重试'));
                return null;
            }
            else {
                rns.Fixture_Set__c = null;
                updateRNSList.add(rns);
            }
        }
        if(updateRNSList.size()>0) {
            FixtureUtil.withoutUpdate(selectedRnsList);
            PageReference pg = new PageReference('/apex/ReceivingNoteSummarySelect?pt_recid=' + parentId + '&raesid=' + inRaesId);
            pg.setRedirect(true);
            pg.getParameters().put('direct', 'false');
            return pg;
        }
        return null;
    }

    public PageReference save() {

        // //20170906 upsert by UniqueKey__c
        // List<ReceivingNoteSummary__c> mfUpsert = new List<ReceivingNoteSummary__c>();
        String chkIdsStr = '';
        Savepoint sp = Database.setSavepoint();
        // Set<String> clearUniqueKeySet = new Set<String>();

        try {
            List<ReceivingNote__c> raUpdate = [
                    select Id
                      from ReceivingNote__c where Id = :parentId for Update];
            if (raUpdate.isEmpty()) {
                throw new ControllerUtil.myException('没有找到收货清单。');
            }
            Id fsId = null;
            for (WrapperInfo wprInfo : viewList) {
                if (wprInfo.check) {
                    fsId = ((ReceivingNoteSummary__c) wprInfo.sobj).Fixture_Set__c;
                    break;
                }
            }
            List<String> chkIdList = new List<String>();
            for (ReceivingNoteSummary__c rns : selectedRnsList) {
                rns.Fixture_Set__c = fsId;
                chkIdList.add(rns.Id);
            }

            FixtureUtil.withoutUpsertObjects(selectedRnsList);

            chkIdsStr = String.join(chkIdList, ',');
        } catch (Exception ex) {
            System.debug(ex.getStackTraceString());
            ApexPages.addMessages(ex);
            Database.rollback(sp);
            return null;
        }

        PageReference pg = new PageReference('/apex/ReceivingNoteDetailSelect');
            // 分配代替品跳转到配套明细选择画面,暂时无用
            if (String.isNotBlank(this.inRaesId)) {
                pg.getParameters().put('raesid', this.inRaesId);
            }
            pg.getParameters().put('sids', chkIdsStr);
            pg.setRedirect(true);
            return pg;
    }

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

    private String makeSoql(String keyword) {

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

        if (!String.isBlank(keyword)) {
            String[] vals = keyword.split(' ');
            soql += ' and (';
            String fmodelno = '';
            for (String v : vals) {
                fmodelno += ' Name like \'%' + String.escapeSingleQuotes(v.replaceAll('%', '\\%')) + '%\' or ';
                fmodelno += ' Loaner_name__c like \'%' + String.escapeSingleQuotes(v.replaceAll('%', '\\%')) + '%\' or';
            }
            fmodelno = fmodelno.removeEnd('or');
            soql += fmodelno + ' )';
            // for (String v : vals) {
            //     soql += ' and Name like \'%' + String.escapeSingleQuotes(v.replaceAll('%', '\\%')) + '%\'';
            // }
        }
        return soql;
    }

    public override void setViewList(List<sObject> queryList) {
        viewList = new List<WrapperInfo>();

        if (selectedData.size() > 0) {

            selectedGroupData = new List<ReceivingNoteSummary__c>();
            Map<String, ReceivingNoteSummary__c> sltFixtureMap = new Map<String, ReceivingNoteSummary__c>();
            Map<String, ReceivingNoteSummary__c> subsFixtureMap = new Map<String, ReceivingNoteSummary__c>();   // 用于存代替分配的一览
            Map<String, Integer> sltFixtureCnt = new Map<String, Integer>();
            // 20170906 グループリスト取得
            // order by Fixture_Set__c, Fixture_Set__r.Loaner_code__c, IndexFromUniqueKey__c
            for (SObject sobj : selectedData) {
                ReceivingNoteSummary__c rns = (ReceivingNoteSummary__c) sobj;

                if (!sltFixtureMap.containsKey(rns.Fixture_Set__c)) {
                    selectedGroupData.add(rns);
                    sltFixtureMap.put(rns.Fixture_Set__c, rns);
                    sltFixtureCnt.put(rns.Fixture_Set__c, 0);
                }
                ReceivingNoteSummary__c nobj = sltFixtureMap.get(rns.Fixture_Set__c);
                Integer nCnt = sltFixtureCnt.get(rns.Fixture_Set__c);

                nCnt++;

                sltFixtureCnt.put(rns.Fixture_Set__c, nCnt);

                viewList.add(new WrapperInfo(rns, myComponentController));
                viewList[viewList.size() - 1].lineNo = viewList.size() - 1;
                viewList[viewList.size() - 1].check = true;
                viewList[viewList.size() - 1].oldCheck = true;
                break;
            }

        }

        if (queryList.size() == 0) {
            return;
        }

        Savepoint sp = Database.setSavepoint();

        // 数式項目値を取れるのために、一回Insertする
        List<ReceivingNoteSummary__c> tempList = new List<ReceivingNoteSummary__c>();
        for (Integer i = 0; i < queryList.size(); i++) {
            // 501を超えた場合前500のみを出す
            if (i == getSearchNumMax()) { break; }
            ReceivingNoteSummary__c mf = new ReceivingNoteSummary__c();
            mf.ReceivingNote__c               = parentId;
            mf.Fixture_Set__c                = queryList[i].Id;
            mf.ReceivingNote__c = selectedRnsList[0].ReceivingNote__c;
            // mf.DataMigration_Flag__c         = true;

            tempList.add(mf);
        }

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

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

        tempList = Database.query(soql);
        if (queryList.size() != tempList.size()) {
            //error message 検索処理正しくありません、システム管理者に連絡してください。
            for (Integer i = 0; i < results.size(); i ++) {
                Database.SaveResult dmlResult = results[i];
                if (!dmlResult.isSuccess()) {
                    System.debug(System.LoggingLevel.ERROR, '第[' + (i + 1) + ']条 insert error:' + dmlResult);
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,
                    '第[' + (i + 1) + ']条 insert error:' + dmlResult));
                    // 1件目だけlogに出す
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,
                        System.Label.CreateRelationListSearchError));
                    Database.rollback(sp);
                    return;
                }
            }
        }
        // 強制ロールバック
        Database.rollback(sp);
        Map<String, SObject> fsDMap = new Map<String,SObject>();
        for(ReceivingNoteSummary__c fsd : tempList){
            ReceivingNoteSummary__c robj = fsd.clone(false);
            // 根据OLY_OCM-404的需求设置默认数量为1
            // robj.Rental_Num__c = 1;
            // robj.VF_Rental_Num__c = 1;
            // robj.DataMigration_Flag__c = false;
            fsDMap.put(fsd.Fixture_Set__c, robj);
        }

        Integer addedNum = 0;
        Boolean hasChecked = viewList.size() > 0;
        for (Integer i = 0; i < queryList.size(); i++) {

// TODO where not in selectedFKIdList
            //if (selectedIds.contains(queryList[i].Id)) {
            //    // 跳过已经选择的备品set明细
            //    continue;
            //}
            addedNum ++;
            // 501を超えた場合前500のみを出す
            if (addedNum == getSearchNumMax()) { break; }
            ReceivingNoteSummary__c mf = (ReceivingNoteSummary__c) fsDMap.get(queryList[i].Id);
            // Fixture_Set__c mf = (Fixture_Set__c) queryList[i];
            viewList.add(new WrapperInfo(mf, myComponentController));
            viewList[viewList.size() - 1].lineNo = viewList.size() - 1;
            // 如果检索出型号完全相同的配套，且清单一览没有连备品配套，则默认勾上
            if(mf.Fixture_Set__r.Name == keyword && !hasChecked){
                viewList[viewList.size() - 1].check = true;
                hasChecked = true;
            }
            // viewList[viewList.size() - 1].additionalInfoMap.put('Substitute_Select_Again__c', String.valueOf(mf.Substitute_Select_Again__c));
            // viewList[viewList.size() - 1].additionalInfoMap.put('Same_Accessory_flag__c',     String.valueOf(mf.Same_Accessory_flag__c));
        }

    }
}