public without sharing class NotReceivingNoteWaitingReceiptController {

    public static final String NONE = system.label.StartTrading_None;
    private List<String> assetFieldApiList;
    private List<String> receivingNoteFieldApiList;

    public List<LabelValue> outputFieldList {get; set;}
    public List<LabelValue> inputFieldList {get; set;}

    public String parId {get; set;}
    public PageBean pageB {get; set;}
    public Boolean showSelectRnsButton{get;set;}
    public String showCount {get;set;}
    public Integer nowPage {get;set;}
    public Integer maxPage {get;set;}
    public Boolean canBefore {get;set;}
    public Boolean canNext {get;set;}
    public Boolean done_flg {get;set;}

    public NotReceivingNoteWaitingReceiptController() {
        parId = System.currentPageReference().getParameters().get('parId');
        nowPage = 1;
        done_flg = false;
    }

    public void init() {
        try {
            Set<String> assetFieldApiSet = new Set<String>();
            Set<String> receivingNoteFieldApiSet = new Set<String>();
            // outputFieldList = setFIeldSet('ReceivingNoteDetail__c', 'ReceivingNoteWaitingReceipt_L', receivingNoteFieldApiSet);
            inputFieldList = setFIeldSet('ReceivingNoteDetail__c', 'NotReceivingNoteWaitingReceipt', receivingNoteFieldApiSet);
            addField(receivingNoteFieldApiSet, assetFieldApiSet);
            assetFieldApiList = new List<String>();
            receivingNoteFieldApiList = new List<String>();
            assetFieldApiList.addAll(assetFieldApiSet);
            receivingNoteFieldApiList.addAll(receivingNoteFieldApiSet);
            receivingNoteFieldApiList.add('Received_Confirm_Time_F__c');
            if (String.isBlank(parId)) {
                throw new ControllerUtil.myException('请传入正确的参数');
            }
            List<ReceivingNote__c> rnList = [SELECT Id
                        , Internal_asset_location__c
                        , Sales_order_number__c
                        , OrderCode__c
                        , ApprovalNumber__c
                        , DateOfDelivery__c
                        , ReceivingNoteNo_New__c
                        , Status__c
                        , Asset_loaner_category__c
                        , RN_Status__c
                        , QRId__c
                        , ManagementCenter__c
                     FROM ReceivingNote__c
                    WHERE Id = :parId];
            if (rnList.size() == 0) {
                throw new ControllerUtil.myException('收货清单Id不存在');
            }
            // else{
            //     if((String.isNotBlank(rnList[0].Asset_loaner_category__c) &&rnList[0].Asset_loaner_category__c != '固定资产')
            //         ||(String.isNotBlank(rnList[0].ManagementCenter__c) && rnList[0].ManagementCenter__c != 'ZZ')
            //         ){
            //         throw new ControllerUtil.myException('非法进入非集中管理数据确认页面！');
            //     }
            // }
            pageB = new PageBean(rnList[0], assetFieldApiList, receivingNoteFieldApiList);
            if (rnList[0].Asset_loaner_category__c == '耗材'){
                showSelectRnsButton = false;
            }
            else{
                showSelectRnsButton = true;
            }
            pageB.rn.Asset_loaner_category__c = null;
            getShowCountOps();
            changePage();
            String message = ApexPages.currentPage().getParameters().get('message');
            if(String.isNotBlank(message)){
                ApexPages.Message vfApplyMsg = new ApexPages.Message(ApexPages.severity.INFO, message);
                ApexPages.addMessage(vfApplyMsg);
            }
        }
        catch (Exception e) {
            ApexPages.addMessages(e);
        }
    }

    public List<SelectOption> getShowCountOps() {
        String countStr = '10,15,20:10';
        List<String> countStrList = countStr.split(':');
        if (String.isBlank(showCount)) {
            showCount = countStrList[1];
        }
        List<SelectOption> opList = new List<SelectOption>();
        for (String str : countStrList[0].split(',')) {
            Integer iStr = Integer.valueOf(str);
            opList.add(new SelectOption(str, str));
        }
        return opList;
    }

    public void nextPage() {
        if (nowPage < maxPage) {
            nowPage ++;
            changePage();
        }
    }

    public void beforePage() {
        if (nowPage > 0) {
            nowPage --;
            changePage();
        }
    }

    public void changePage() {
        maxPage = Integer.valueOf((pageB.rowBList.size() / Integer.valueOf(showCount)));
        maxPage = maxPage+1;
        Integer showC = Integer.valueOf(showCount);
        Integer i = (nowPage - 1) * showC;
        Integer k = (pageB.rowBList.size() - i) > showC ? showC : (pageB.rowBList.size() - i);
        pageB.showBList = new List<RowBean>();
        System.debug(k);
        for (Integer j = i; j < i + k; j ++) {
            pageB.showBList.add(pageB.rowBList[j]);
        }
        pageB.currentPageRecordCnt = pageB.showBList.size();
        canNext = nowPage < maxPage;
        canBefore = nowPage > 1;
    }
    public List<SelectOption> getStatusOps() {
        List<FixtureUtil.RNDStatus> rndList = new List<FixtureUtil.RNDStatus>();
        rndList.add(FixtureUtil.RNDStatus.Dai_Shu_Ju_Que_Ren);
        rndList.add(FixtureUtil.RNDStatus.Yi_Shu_Ju_Que_Ren);
        List<SelectOption> opList = new List<SelectOption>();
        opList.add(new SelectOption('', '--无--'));
        for (FixtureUtil.RNDStatus sNum : rndList) {
            String value = FixtureUtil.RNDStatusMap.get(sNum.ordinal());
            opList.add(new SelectOption(value, value));
        }
        return opList;
    }
    public void search() {
        System.debug(assetFieldApiList);
        String wher = '';
        if (String.isNotBlank(pageB.status)) {
            wher += ' AND RND_Status__c = \'' + String.escapeSingleQuotes(pageB.status) + '\'';
        }
        if (String.isNotBlank(pageB.fixture_Model_No)) {
            wher += ' AND Fixture_Model_No_F__c Like \'%' + String.escapeSingleQuotes(pageB.fixture_Model_No) + '%\'';
        }
        nowPage = 1;
        pageB.search(wher, assetFieldApiList, receivingNoteFieldApiList);
        changePage();
    }
    public void changeFixModel() {
        pageB.fixMode = true;
    }

    private void addField(Set<String> receivingNoteFieldApiSet, Set<String> assetFieldApiSet) {
        receivingNoteFieldApiSet.add('Id');
        receivingNoteFieldApiSet.add('Name');
        receivingNoteFieldApiSet.add('RNDAssert__c');
        receivingNoteFieldApiSet.add('ReceivingNoteSummary__c');
        receivingNoteFieldApiSet.add('Loaner_accsessary__c');
        receivingNoteFieldApiSet.add('DataConfirmation__c');
        receivingNoteFieldApiSet.add('unknow_serial_NO_product__c');
        receivingNoteFieldApiSet.add('ReceivingNoteSummary__r.ReceivingNote__c');
        receivingNoteFieldApiSet.add('ReceivingNoteSummary__r.Select_Fixture_Set_Key__c');
        receivingNoteFieldApiSet.add('ReceivingNoteSummary__r.Package_Status__c');
        receivingNoteFieldApiSet.add('Asset_loaner_category_F__c');
        receivingNoteFieldApiSet.add('Change_Point__c');
        receivingNoteFieldApiSet.add('ReceivingNoteSummary__r.Received_Confirm_Time__c');
        receivingNoteFieldApiSet.add('AcceptanceTime__c');
        receivingNoteFieldApiSet.add('DataConfirmationStaff__c');
        receivingNoteFieldApiSet.add('DataConfirmationTime__c');
        receivingNoteFieldApiSet.add('ReceivingNoteSummary__r.Wei_DataConfirmation_Cnt__c');
        receivingNoteFieldApiSet.add('Fixture_Arrival_Process__c');
        receivingNoteFieldApiSet.add('Fixture_Arrival_Product__c');
        receivingNoteFieldApiSet.add('Default_Fixture_Arrival_Process__c');
        receivingNoteFieldApiSet.add('Default_Fixture_Arrival_Product__c');
        receivingNoteFieldApiSet.add('Product_Arrival_Product__c');
        receivingNoteFieldApiSet.add('Set_Arrival_Product__c');
        receivingNoteFieldApiSet.add('RND_Status__c');
        receivingNoteFieldApiSet.add('Fixture_Set_Detail__c');
        receivingNoteFieldApiSet.add('RNDAssert__r.Consumable_Guaranteen_end__c');
    }

    private List<LabelValue> setFIeldSet(String objApi, String fieldSetApi, Set<String> fieldApiSet) {
        List<LabelValue> lvList = new List<LabelValue>();
        Map<String, Schema.FieldSet> fsMap = Schema.getGlobalDescribe().get(objApi).getDescribe().fieldSets.getMap();
        Schema.FieldSet fs = fsMap.get(fieldSetApi);
        List<FieldSetMember> fsmList = fs.getFields();

        for (FieldSetMember fsm : fsmList) {
            if (objApi == 'Asset') {
                fieldApiSet.add('RNDAssert__r.' + fsm.getFieldPath());
            }
            else {
                fieldApiSet.add(fsm.getFieldPath());
            }
            lvList.add(new LabelValue(fsm.getLabel(), fsm.getFieldPath()));
        }
        return lvList;
    }
    // 数据确认
    public Void defineSaveRecord() {
        done_flg = false;
        try {
            List<ReceivingNoteDetail__c> rndList = new List<ReceivingNoteDetail__c>();
            Map<Id,Asset> assMap = new Map<Id,Asset>();
            Datetime now = System.Now();
            String userId = Userinfo.getUserId();
            Account ocm = [select Id from Account where AgentCode_Ext__c =:System.Label.Account_Asset_FJZ];//20210623 ljh add
            Map<Id, ReceivingNoteDetail__c>  originRndMap= new Map<Id, ReceivingNoteDetail__c> (
                [
                    SELECT Id
                         , DataConfirmation__c
                         , Received_Confirm_Time_F__c
                      FROM ReceivingNoteDetail__c
                     WHERE ReceivingNote__c =:parId
                ]
            );
            for (RowBean rowB : pageB.showBList) {
                if (rowB.checked) {
                    if(originRndMap.containsKey(rowB.rnd.Id)) {
                        ReceivingNoteDetail__c originRnd = originRndMap.get(rowB.rnd.Id);
                        if(originRnd.DataConfirmation__c) {
                            throw new ControllerUtil.myException('【' + rowB.rnd.Name + '】已数据确认，不可勾选和修改');
                            return;
                        }
                    }
                    else {
                        throw new ControllerUtil.myException('【' + rowB.rnd.Name + '】不存在，请刷新画面重试');
                        return;
                    }
                    rowB.rnd.DataConfirmation__c = true;
                    rowB.rnd.DataConfirmationTime__c = now;
                    rowB.rnd.DataConfirmationStaff__c = userId;
                    Asset ass = new Asset();
                    ass.Id = rowB.rnd.RNDAssert__c;
                    if (String.isNotBlank(rowB.rnd.SerialNumber__c)) {
                        ass.SerialNumber = rowB.rnd.SerialNumber__c;
                        ass.SerialNumber_Origin__c = rowB.rnd.SerialNumber_Origin__c;
                    }
                    ass.AccountId = ocm.Id;
                    ass.AssetManageConfirm__c = false;
                    assMap.put(rowB.rnd.RNDAssert__c,ass);
                    rndList.add(rowB.rnd);
                }
            }
            if (rndList.size() > 0) {
                update rndList;
                update assMap.values();
                init();
                done_flg = true;
            }else{
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '请选择要确认的数据'));
            }
        }
        catch (Exception e) {
            ApexPages.addMessages(e);
        }
    }
    // 保存画面上的数据
    public Void saveRecord() {
        done_flg = false;
        try {
            List<ReceivingNoteDetail__c> rndList = new List<ReceivingNoteDetail__c>();
            Datetime now = System.Now();
            String userId = Userinfo.getUserId();
            Map<Id, ReceivingNoteDetail__c>  originRndMap= new Map<Id, ReceivingNoteDetail__c> (
                [
                    SELECT Id
                         , DataConfirmation__c
                         , Received_Confirm_Time_F__c
                      FROM ReceivingNoteDetail__c
                     WHERE ReceivingNote__c =:parId
                ]
            );
            for (RowBean rowB : pageB.showBList) {
                if (rowB.checked) {
                    if(originRndMap.containsKey(rowB.rnd.Id)) {
                        ReceivingNoteDetail__c originRnd = originRndMap.get(rowB.rnd.Id);
                        if(originRnd.DataConfirmation__c) {
                            throw new ControllerUtil.myException('【' + rowB.rnd.Name + '】已数据确认，不可勾选和修改');
                            return;
                        }
                    }
                    else {
                        throw new ControllerUtil.myException('【' + rowB.rnd.Name + '】不存在，请刷新画面重试');
                        return;
                    }
                    rndList.add(rowB.rnd);
                }
            }
            if (rndList.size() > 0) {
                update rndList;
                init();
                done_flg = true;
            }else{
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '请选择要保存的数据'));
                return;
            }
        }
        catch (Exception e) {
            ApexPages.addMessages(e);
        }
    }
    public class PageBean {
        /* ------------ 复数编辑用 ------------ */
        public ReceivingNoteDetail__c assetInput {get{
            if (assetInput == null) {
                assetInput = [SELECT Id
                         FROM ReceivingNoteDetail__c
                        LIMIT 1];
                assetInput = new ReceivingNoteDetail__c(Id = assetInput.Id);
            }
            return assetInput;
        } set;}

        /* ------------ 检索用 ------------ */
        public ReceivingNote__c rn {get; set;}
        public String fixture_Model_No {get; set;}
        public String status {get;set;}

        /* ------------  显示用 ------------ */
        public String dateOfDelivery {get; set;}

        /* ------------ 明细一覧 ------------ */
        public List<RowBean> rowBList {get; set;}
        public List<RowBean> showBList {get; set;}

        /* ------------ 记录用 ------------ */
        public Boolean fixMode {get; set;}
        public Integer currentPageRecordCnt {get; set;}

        public PageBean() {
            rn = new ReceivingNote__c();
            rowBList = new List<RowBean>();
            showBList = new List<RowBean>();
            fixMode = false;
            currentPageRecordCnt = 0;
        }

        public PageBean(ReceivingNote__c rnObj, List<String> assetFieldApiList, List<String> receivingNoteFieldApiList) {
            rn = rnObj;
            dateOfDelivery = rnObj.DateOfDelivery__c == null ? '' : rnObj.DateOfDelivery__c.format();
            rowBList = new List<RowBean>();
            showBList = new List<RowBean>();
            fixMode = false;
            search(null, assetFieldApiList, receivingNoteFieldApiList);
        }

        public void search(String wher, List<String> assetFieldApiList, List<String> receivingNoteFieldApiList) {
            wher = String.isBlank(wher) ? '' : wher;
            System.debug(assetFieldApiList);
            String soql = 'SELECT '
                    + String.join(assetFieldApiList, ',')
                    + (assetFieldApiList.size() > 0 ? ',' : '')
                    + String.join(receivingNoteFieldApiList, ',')
                 + ' FROM ReceivingNoteDetail__c '
                + ' WHERE ReceivingNoteSummary__r.ReceivingNote__c = \'' + rn.Id + '\'' + wher
                  + ' AND Delete_Flag__c = false '
                + ' ORDER BY ReceivingNoteSummary__c, ReceivingNoteDetailNo__c, RNDAssert__c nulls last';
            rowBList = new List<RowBean>();
            showBList = new List<RowBean>();
            System.debug(soql);
            List<ReceivingNoteDetail__c> rndList = Database.query(soql);
            Integer i = 0;
            for (ReceivingNoteDetail__c rnd : rndList) {
                rowBList.add(new RowBean(rnd, i));
                i ++;
            }
            currentPageRecordCnt = showBList.size();
        }
    }

    public class RowBean {
        public Boolean checked {get; set;}
        public Boolean canChange {get; set;}
        public Boolean dataConfirmation {get; set;}
        public String canChangeField {get; set;}
        public String canNotChangeField {get; set;}
        public Integer lineNo {get; set;}
        public Boolean haveAsset {get; set;}
        public ReceivingNoteDetail__c rnd {get; set;}

        public RowBean() {
            checked = false;
            rnd = new ReceivingNoteDetail__c();
            canChange = true;
            dataConfirmation = false;
            canChangeField = '';
        }

        public RowBean(ReceivingNoteDetail__c rnd1, Integer lineNo1) {
            rnd = rnd1;
            checked = false;
            canChange = true;
            dataConfirmation = rnd1.DataConfirmation__c;
            lineNo = lineNo1;
            // 产品入库产品 是 空, 说明是第一次打开画面 而且 没有保存过
            if (null == rnd.Product_Arrival_Product__c
                && String.isBlank(rnd.Fixture_Arrival_Process__c)
            ) {
                rnd.Fixture_Arrival_Process__c = rnd.Default_Fixture_Arrival_Process__c;
                rnd.Fixture_Arrival_Product__c = rnd.Default_Fixture_Arrival_Product__c;
            }
            // 收货确认过的明细不可编辑
            if( rnd.DataConfirmation__c && rnd.Received_Confirm_Time_F__c != null) {
                canChange = false;
            }

            if (rnd1.Asset_loaner_category_F__c == '耗材') {
                canChangeField = 'Salesdepartment__c, DataConfirmation__c, Equipment_Type__c,SerialNumber__c';
            }
            else{
                canChangeField = 'SerialNumber__c';
            }
            canNotChangeField = 'SerialNumber_Origin__c, SerialNumber__c, Change_Point__c, PeriodOfUse_Final__c';
            // 数据确认后、备品入库处理、备品入库产品が変更不可とする
            if ('待数据确认' != rnd1.RND_Status__c) {
                canNotChangeField += ', Fixture_Arrival_Process__c, Fixture_Arrival_Product__c';
            }
            haveAsset = String.isNotBlank(rnd1.RNDAssert__c);
        }
    }

    public class LabelValue {
        public String label {get; set;}
        public String value {get; set;}

        public LabelValue() {
            label = '';
            value = '';
        }

        public LabelValue(String l, String v) {
            label = l;
            value = v;
        }
    }

}