//非集中管理备品确认画面
public without sharing class NotReceivingNoteListFirstController  extends CreateRelationListPagingCtrlBase {
    public override Integer getSearchNumMax() {
        //各ページに制御あれば、最大件数を指定する
        // searchNumMax = Integer.valueOf(Label.Product_Select_Limit);
        // searchNumMax = 20;
        pagesize = '20';
        return searchNumMax;
    }

    /* 選択されたデータ取得用Soql　Fromから*/
    public override String getSelectedDataSql() {
        // オブジェクトAPI名
        selectedDataSql = ' From ReceivingNote__c';
        selectedDataSql += ' where id = null ';
        selectedDataSql += ' order by Id';
        if (myComponentController.columnLeftRW != null) {
            for (String key : myComponentController.columnLeftRW.keySet()) {
                myComponentController.columnLeftRW.put(key, 'r');
            }
        }
        return selectedDataSql;
    }

    public override String getOriginObjName() {
        // オブジェクトAPI名
        originObjName = 'ReceivingNote__c';
        return originObjName;
    }
    public override String getOriginObjColumns() {
        // 項目セット
        originObjColumns = 'Id , ContactPerson__c, RN_Status__c , Internal_asset_location__c , Sales_order_number__c , OrderCode__c , ApprovalNumber__c , Asset_loaner_category__c , DateOfDelivery__c , ReceivingNoteSummary_Cnt__c, Data_Confirmation_Link__c, ReceivingNoteNo_New__c,ReceivingNotePDF_LINK__c,NotReceivingNoteListFirst_Link__c ';
        return originObjColumns;
    }

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

    public override List<String> getColumnFieldList() {
        // strColumus 里加 field
        // FixtureUtil#raesdGroupByAssetId()の項目も必要
        return new List<String>{'Id'};
    }

    public override String getFKColumnField() {
        // getObjName 连 getOriginObjName 的 FK
        return '';
    }

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

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

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

        return sqlWhereStr;

    }

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

    public override Boolean getIsNeedRunSearch() {
        return true;
    }

    public ReceivingNote__c rn { get; set; }     //别存放地

    public String orderCode { get; set; }         //订单编码
    public String salesOrderNumber {get;set;}      // 合同编码
    public String approvalNumber { get; set; }         //采购申请裁决号
    //wangweipeng 20210616   新增 联系人 查询条件
    public String contactPerson { get; set; }         //联系人
    public String asset_loaner_category { get; set; }         //备品类别
    public String dateOfDelivery { get; set; }         //发货日
    public String status { get; set; }         //收货状态
    // public String beiShangGuang {get; set;} // 北上广备品中心
    public String beiPinCunfangDi {get; set;} 	//备品存放地

    public NotReceivingNoteListFirstController() {
        parentId = '00000';
        status = '待数据确认';
    }

    public void init() {
        rn = new ReceivingNote__c();
        isNeedSearchFirst = true;
        isNeedCheckEvent = true;
        getSqlWhereStr();
    }

    public PageReference searchOpp() {

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

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

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

    public override void setViewList(List<sObject> queryList) {
        viewList = new List<WrapperInfo>();
        for (Integer i = 0; i < queryList.size(); i++) {
            // 501を超えた場合前500のみを出す
            if (i == getSearchNumMax()) { break; }
            ReceivingNote__c mf = (ReceivingNote__c)queryList[i];
            viewList.add(new WrapperInfo(mf, myComponentController));
            viewList[viewList.size() - 1].lineNo = viewList.size() - 1;
        }
    }
    // 备品类别
    public List<SelectOption> getAsset_loaner_categoryOps() {
        List<SelectOption> opList = new List<SelectOption>();
        opList.add(new SelectOption('固定资产', '固定资产'));
        return opList;
    }

    public List<SelectOption> getRNStatusOpss() {
        List<FixtureUtil.RNStatus> rnsList = new List<FixtureUtil.RNStatus>();
        rnsList.add(FixtureUtil.RNStatus.Dai_Shu_Ju_Que_Ren);
        rnsList.add(FixtureUtil.RNStatus.Yi_Shu_Ju_Que_Ren);
        List<SelectOption> opList = new List<SelectOption>();
        opList.add(new SelectOption('', '--全部--'));
        for (FixtureUtil.RNStatus sNum : rnsList) {
            String value = FixtureUtil.RNStatusMap.get(sNum.ordinal());
            opList.add(new SelectOption(value, value));
        }
        return opList;
    }
    private String makeSoql() {
        String soql = ' Where Id != null';
        //拼接固定条件 --备品存放地不为北上广备品中心 并且 备品类别 = 固定资产
        soql += ' AND Internal_asset_location__c !=\'北京 备品中心\' AND Internal_asset_location__c != \'上海 备品中心\' AND Internal_asset_location__c != \'广州 备品中心\' AND Asset_loaner_category__c = \'固定资产\' ';

        if(String.isNotBlank(beiPinCunfangDi) ) {
        	soql += ' AND Internal_asset_location__c LIKE \'%' + String.escapeSingleQuotes(beiPinCunfangDi) + '%\'';
        }

        if (String.isNotBlank(orderCode)) {
            soql += ' AND OrderCode__c LIKE \'%' + String.escapeSingleQuotes(orderCode) + '%\'';
        }

        if (String.isNotBlank(salesOrderNumber)) {
            soql += ' AND Sales_order_number__c LIKE \'%' + String.escapeSingleQuotes(salesOrderNumber) + '%\'';
        }

        if (String.isNotBlank(approvalNumber)) {
            soql += ' AND ApprovalNumber__c LIKE \'%' + String.escapeSingleQuotes(approvalNumber) + '%\'';
        }
        if(String.isNotBlank(contactPerson)){
            soql += ' AND ContactPerson__c LIKE \'%' + String.escapeSingleQuotes(contactPerson) + '%\'';
        }
        if (String.isNotBlank(dateOfDelivery)) {
            String dateStr = dateOfDelivery.replace('/', '-');
            soql += ' AND DateOfDelivery__c = ' + String.escapeSingleQuotes(dateStr);
        }
        if (String.isNotBlank(status)) {
            soql += ' AND RN_Status__c = \'' + String.escapeSingleQuotes(status) + '\'';
        }
        soql += ' AND DateOfDelivery__c >= '+ System.Label.DateNotReceivingNote;
        // soql += ' AND DateOfDelivery__c >= 2021-07-01';
        System.debug('zheli:'+soql);
        return soql;
    }
    public PageReference save() {
        Savepoint sp = Database.setSavepoint();
        try{
            // 获取打勾清单
            Map<Id,Integer> rnRndMap = new Map<Id, Integer>();
            for (WrapperInfo info:viewList){
                if(info.check){
                    ReceivingNote__c rn = (ReceivingNote__c)info.sobj;
                    if(String.isNotBlank(rn.RN_Status__c) && rn.RN_Status__c == '已数据确认') {
                        throw new ControllerUtil.myException('【' + rn.ReceivingNoteNo_New__c + '】已全部数据确认，无需再操作');
                    }
                    rnRndMap.put(info.sobj.Id, 0);
                }
            }
            Account ocm = [select Id from Account where AgentCode_Ext__c =:System.Label.Account_Asset_FJZ];//20210623 ljh add
            // 获取明细 //获取一览
            List<ReceivingNoteDetail__c> rndList = [
                    SELECT DataConfirmationAgain__c
                         , Inspection_result_after__c
                         , Arrival_wh_Request_time__c
                         , ReceivingNote__r.ReceivingNoteNo__c
                         , ReceivingNote__r.Name
                         , SerialNumber__c 
                         , RNDAssert__c
                         , ReceivingNoteSummary__c 
                         , Arrival_in_wh__c
                         , DataConfirmation__c
                      FROM ReceivingNoteDetail__c
                     WHERE Delete_Flag__c = false  
                       AND ReceivingNote__c IN :rnRndMap.keySet()
            ];
            //20210623 ljh add start
            List<ReceivingNoteDetail__c> stockInRequestAvailableRndList = new List<ReceivingNoteDetail__c>(); // 可做入库指示的明细列表
            Id lastRnId = null;
            Boolean hasStockInAvailable = false;
            Boolean hasStockInUnavailable = false;
            ReceivingNoteDetail__c lastRnd;
            Map<Id,Asset> assMap = new Map<Id,Asset>();
            
            Datetime now = System.Now();
            String userId = Userinfo.getUserId();
            for(ReceivingNoteDetail__c rnd:rndList){
                if (String.isBlank(lastRnId)){
                    lastRnId = rnd.ReceivingNote__c;
                }
                else if (lastRnId != rnd.ReceivingNote__c){
                    if(hasStockInAvailable == false){
                        Apexpages.addMessage(new ApexPages.message(Apexpages.Severity.ERROR,  lastRnd.ReceivingNote__r.Name + '无法数据确认'));
                        return null;
                    }
                    else if (hasStockInUnavailable){
                        Apexpages.addMessage(new ApexPages.message(Apexpages.Severity.INFO, lastRnd.ReceivingNote__r.Name + '部分数据确认'));
                    }
                    lastRnId = rnd.ReceivingNote__c;
                    hasStockInAvailable = false;
                    hasStockInUnavailable = false;
                }
                if(!rnd.DataConfirmation__c){
                    rnd.DataConfirmation__c = true;
                    rnd.DataConfirmationTime__c = now;
                    rnd.DataConfirmationStaff__c = userId;
                    hasStockInAvailable = true;
                    stockInRequestAvailableRndList.add(rnd);
                    //保有设备map
                    Asset ass = new Asset();
                    ass.Id = rnd.RNDAssert__c;
                    if (String.isNotBlank(rnd.SerialNumber__c)) {
                        ass.SerialNumber = rnd.SerialNumber__c;
                        ass.SerialNumber_Origin__c = rnd.SerialNumber_Origin__c;
                    }
                    ass.AccountId = ocm.Id;
                    ass.AssetManageConfirm__c = false;
                    assMap.put(rnd.RNDAssert__c,ass);
                }
                else{
                    hasStockInUnavailable = true;
                }
                lastRnd = rnd;
            }

            if (String.isNotBlank(lastRnId)) {
                if(hasStockInAvailable == false){
                    Apexpages.addMessage(new ApexPages.message(Apexpages.Severity.ERROR,  '【' + lastRnd.ReceivingNote__r.Name + '】已全部数据确认，无需再操作'));
                    return null;
                }
                else if (hasStockInUnavailable){
                    Apexpages.addMessage(new ApexPages.message(Apexpages.Severity.INFO, lastRnd.ReceivingNote__r.Name + '部分数据确认'));
                }
            }
            // 写入数据库
            if (stockInRequestAvailableRndList.size()>0){
                update stockInRequestAvailableRndList;
                update assMap.values();
                Apexpages.addMessage(new ApexPages.message(Apexpages.Severity.INFO, '保存成功'));
                PageReference pageRef = ApexPages.CurrentPage();
                return pageRef; 
            }
            //20210623 ljh add end
        }
        catch (Exception e) {
            Database.rollback(sp);
            ApexPages.addMessages(e);
            return null;
        }
        return null;
    }
}