public with sharing class InstructReportController {
    public String targetInstructReportId { get; private set; }
    public String targetCampaignId { get; private set; }
    public Instruct_report__c Instruct_report { get; private set; }
    public list<Instructed_staff__c> ISList { get; private set; }
    public list<InstructedstaffInfo> checkedISList { get; private set; }
    public list<InstructedstaffInfo> uncheckedISList { get; private set; }
    public boolean ReadOnly { get; private set; }

    // 20220222 PI改造 by Bright--start
    //deloitte-zhj 20231114 PIPL还原
    //public string staticResource { get; private set; }   
    // 20220222 PI改造 by Bright--end

    public InstructReportController() {
        this.ReadOnly = true;
        //deloitte-zhj 20231114 PIPL还原
        //staticResource = JSON.serialize(PIHelper.getPIIntegrationInfo('Contact'));// 20220222 PI改造 by Bright
    }
    public InstructReportController(ApexPages.StandardController controller) {
        this();
    }
    public void init() {

        this.targetInstructReportId = ApexPages.currentPage().getParameters().get('id');
        this.targetCampaignId = ApexPages.currentPage().getParameters().get('camid');
        try {
            //打开现有带教报告
            if (String.isBlank(this.targetInstructReportId) == false) {
                setCurrentInstructReport();
                if (this.Instruct_report == null) {
                    throw new ControllerUtil.myException('无法打开现有带教报告');
                }
                this.targetCampaignId = this.Instruct_report.Campaign__c;

            }
            //新建带教报告
            else if (!String.isBlank(this.targetCampaignId)) {
                //HWAG-BDZ398 判断是否有权新建报告 start
                if (!Instruct_report__c.sObjectType.getDescribe().isCreateable()) {
                    throw new ControllerUtil.myException('您没有权限新建带教报告');
                    return;
                }
                //HWAG-BDZ398 判断是否有权新建报告 end
                this.ReadOnly = false;
                this.Instruct_report = new Instruct_report__c();
                this.Instruct_report.Campaign__c = this.targetCampaignId;
                setUpInstructReport();
            }
            //其他可能直接报错
            else {
                throw new ControllerUtil.myException('无法显示带教报告');
                return;
            }
            // 初始化已选择带教人员和未选择带教人员
            checkedISList = new list<InstructedstaffInfo>();
            uncheckedISList = new list<InstructedstaffInfo>();
            setCurrentInstructedStaff();
        } catch (Exception ex) {
            ApexPages.addMessages(ex);

        }

        return;

    }
    //HWAG-BDZ398 判断是否有权编辑报告  服务企划部窗口 不能编辑 start
    public Boolean getIsServiceDesignDep() {
        List<group> groupList =
            [SELECT Id, Name, DeveloperName
             FROM Group
             where DeveloperName  = 'ServiceDesignDepGroup'];
        if (groupList.size() > 0) {
            list<GroupMember> GMlist =
                [select id from GroupMember
                 where GroupId = :groupList[0].id
                                 and UserOrGroupId = : userinfo.getuserid()];
            if (GMlist.size() > 0) {
                return true;
            }
        }

        return false;
    }
    //HWAG-BDZ398 判断是否有权编辑报告  服务企划部窗口 不能编辑  end

    @TestVisible private void setCurrentInstructReport() {
        list<Instruct_report__c> Instruct_reportList = [SELECT Id, Name, CreatedById,
                                 Report_Code__c,
                                 Status__c,
                                 Verifier__c, VerifierName__c, VerifierNumber__c ,
                                 Instructed_staff_number__c, Instruct_Staff__c,
                                 Campaign__c, ReportDate__c, teachingDate__c
                                 FROM Instruct_report__c where id = : targetInstructReportId];

        if (Instruct_reportList.size() > 0) {
            Instruct_report = Instruct_reportList[0];
        }

    }

    // 检索出当前学会培训下所有参会人员，检索出当前带教报告的人员，进行一一比对，设置带教人员和参会名单
    @TestVisible private void setCurrentInstructedStaff() {
        checkedISList.clear();
        uncheckedISList.clear();
        list<CampaignMember__c> CMlist = [
                                             SELECT Id, Name, Department_ID__c ,
                                             //增加检索 有效/无效 精琢技术 wql 2021/02/04 start
                                             Is_Active_Formula__c
                                             //增加检索 有效/无效 精琢技术 wql 2021/02/04 end
                                             ,Contact_ID__c, Contact_ID__r.Name,
                                             //deloitte-zhj 20231114 PIPL还原
                                             //Contact_ID__r.AWS_Data_Id__c,// 20220222 PI改造 by Bright
                                             // LJPH-BVNBMM start
                                             Contact_ID__r.AccountId,
                                             Department_Service__c,
                                             Department_ServiceID__c,Contact__c,
                                             ContactName__c,
                                             // LJPH-BVNBMM end
                                             dept__c, State__c, City__c
                                             FROM CampaignMember__c
                                             where Campaign__c = : Instruct_report.Campaign__c
                                         ];

        list<Instructed_staff__c> ISList =
            [SELECT Id, Name, Instruct_report__c,
             Instructed_staff_feedback__c,
             Instruct_staff_feedback__c,
             Instruct_content_other__c, Instruct_time__c, Instruct_Date__c,
             CampaignMember__c, DepartmentID__c, DepartmentName__c, Department__c
             //增加检索 有效/无效 精琢技术 wql 2021/02/04 start
             ,Is_Active_Formula__c
             //增加检索 有效/无效 精琢技术 wql 2021/02/04 end
             , ContactID__C
             //deloitte-zhj 20231114 PIPL还原
             //,ContactID__r.AWS_Data_Id__c// 20220222 PI改造 by Bright
             //带教报告 新增查询字段：带教地点、带教地点（其他）、设备类别、具体型号、备注 精琢技术 wql 2020/04/14 start
             , Instruct_place_other__c, Specific_model__c,
             Instruct_remarks__c, Equipment_category__c, Instruct_place__c, Instruct_content__c
             //带教报告 新增查询字段：带教地点、带教地点（其他）、设备类别、具体型号、备注 精琢技术 wql 2020/04/14 end
             //带教报告 新增字段：确认人职位、确认人姓名 精琢技术 wql 2020/05/27 start
             , Verifier__c, VerifierName__c
             //带教报告 新增字段：确认人职位、确认人姓名 精琢技术 wql 2020/05/27 end

             FROM Instructed_staff__c
             where Instruct_report__c = : targetInstructReportId];
        Map <id, Instructed_staff__c> ISMap = new Map <id, Instructed_staff__c>();

        for (Instructed_staff__c temIS :  ISList) {
            ISMap.put(temIS.CampaignMember__c, temIS);
        }

        for (CampaignMember__c temCM : CMlist) {
            if (ISMap.containsKey(temCM.id)) {
                checkedISList.add(
                    new InstructedstaffInfo(checkedISList.size(),
                                            ISMap.get(temCM.id), temCM, true));

            } else {
                uncheckedISList.add(new InstructedstaffInfo(uncheckedISList.size(), temCM));
            }
        }


    }

    public PageReference exchangeInstructedstaff() {
        list<InstructedstaffInfo> temcheckedISList = new list<InstructedstaffInfo>();
        list<InstructedstaffInfo> temuncheckedISList = new list<InstructedstaffInfo>();
        for (InstructedstaffInfo checkedIS : checkedISList) {
            if (checkedIS.rec_checkBox) {
                checkedIS.lineNo = temcheckedISList.size();
                temcheckedISList.add(checkedIS);
            } else {
                checkedIS.IS = null;
                checkedIS.lineNo = temuncheckedISList.size();
                temuncheckedISList.add(checkedIS);
            }
        }
        for (InstructedstaffInfo uncheckedIS : uncheckedISList) {

            if (uncheckedIS.rec_checkBox) {
                //deloitte-zhj 20231114 PIPL还原
                //System.debug('uncheckedIS.CamMem.Contact_ID__r='+uncheckedIS.CamMem.Contact_ID__r.AWS_Data_Id__c);
                uncheckedIS.IS = new Instructed_staff__c(Name = uncheckedIS.CamMem.Contact_ID__r.Name,
                        // LJPH-BVNBMM 改为同步当前联系人所在的科室 start
                        Department__c = uncheckedIS.CamMem.Contact_ID__r.AccountId,
                        // LJPH-BVNBMM 改为同步当前联系人所在的科室 start
                        CampaignMember__c = uncheckedIS.CamMem.id,
                        ContactID__c = uncheckedIS.CamMem.Contact_ID__c,
                        ContactID__r = uncheckedIS.CamMem.Contact_ID__r // 20220222 PI改造 by Bright
                         );
                uncheckedIS.lineNo = temuncheckedISList.size();
                temcheckedISList.add(uncheckedIS);
            } else {
                uncheckedIS.IS = null;
                uncheckedIS.lineNo = temuncheckedISList.size();
                temuncheckedISList.add(uncheckedIS);
            }
        }
        checkedISList   = temcheckedISList.clone();
        uncheckedISList = temuncheckedISList.clone();
        return null;
    }

    public PageReference save() {

        if (CheckSaveInput()) {
            return null;
        }

        if (syncInstructReport()) {
            setCurrentInstructReport();
            setCurrentInstructedStaff();

            ReadOnly = true;
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO, '保存好了！'));
        }
        return null;
    }

    public PageReference submit() {
        if (CheckSaveInput()) {
            return null;
        }
        Savepoint sp = Database.setSavepoint();

        try {
            if (syncInstructReport()) {
                ReadOnly = true;
                Approval.ProcessSubmitRequest psr = new Approval.ProcessSubmitRequest();
                psr.setObjectId(this.Instruct_report.id);

                Approval.ProcessResult submitResult = Approval.process(psr);
                setCurrentInstructReport();
                setCurrentInstructedStaff();
                ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO, '提交成功'));
            }
        } catch (DMLException ex) {
            Database.rollback(sp);
            ApexPages.addMessages(ex);
        } catch (Exception ex) {
            Database.rollback(sp);
            ApexPages.addMessages(ex);
        }

        system.debug('Submit End');

        return null;
    }

    public PageReference EditRecord() {
        ReadOnly = !ReadOnly;
        Instruct_report.Status__c = '草案中';
        return null;
    }

    public Boolean getInputdisabled() {
        return ReadOnly;
    }


    /** 保存返回 **/
    public PageReference saveAndCancel () {
        if (CheckSaveInput()) {
            return null;
        }

        if (syncInstructReport()) {
            PageReference ret = null;
            if (this.targetCampaignId != null) {
                ret = new PageReference('/' + this.targetCampaignId);
            }
            return ret;
        }
        return null;
    }
    public PageReference cancel() {
        PageReference ret = null;
        if (this.targetCampaignId != null) {
            ret = new PageReference('/' + this.targetCampaignId);
        }
        return ret;
    }
    /*
        新建的带教报告
    */
    @TestVisible private void setUpInstructReport() {
        this.Instruct_report.Status__c   = '草案中';
        list<Instruct_report__c> IRRecords =
            [select id, Campaign__r.OwnerID, Campaign__r.RecordTypeid, Campaign__r.Salesdepartment__c
             from Instruct_report__c where Campaign__c = : targetCampaignId];

        Campaign temCam = [select id, name, TrainingCode__c, ServiceDesignDep__c,
                           JingliApprovalManager__c, BuchangApprovalManager__c,OwnerID,RecordTypeid,Salesdepartment__c 
                           from Campaign where id = : targetCampaignId];


        if (IRRecords == null || temCam == null) {
            throw new ControllerUtil.myException('找不到对应的学会培训,无法保存！');
        }


        integer IRRecordsNumber = IRRecords.size() + 1;
        this.Instruct_report.Name = temCam.Name + '第' + IRRecordsNumber + '次带教报告';
        // 修改带教报告经理等取值逻辑  2020/07/28   精琢技术 start
        if (temCam != null) {
            setInsertOwner(temCam);
        }
        //注释原来赋值逻辑
        // this.Instruct_report.ServiceDesignDep__c = temCam.ServiceDesignDep__c;
        // this.Instruct_report.JingliApprovalManager__c = temCam.JingliApprovalManager__c;
        // this.Instruct_report.BuchangApprovalManager__c = temCam.BuchangApprovalManager__c;
        // 修改带教报告经理等取值逻辑  2020/07/28   精琢技术 end
        if (IRRecordsNumber < 10) {
            this.Instruct_report.Report_Code__c = temCam.TrainingCode__c + '-OJT00' + IRRecordsNumber;
        } else {
            this.Instruct_report.Report_Code__c = temCam.TrainingCode__c + '-OJT0' + IRRecordsNumber;
        }
    }

    //LJPH-BRW8SH 精琢技术 wql 2020/07/29 start
    //提交待审批的时候给服务企划部窗口、经理、部长 赋值
    @TestVisible private void setInsertOwner(Campaign temCam) {
        if (temCam != null ) {
            Map<Id, User> userMap = new Map<Id, User>();
            List<user> OwnerList = New List<user>();
            // 修改带教报告经理等取值逻辑  2020/07/28   精琢技术 Start
            OwnerList = [SELECT Id, SalesManager__c, BuchangApprovalManagerSales__c,
                         JingliApprovalManager__c, BuchangApprovalManager__c, ZongjianApprovalManager__c,
                         OCM_man_province__c, Province__c
                         FROM user WHERE id = :temCam.OwnerID];
            // 修改带教报告经理等取值逻辑  2020/07/28   精琢技术 end
            for (User u : OwnerList) {
                userMap.put(u.Id, u);
            }
            
            if (temCam.RecordTypeid != (ID) system.label.RecordType_CampaignService ) {
                this.Instruct_report.JingliApprovalManager__c  = userMap.get(temCam.OwnerID).SalesManager__c;
                this.Instruct_report.BuchangApprovalManager__c = userMap.get(temCam.OwnerID).BuchangApprovalManagerSales__c;

            } else {
                this.Instruct_report.JingliApprovalManager__c = userMap.get(temCam.OwnerID).JingliApprovalManager__c == null ? temCam.OwnerID :  userMap.get(temCam.OwnerID).JingliApprovalManager__c;
                this.Instruct_report.BuchangApprovalManager__c = userMap.get(temCam.OwnerID).BuchangApprovalManager__c == null ? temCam.OwnerID :  userMap.get(temCam.OwnerID).BuchangApprovalManager__c;

                if (temCam.Salesdepartment__c != null && temCam.Salesdepartment__c.equals('1.华北')) {
                    this.Instruct_report.ServiceDesignDep__c = System.Label.ServiceDesignDep_NC;
                }
                if (temCam.Salesdepartment__c != null && temCam.Salesdepartment__c.equals('2.东北')) {
                    this.Instruct_report.ServiceDesignDep__c = System.Label.ServiceDesignDep_NE;
                }
                if (temCam.Salesdepartment__c != null && temCam.Salesdepartment__c.equals('3.西北')) {
                    this.Instruct_report.ServiceDesignDep__c = System.Label.ServiceDesignDep_NW;
                }
                if (temCam.Salesdepartment__c != null && temCam.Salesdepartment__c.equals('4.西南')) {
                    this.Instruct_report.ServiceDesignDep__c = System.Label.ServiceDesignDep_SW;
                }
                if (temCam.Salesdepartment__c != null && temCam.Salesdepartment__c.equals('5.华东')) {
                    this.Instruct_report.ServiceDesignDep__c = System.Label.ServiceDesignDep_EC;
                }
                if (temCam.Salesdepartment__c != null && temCam.Salesdepartment__c.equals('6.华南')) {
                    this.Instruct_report.ServiceDesignDep__c = System.Label.ServiceDesignDep_SC;
                } else {
                    this.Instruct_report.ServiceDesignDep__c = System.Label.ServiceDesignDep_NC;
                }
            }
        }


        // Campaign temCam = [select id, name, TrainingCode__c, ServiceDesignDep__c,
        //                    JingliApprovalManager__c, BuchangApprovalManager__c
        //                    from Campaign where id = : targetCampaignId];
        // this.Instruct_report.ServiceDesignDep__c = temCam.ServiceDesignDep__c;
        // this.Instruct_report.JingliApprovalManager__c = temCam.JingliApprovalManager__c;
        // this.Instruct_report.BuchangApprovalManager__c = temCam.BuchangApprovalManager__c;
    }
    //LJPH-BRW8SH 精琢技术 wql 2020/07/29 end
    @TestVisible private Boolean syncInstructReport() {
        system.debug('syncInstructReport start');
        Savepoint sp = Database.setSavepoint();
        try {
            //LJPH-BRW8SH 精琢技术 wql 2020/07/29 start
            Campaign temCam = [select id, name, TrainingCode__c, ServiceDesignDep__c,
                           JingliApprovalManager__c, BuchangApprovalManager__c,OwnerID,RecordTypeid,Salesdepartment__c 
                           from Campaign where id = : targetCampaignId];


            if (temCam != null) {
                setInsertOwner(temCam);
            }
            
            //LJPH-BRW8SH 精琢技术 wql 2020/07/29 end

            upsert Instruct_report;
            targetInstructReportId = Instruct_report.id;
            //删掉所有带教报告人员
            list<Instructed_staff__c> deleteIS = [select id from Instructed_staff__c
                                                  where Instruct_report__c = : targetInstructReportId];
            if (deleteIS.size() > 0) {
                delete deleteIS;
            }
            //插入页面上带教报告人员
            list<Instructed_staff__c> insertIS = new list<Instructed_staff__c>();
            for (InstructedstaffInfo temIS : checkedISList) {
                if (temIS.IS.Instruct_report__c == null) {
                    temIS.IS.Instruct_report__c = targetInstructReportId;
                }
                temIS.IS.id = null;
                insertIS.add(temIS.IS);
            }
            if (insertIS.size() > 0) {
                insert insertIS;
            }
            setCurrentInstructReport();
            return true;
        } catch (DMLException ex) {
            Database.rollback(sp);

            ApexPages.addMessages(ex);
        } catch (Exception ex) {
            Database.rollback(sp);
            ApexPages.addMessages(ex);
        }
        return false;

    }


    @TestVisible private Boolean CheckSaveInput() {
        boolean hasError = false;
        // if (string.isblank(Instruct_report.Instruct_Staff__c)) {
        //     hasError = true;
        //     Instruct_report.Instruct_Staff__c.addError('请填写带教人！');
        // }
        //if (string.isblank(Instruct_report.Verifier__c)) {
        //  hasError = true;
        //  Instruct_report.Verifier__c.addError('请选择确认人职位！');

        //}
        // if (string.isblank(Instruct_report.VerifierName__c)) {
        //     hasError = true;
        //     Instruct_report.VerifierName__c.addError('请选择确认人姓名！');

        // }
        //if (string.isblank(Instruct_report.VerifierNumber__c)) {
        //  hasError = true;
        //  Instruct_report.VerifierNumber__c.addError('请选择确认人电话！');

        //}
        for (InstructedstaffInfo temIS : checkedISList) {
            if (temIS.IS.Instruct_Date__c == null) {
                hasError = true;
                temIS.IS.Instruct_Date__c.addError('请选择带教日期！');

            }
            if (temIS.IS.Instruct_time__c == null ) {
                hasError = true;
                temIS.IS.Instruct_time__c.addError('请填写带教时长(H)  ！');

            }
            if (string.isblank(temIS.IS.Instruct_content__c)) {
                hasError = true;
                temIS.IS.Instruct_content__c.addError('请填写带教内容！');
            }

            if (string.isblank(temIS.IS.Verifier__c)) {
                hasError = true;
                temIS.IS.Verifier__c.addError('请填写确认人职位！');
            }

            if (string.isblank(temIS.IS.VerifierName__c)) {
                hasError = true;
                temIS.IS.VerifierName__c.addError('请填写确认人姓名！');
            }

            // } else if ('其他'.equals(temIS.IS.Instruct_content__c)
            //            && (temIS.IS.Instruct_content_other__c == null ||
            //                temIS.IS.Instruct_content_other__c.equals('')
            //               )) {
            //     hasError = true;
            //     temIS.IS.Instruct_content_other__c.addError('带教内容选择其他时，请填写具体内容！');

            // }
            //带教报告 带教地点验证
            Integer index;
            String  place = String.valueOf(temIS.IS.Instruct_place__c);
            if (String.isNotBlank(place)) {
                index = place.indexOf('其它');
            }

            system.debug('place:' + place);
            system.debug('index:' + index);
            if (string.isblank(temIS.IS.Instruct_place__c)) {
                hasError = true;
                temIS.IS.Instruct_place__c.addError('请填写带教地点！');
            } else if (index != -1 && string.isblank(temIS.IS.Instruct_place_other__c)) {
                hasError = true;
                temIS.IS.Instruct_place_other__c.addError('带教地点选择其它时，请填写带教地点（其它)！');
            }
            //if(string.isblank(temIS.IS.Instruct_place__c)){
            //  hasError = true;
            //temIS.IS.Instruct_place__c.addError('请填写带教地点！');
            //}else if('其它'.equals(temIS.IS.Instruct_place__c)
            //  && string.isblank(temIS.IS.Instruct_place_other__c)){
            // hasError = true;
            //temIS.IS.Instruct_place_other__c.addError('带教地点选择其它时，请填写带教地点（其它)！');
            //}
            if (string.isblank(temIS.IS.Instructed_staff_feedback__c)) {
                hasError = true;
                temIS.IS.Instructed_staff_feedback__c.addError('请填写被带教者反馈！');

            }
            if (string.isblank(temIS.IS.Instruct_staff_feedback__c)) {
                hasError = true;
                temIS.IS.Instruct_staff_feedback__c.addError('请填写带教者意见建议！');

            }
            if (string.isblank(temIS.IS.Instruct_content_other__c)) {
                hasError = true;
                temIS.IS.Instruct_content_other__c.addError('请填写具体内容！');

            }

        }
        if (checkedISList.size() == 0 ) {
            hasError = true;
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Error, '请选择至少一位带教人员！'));


        }

        return hasError;
    }
    public Integer CheckedCnt {
        get {
            return checkedISList == null ? 0 : checkedISList.size();
        }
    }
    public Integer unCheckedCnt {
        get {
            return uncheckedISList == null ? 0 : uncheckedISList.size();
        }
    }
    public class InstructedstaffInfo {
        public Instructed_staff__c IS       {get; set;}
        public CampaignMember__c  CamMem    {get; set;}

        public Integer lineNo               {get; private set;}
        public Boolean rec_checkBox         {get; set;}
        public InstructedstaffInfo(Integer lineNo, Instructed_staff__c IS,
                                   CampaignMember__c  CamMem, boolean selectedLocal) {
            this.lineNo         = lineNo;
            this.IS             = IS;
            this.rec_checkBox   = selectedLocal;
            this.CamMem         = CamMem;
            


        }
        public InstructedstaffInfo(Integer lineNo, CampaignMember__c  CamMem) {
            this.lineNo         = lineNo;
            this.IS             = new Instructed_staff__c(ContactID__c = CamMem.Contact_ID__c);
            this.rec_checkBox   = false;
            this.CamMem         = CamMem;
        }
    }
}