public with sharing class ConsumTrialController {

    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 Boolean canEdit{get;set;}
    public Boolean redOnly{get;set;}
    public Boolean showEditButton{get;set;}
    private String case_OR_animal_organLabel{get;set;}
    private String saveType{get;set;}
    public String staticResource {get; set;}
    public String rowListString{set;get;}
    public String EditAWSDataId{set;get;}

    public ConsumTrialController(ApexPages.StandardController stdController) {
        parId = System.currentPageReference().getParameters().get('Id');
        canEdit = System.currentPageReference().getParameters().get('canedit') == 'true';
        saveType = System.currentPageReference().getParameters().get('saveType');
        redOnly = false;
        showEditButton = false;
        if (String.isBlank(parId)) {
            parId = stdController.getId();
        }
        PIHelper.PIIntegration piIntegration = PIHelper.getPIIntegrationInfo('Consum_Apply_Equipment_Set_Detail__c');
        staticResource = JSON.serialize(piIntegration);
    }

    public void init() {
        try {
            if (String.isBlank(parId)) {
                throw new ControllerUtil.myException('请传入正确的参数');
            }
            List<Consum_Apply__c> rnList = [SELECT Id
                        // , DateOfDelivery__c
                        // , ReceivingNoteNo__c
                        , Status__c
                        ,AWS_Data_Id__c
                        // , Asset_loaner_category__c
                        , RA_Status__c
                        , demo_purpose2__c
                        , Person_In_Charge__c
                        , Request_demo_time__c
                     FROM Consum_Apply__c
                    WHERE Id = :parId];
            if (rnList.size() == 0) {
                throw new ControllerUtil.myException('收货清单Id不存在');
            }
            if (rnList[0].Request_demo_time__c != null) {
                redOnly = true;
            }
            case_OR_animal_organLabel = '病例';
            if (rnList[0].demo_purpose2__c == '动物实验' ) {
                case_OR_animal_organLabel = '动物脏器';
            }
            Set<String> assetFieldApiSet = new Set<String>();
            Set<String> receivingNoteFieldApiSet = new Set<String>();
            outputFieldList = setFIeldSet('Consum_Apply_Equipment_Set_Detail__c', 'ConsumTrial_L', receivingNoteFieldApiSet);
            inputFieldList = setFIeldSet('Consum_Apply_Equipment_Set_Detail__c', 'ConsumTrial_R', receivingNoteFieldApiSet);
            addField(receivingNoteFieldApiSet, assetFieldApiSet);
            assetFieldApiList = new List<String>();
            receivingNoteFieldApiList = new List<String>();
            assetFieldApiList.addAll(assetFieldApiSet);
            receivingNoteFieldApiList.addAll(receivingNoteFieldApiSet);
            pageB = new PageBean(rnList[0], assetFieldApiList, receivingNoteFieldApiList);
            rowListString = JSON.serialize(pageB.rowBList);
            showEditButton = (rnList[0].Status__c != '申请中' && rnList[0].Status__c != '取消');
        }
        catch (Exception e) {
            ApexPages.addMessages(e);
        }
        if (saveType == '1') {
            ApexPages.Message message = new ApexPages.Message(ApexPages.severity.INFO, '保存成功');
            ApexPages.addMessage(message);
        }
    }

    public List<SelectOption> getAsreceivedConditionOps() {
        return getPlickList('Consum_Apply__c', 'Status__c');
    }

    public List<SelectOption> getcategoryOps() {
        return getPlickList('Consum_Apply__c', 'Asset_loaner_category__c');
    }

    public void search() {
        System.debug(assetFieldApiList);
        String wher = '';
        if (String.isNotBlank(pageB.rn.Status__c)) {
            wher += ' AND RND_Status__c = \'' + String.escapeSingleQuotes(pageB.rn.Status__c) + '\'';
        }

        if (String.isNotBlank(pageB.fixture_Model_No)) {
            wher += ' AND Fixture_Model_No_F__c Like \'%' + String.escapeSingleQuotes(pageB.fixture_Model_No) + '%\'';
        }
        pageB.search(wher, assetFieldApiList, receivingNoteFieldApiList);
    }

    public void changeFixModel() {
        pageB.fixMode = pageB.fixMode == false;
    }

    private void addField(Set<String> receivingNoteFieldApiSet, Set<String> assetFieldApiSet) {
        receivingNoteFieldApiSet.add('Id');
        receivingNoteFieldApiSet.add('Name');
        receivingNoteFieldApiSet.add('Asset__c');
        receivingNoteFieldApiSet.add('Fixture_Model_No_F__c');
        receivingNoteFieldApiSet.add('Consum_Apply__r.AnimalExerimentFlag__c');
        receivingNoteFieldApiSet.add('Consum_Apply__r.demo_purpose2__c');
    }

    private List<SelectOption> getPlickList(String objApi, String fieldApi) {
        Schema.DescribeFieldResult fieldResult = Schema.getGlobalDescribe().get(objApi).getDescribe().fields.getMap().get(fieldApi).getDescribe();
        List<SelectOption> pickListValuesList= new List<SelectOption>();
        List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
        pickListValuesList.add(new SelectOption('', NONE));
        for( Schema.PicklistEntry pickListVal : ple){
            pickListValuesList.add(new SelectOption(pickListVal.getValue(), pickListVal.getLabel()));
        }
        return pickListValuesList;
    }

    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('Assert__r.' + fsm.getFieldPath());
            }
            else {
                fieldApiSet.add(fsm.getFieldPath());
            }
            if (fsm.getFieldPath() == 'Case_OR_animal_organ__c') {
                lvList.add(new LabelValue(case_OR_animal_organLabel, fsm.getFieldPath()));
            }
            else {
                lvList.add(new LabelValue(fsm.getLabel(), fsm.getFieldPath()));
            }
        }
        return lvList;
    }

    // 适用区域信息提示
    public void showApplyMsg() {
        String applyMsg = ApexPages.currentPage().getParameters().get('applyMsg');
        String applyMsgType = ApexPages.currentPage().getParameters().get('applyMsgType');
        String applyErrorLabel = ApexPages.currentPage().getParameters().get('applyErrorLabel');
        if(applyMsgType == 'Fail') {
            ApexPages.Message vfApplyMsg = new ApexPages.Message(ApexPages.severity.ERROR, applyMsg);
            ApexPages.addMessage(vfApplyMsg);
            System.debug('applyMsg===' + applyMsg);
            System.debug('applyMsgType===' + applyMsgType);
            System.debug('applyErrorLabel===' + applyErrorLabel);
            if(applyErrorLabel != null) {
                System.debug('applyErrorLabel===' + applyErrorLabel);
            }
        } else {
            ApexPages.Message vfApplyMsg = new ApexPages.Message(ApexPages.severity.INFO, applyMsg);
            ApexPages.addMessage(vfApplyMsg);
        }
    }
    public List<SelectOption> getShowDemonstrationOps() {
        List<SelectOption>  options = getPlickList('Consum_Apply_Equipment_Set_Detail__c', 'Show_demonstration__c');
        // 显示为空白，值为'x'，适用时保持原样
        options.add(0, new SelectOption('x',''));
        return options;
    }
    public List<SelectOption> getOperationTypeOps() {
        List<SelectOption>  options = getPlickList('Consum_Apply_Equipment_Set_Detail__c', 'Operation_Type__c');
        // 显示为空白，值为'x'，适用时保持原样
        options.add(0, new SelectOption('x',''));
        return options;
    }
    public List<SelectOption> getCase_OR_animal_organOpsHead() {
        List<SelectOption> opList = getCase_OR_animal_organOps();
        opList.add(0, new SelectOption('x',''));
        return opList;
    }
    public List<SelectOption> getCase_OR_animal_organOps() {
        List<SelectOption> opList = new List<SelectOption>();
        opList.add(new SelectOption('', NONE));
        for (Integer i = 0; i < 20; i ++) {
            String value = case_OR_animal_organLabel + String.valueOf(i + 1);
            opList.add(new SelectOption(value, value));
        }
        return opList;
    }

    // 保存画面上的数据
    public PageReference saveRecord() {
        try {
            List<Consum_Apply__c> rnList = [SELECT Id
                        // , DateOfDelivery__c
                        // , ReceivingNoteNo__c
                        , Status__c
                        // , Asset_loaner_category__c
                        , RA_Status__c
                        , demo_purpose2__c
                        , Person_In_Charge__c
                     FROM Consum_Apply__c
                    WHERE Id = :parId];
            if (rnList.size() == 0) {
                throw new ControllerUtil.myException('耗材申请书不存在,请刷新画面重试');
            }
            if (rnList[0].Status__c == '申请中') {
                throw new ControllerUtil.myException('申请中的耗材申请书不能保存');
            }
            else if (rnList[0].Status__c == '取消') {
                throw new ControllerUtil.myException('取消的耗材申请书不能保存');
            }
            system.debug('耗材备品明细加密信息:'+JSON.serialize(pageB.rowBList));
            List<Consum_Apply_Equipment_Set_Detail__c> rndList = new List<Consum_Apply_Equipment_Set_Detail__c>();
            for (RowBean rowB : pageB.rowBList) {
                if (rowB.checked) {
                    rowB.rnd.InputCheck__c = true;
                    //rowB.rnd.AWS_Data_Id__c = EditAWSDataId;
                    System.debug('zhj rowB.rnd.AWS_Data_Id__c = '+ rowB.rnd.AWS_Data_Id__c);
                    rndList.add(rowB.rnd);
                }
            }
            if (rndList.size() > 0) {
                FixtureUtil.withoutUpdate(rndList, true);
                PageReference pag = new PageReference('/apex/ConsumTrial?id=' + parId + '&canedit=true&saveType=1');
                pag.setRedirect(true);
                return pag;
            }
            else{
                init();
            }
        }
        catch (Exception e) {
            ApexPages.addMessages(e);
            return null;
        }
        pageB.fixMode = false;
        return null;
    }

    public PageReference SelectRNS() {
        try {
            // List<String> rowId = new List<String>();
            // String rdId;
            // String snumber;
            // Set<String> selectKey = new Set<String>();
            // Set<String> modelKey = new Set<String>();
            // Boolean haveCheck = false;
            // for (RowBean rowB : pageB.rowBList) {
            //     if (rowb.checked) {
            //         if(String.isblank(rowB.rnd.Asset__c)){
            //             throw new ControllerUtil.myException('存在不带保有设备的明细,不可以选择配套');
            //         }
            //         // rowId.add(rowB.rnd.Consum_Apply_Equipment_Set__c);
            //         if (selectKey.isEmpty()) {
            //             selectKey.add(rowB.rnd.Consum_Apply_Equipment_Set__r.Select_Fixture_Set_Key__c);
            //             modelKey.add(rowB.rnd.Fixture_Model_No_F__c);
            //         }
            //         if (selectKey.contains(rowB.rnd.Consum_Apply_Equipment_Set__r.Select_Fixture_Set_Key__c) == false) {
            //             throw new ControllerUtil.myException('有不是一起选择配套的明细,不可以一起选择配套');
            //         }
            //         if (modelKey.contains(rowB.rnd.Fixture_Model_No_F__c) == false) {
            //             throw new ControllerUtil.myException('有不统一的备品配套明细型号一起选择,不可以一起选择配套');
            //         }
            //         rdId = rowB.rnd.Consum_Apply_Equipment_Set__r.Consum_Apply__c;
            //         if (String.isBlank(snumber)) {
            //             snumber = rowB.rnd.Id;
            //         }
            //         haveCheck = true;
            //     }
            // }
            // if (haveCheck == false) {
            //     throw new ControllerUtil.myException('请选择收货清单一览明细');
            // }
            // PageReference pg = new PageReference('/apex/ReceivingNoteSummarySelect?pt_recid=' + rdId + '&raesid=' + String.join(rowId, ','));
            // return pg;
        }
        catch (Exception e) {
            ApexPages.addMessages(e);
        }
        return null;
    }

    /**
    @description 取消按钮Action 
                 OLY_OCM-768 指摘【取消】按钮的功能是关闭画面，此处为提高覆盖率而注释掉
    */
    //public PageReference cancelRecord() {
    //    try {
    //        Set<String> rnsIdList = new Set<String>();
    //        for (RowBean rowB : pageB.rowBList) {
    //            if (rowB.checked) {
    //                rnsIdList.add(rowB.rnd.Consum_Apply_Equipment_Set__c);
    //            }
    //        }
    //        List<Consum_Apply_Equipment_Set_Detail__c> rndList = [SELECT Id
    //                 FROM Consum_Apply_Equipment_Set_Detail__c
    //                WHERE Asset__c = null
    //                  AND Consum_Apply_Equipment_Set__c = :rnsIdList];
    //        if (rndList.size() > 0) {
    //            delete rndList;
    //        }
    //        else {
    //            ApexPages.Message vfApplyMsg = new ApexPages.Message(ApexPages.severity.WARNING, '没有需要取消的收货清单配套一览');
    //            ApexPages.addMessage(vfApplyMsg);
    //        }
    //        search();
    //    }
    //    catch (Exception e) {
    //        ApexPages.addMessages(e);
    //    }
    //    pageB.fixMode = false;
    //    return null;
    //}

    // 幸好提醒邮件Action
    public void sendEmail() {
        // Savepoint sp = Database.setSavepoint();
        // try{
        //     String emailBody = System.currentPageReference().getParameters().get('emailBody');
        //     String emailMsg = '';
        //     for (RowBean rowB : pageB.rowBList) {
        //         if (rowB.checked) {
        //            emailMsg += rowB.rnd.Name + '<BR>';
        //         }
        //     }
        //     if (String.isNotBlank(emailMsg)) {
        //         pageB.rn.Model_Reminder_Email_Text__c = null;
        //         update pageB.rn;
        //         pageB.rn.Model_Reminder_Email_Text__c = emailBody + '<BR><BR>' + emailMsg;
        //         update pageB.rn;
        //         ApexPages.Message vfApplyMsg = new ApexPages.Message(ApexPages.severity.INFO, '已发送');
        //         ApexPages.addMessage(vfApplyMsg);
        //     }
        //     else {
        //         throw new ControllerUtil.myException('请选择型号提醒邮件明细');
        //     }
        // }
        // catch (Exception e) {
        //     Database.rollback(sp);
        //     ApexPages.addMessages(e);
        // }
    }


    public class PageBean {
        /* ------------ 检索编辑用 ------------ */
        //public Consum_Apply_Equipment_Set_Detail__c caesdInput {get{
        //    if (caesdInput == null) {
        //        List<Consum_Apply_Equipment_Set_Detail__c> caesdList = [SELECT Id
        //                 FROM Consum_Apply_Equipment_Set_Detail__c
        //                LIMIT 1];
        //        caesdInput = new Consum_Apply_Equipment_Set_Detail__c();
        //        if (caesdList.size() > 0) {
        //            caesdInput.Id = caesdList[0].Id;
        //        }
        //    }
        //    return caesdInput;
        //} set;}
        public Consum_Apply_Equipment_Set_Detail__c caesdInput {get;set;}

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

        /* ------------  显示用 ------------ */
        public String spareLocationName {get; set;}
        public String dateOfDelivery {get; set;}
        public String orderCode {get; set;}
        public String approvalNumber {get; set;}
        public String receivingNoteNo {get; set;}
        public String asreceivedCondition {get; set;}

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

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

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

        public PageBean(Consum_Apply__c rnObj, List<String> assetFieldApiList, List<String> receivingNoteFieldApiList) {
            rn = rnObj;
            asreceivedCondition = rnObj.RA_Status__c;
            // dateOfDelivery = rnObj.DateOfDelivery__c == null ? '' : rnObj.DateOfDelivery__c.format();
            rowBList = new List<RowBean>();
            fixMode = false;
            search(null, assetFieldApiList, receivingNoteFieldApiList);
            if (caesdInput == null) {
                List<Consum_Apply_Equipment_Set_Detail__c> caesdList = [SELECT Id
                         FROM Consum_Apply_Equipment_Set_Detail__c
                        LIMIT 1];
                caesdInput = new Consum_Apply_Equipment_Set_Detail__c();
                if (caesdList.size() > 0) {
                    caesdInput.Id = caesdList[0].Id;
                    caesdInput.Follower_User__c = rnObj.Person_In_Charge__c;
                }
            }
        }

        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, ',')
                    + ',AWS_Data_Id__c'
                 + ' FROM Consum_Apply_Equipment_Set_Detail__c '
                + ' WHERE Consum_Apply_Equipment_Set__r.Consum_Apply__c = \'' + rn.Id + '\'' + wher
                  + ' AND (Cancel_Select__c = false OR NG_Select_Again__c = true)'
                + ' ORDER BY Consum_Apply_Equipment_Set__r.Consum_Apply__c, Consum_Apply_Equipment_Set__c, Fixture_Model_No_F__c, NG_Select_Again__c, Degree_Of_Importance__c Limit 501';
            rowBList = new List<RowBean>();
            System.debug(soql);
            List<Consum_Apply_Equipment_Set_Detail__c> rndList = Database.query(soql);
            if (rndList.size() > 500) {
                ApexPages.Message vfApplyMsg = new ApexPages.Message(ApexPages.severity.WARNING, '耗材明细超过500条,只显示前500条耗材明细');
                ApexPages.addMessage(vfApplyMsg);
                rndList.remove(500);
            }
            // Map<String, Integer> maxDegree_Of_ImportanceMap = new Map<String, Integer>();
            // for (Consum_Apply_Equipment_Set_Detail__c rnd : rndList) {
            //     if (maxDegree_Of_ImportanceMap.containsKey(rnd.Fixture_Model_No_F__c) == false) {
            //         maxDegree_Of_ImportanceMap.put(rnd.Fixture_Model_No_F__c, 0);
            //     }
            //     maxDegree_Of_ImportanceMap.put(rnd.Fixture_Model_No_F__c, maxDegree_Of_ImportanceMap.get(rnd.Fixture_Model_No_F__c) + 1);
            // }
            Integer i = 0;
            Boolean isOddnumber = true;
            String modelNumber = '';
            for (Consum_Apply_Equipment_Set_Detail__c rnd : rndList) {
                RowBean rb = new RowBean(rnd, i);
                rb.maxDegree_Of_Importance = rndList.size();
                if (String.isBlank(modelNumber)) {
                    modelNumber = rb.rnd.Fixture_Model_No_F__c;
                }
                if (modelNumber != rb.rnd.Fixture_Model_No_F__c) {
                    modelNumber = rb.rnd.Fixture_Model_No_F__c;
                    isOddnumber = !isOddnumber;
                }
                rb.isOddnumber = isOddnumber;
                rowBList.add(rb);
                i ++;
            }
            currentPageRecordCnt = rndList.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 Integer lineNo {get; set;}
        public Boolean haveAsset {get; set;}
        public Integer maxDegree_Of_Importance {get; set;}
        public Consum_Apply_Equipment_Set_Detail__c rnd {get; set;}
        public Boolean isOddnumber {get; set;}
        // public Asset asse {get; set;}

        public RowBean() {
            checked = false;
            rnd = new Consum_Apply_Equipment_Set_Detail__c();
            // asse = new Asset();
            canChange = true;
            dataConfirmation = false;
            canChangeField = '';
        }

        public RowBean(Consum_Apply_Equipment_Set_Detail__c rnd1, Integer lineNo1) {
            rnd = rnd1;
            // asse = rnd1.RNDAssert__r;
            checked = false;
            canChange = true;
            // dataConfirmation = rnd1.DataConfirmation__c;
            lineNo = lineNo1 + 1;
            canChangeField = 'Show_demonstration__c, Operation_Type__c, Consum_Start_Date__c';
            canChangeField += ',AWS_Data_Id__c, Case_OR_animal_organ__c, Trial_User__c, Follower_User__c, Spare__c, Comment__c, Degree_Of_Importance__c';

            haveAsset = String.isNotBlank(rnd1.Asset__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;
        }
    }

    @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++;
    }
}