public without sharing class AssessmentReportController {
    public String targetAssessmentReportId { get; private set; }
    public String targetCampaignId { get; private set; }
    public boolean ReadOnly { get; private set; }
    public AssessmentReport__c AssessmentReport {get; set;}
    public List<AssessmentReportStaffInfo> ARSInfoList {get; set;}
    public integer ASRRecordsNumber;
    public boolean hasError;
    public String ErrorMessages;
    //deloitte-zhj 20231114 PIPL还原
    //public String awsString{get; set;}
    //public String staticResource {get; set;}


    public AssessmentReportController() {
        this.ReadOnly = true;
        hasError = false;
        ErrorMessages = '';
    }
    public AssessmentReportController(ApexPages.StandardController controller) {
        this();
    }
    //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
    public PageReference init() {

        this.targetAssessmentReportId = ApexPages.currentPage().getParameters().get('id');
        this.targetCampaignId = ApexPages.currentPage().getParameters().get('camid');
        try {
            //打开现有授课报告
            if (!String.isBlank(this.targetAssessmentReportId)) {
                setCurrentAssessmentReport();
                if (this.AssessmentReport == null) {
                    throw new ControllerUtil.myException('无法打开现有授课/考核报告');
                    return null;
                }
                this.targetCampaignId = this.AssessmentReport.Campaign__c;

            }
            //新建授课报告
            else if (!String.isBlank(this.targetCampaignId)) {
                //HWAG-BDZ398 判断是否有权新建报告 start
                if (!AssessmentReport__c.sObjectType.getDescribe().isCreateable()) {
                    throw new ControllerUtil.myException('您没有权限新建授课/考核报告');
                    return null;
                }
                //HWAG-BDZ398 判断是否有权新建报告 end
                this.ReadOnly = false;
                this.AssessmentReport = new AssessmentReport__c();
                this.AssessmentReport.Campaign__c = targetCampaignId;
                setUpAssessmentReport();

            }
            //其他直接报错
            else {
                throw new ControllerUtil.myException('无法显示授课/考核报告');
                return null;
            }
            setCurrentAssessmentReportStaff();
            //deloitte-zhj 20231114 PIPL还原
            //staticResource = JSON.serialize(PIHelper.getPIIntegrationInfo('Contact'));
        } catch (Exception ex) {
            ApexPages.addMessages(ex);

        }

        return null;
    }

    @TestVisible private void setCurrentAssessmentReport() {
        if (!string.isblank(targetAssessmentReportId)) {
            List<AssessmentReport__c> amrList = [select id, Type__c, Report_Code__c, Name,
                                                 TeachingHourSelect__c, TeachingHour__c,
                                                 TeachingHourOther__c, Status__c,
                                                 AttendNumber__c,  AverageGrade__c,
                                                 TrainingLecturer1__c, TrainingLecturer1__r.name,
                                                 TrainingLecturer2__c, TrainingLecturer2__r.name,
                                                 TrainingLecturer3__c, TrainingLecturer3__r.name,
                                                 TrainingLecturer4__c, TrainingLecturer4__r.name,
                                                 TrainingLecturer5__c, TrainingLecturer5__r.name,
                                                 HomeworkFeedback__c,
                                                 TeacherFeedback__c, LectureFeedback__c,
                                                 GoodExample__c, TeachingContent__c,
                                                 TrainedStaffFeedback__c, AttendRate__c,
                                                 Campaign__c, AssessNext__c, TeachingDate__c
                                                 from AssessmentReport__c where id = : targetAssessmentReportId];
            if (amrList != null && amrList.size() > 0) {
                AssessmentReport = amrList[0];
            }
        }
    }

    public Boolean getInputdisabled() {
        return ReadOnly;
    }

    /*
        新建的授课报告
    */
    @TestVisible private void setUpAssessmentReport() {
        this.AssessmentReport.Status__c  = '草案中';
        list<AssessmentReport__c> ASRRecords =
            [select id,Campaign__r.OwnerID,Campaign__r.RecordTypeid,Campaign__r.Salesdepartment__c from AssessmentReport__c where Campaign__c = : targetCampaignId];
        Campaign temCam = [select id, name, TrainingCode__c,
                           Lesson1Date__c, Lesson2Date__c,
                           Lesson3Date__c, Lesson4Date__c,
                           Lesson5Date__c, Lesson6Date__c,
                           Lesson7Date__c, Lesson8Date__c,
                           ServiceDesignDep__c, JingliApprovalManager__c, BuchangApprovalManager__c, FinalExamDate__c,OwnerID,RecordTypeid,Salesdepartment__c 
                           from Campaign where id = : targetCampaignId];
        if (ASRRecords == null || temCam == null) {
            throw new ControllerUtil.myException('找不到对应的学会培训,无法保存！');
        }
        ASRRecordsNumber = ASRRecords.size() + 1;

        this.AssessmentReport.Name = temCam.Name + '第' + ASRRecordsNumber + '次报告';
        // 修改带教报告经理等取值逻辑  2020/07/28   精琢技术 start
        if(temCam != null){
            setInsertOwner(temCam);
        }
        //注释原来赋值逻辑
        // this.AssessmentReport.ServiceDesignDep__c = temCam.ServiceDesignDep__c;
        // this.AssessmentReport.JingliApprovalManager__c = temCam.JingliApprovalManager__c;
        // this.AssessmentReport.BuchangApprovalManager__c = temCam.BuchangApprovalManager__c;
        if (AssessmentReport.TeachingDate__c == null && ASRRecordsNumber <= 9) {
            if ( ASRRecordsNumber <= 8 && temCam.get('Lesson' + ASRRecordsNumber + 'Date__c') != null) {
                this.AssessmentReport.TeachingDate__c = Date.valueOf(temCam.get('Lesson' + ASRRecordsNumber + 'Date__c'));
            } else {
                this.AssessmentReport.TeachingDate__c = Date.valueOf(temCam.get('FinalExamDate__c'));
            }
            integer nextASRRecordsNumber = ASRRecordsNumber + 1 ;

        }
        if (!String.isBlank(AssessmentReport.Type__c)) {

            if (AssessmentReport.Type__c.equals('考核')) {
                this.AssessmentReport.Name = temCam.Name + '考核报告';
            }
            string reportType = AssessmentReport.Type__c == '授课' ? 'SK' : 'KH';
            if (ASRRecordsNumber < 10) {
                this.AssessmentReport.Report_Code__c = temCam.TrainingCode__c + '-' + reportType + '00' + ASRRecordsNumber;
            } else {
                this.AssessmentReport.Report_Code__c = temCam.TrainingCode__c + '-' + reportType + '0' + ASRRecordsNumber;
            }
        }
        this.AssessmentReport.Campaign__c = this.targetCampaignId;
    }

    //LJPH-BRW8SH 精琢技术 wql 2020/08/18 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.AssessmentReport.JingliApprovalManager__c  = userMap.get(temCam.OwnerID).SalesManager__c;
                    this.AssessmentReport.BuchangApprovalManager__c = userMap.get(temCam.OwnerID).BuchangApprovalManagerSales__c;
                    
            }else {
                    this.AssessmentReport.JingliApprovalManager__c = userMap.get(temCam.OwnerID).JingliApprovalManager__c == null ? temCam.OwnerID :  userMap.get(temCam.OwnerID).JingliApprovalManager__c;
                    this.AssessmentReport.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.AssessmentReport.ServiceDesignDep__c = System.Label.ServiceDesignDep_NC;
                    }
                    if (temCam.Salesdepartment__c != null && temCam.Salesdepartment__c.equals('2.东北')) {
                        this.AssessmentReport.ServiceDesignDep__c = System.Label.ServiceDesignDep_NE;
                    }
                    if (temCam.Salesdepartment__c != null && temCam.Salesdepartment__c.equals('3.西北')) {
                        this.AssessmentReport.ServiceDesignDep__c = System.Label.ServiceDesignDep_NW;
                    }
                    if (temCam.Salesdepartment__c != null && temCam.Salesdepartment__c.equals('4.西南')) {
                        this.AssessmentReport.ServiceDesignDep__c = System.Label.ServiceDesignDep_SW;
                    }
                    if (temCam.Salesdepartment__c != null && temCam.Salesdepartment__c.equals('5.华东')) {
                        this.AssessmentReport.ServiceDesignDep__c = System.Label.ServiceDesignDep_EC;
                    }
                    if (temCam.Salesdepartment__c != null && temCam.Salesdepartment__c.equals('6.华南')) {
                        this.AssessmentReport.ServiceDesignDep__c = System.Label.ServiceDesignDep_SC;
                    } else {
                        this.AssessmentReport.ServiceDesignDep__c = System.Label.ServiceDesignDep_NC;
                    }
                  }
        }
        //LJPH-BRW8SH 精琢技术 wql 2020/08/18 start
        
        // Campaign temCam = [select id, name, TrainingCode__c, ServiceDesignDep__c,
        //                    JingliApprovalManager__c, BuchangApprovalManager__c
        //                    from Campaign where id = : targetCampaignId];
        // this.AssessmentReport.ServiceDesignDep__c = temCam.ServiceDesignDep__c;
        // this.AssessmentReport.JingliApprovalManager__c = temCam.JingliApprovalManager__c;
        // this.AssessmentReport.BuchangApprovalManager__c = temCam.BuchangApprovalManager__c;
    }


    @TestVisible private void setCurrentAssessmentReportStaff() {
        List<AssessmentReportStaffInfo> TempARSInfoList = new List<AssessmentReportStaffInfo>();
        list<CampaignMember__c> CMlist = [
                                             SELECT Id, Name, Department_ID__c,
                                             Contact_ID__c, Contact_ID__r.Name,
                                             Contact_ID__r.AWS_Data_Id__c,
                                             dept__c, State__c, City__c
                                             FROM CampaignMember__c
                                             where Campaign__c = : AssessmentReport.Campaign__c
                                         ];
        List<AssessmentReportStaff__c> tempAmrsList = [select id, Department__r.Name,
                                       Name, State__c, City__c,
                                       dept__c, AttendStatus__c, AttendRate__c, Grade__c,
                                       HomeworkFeedback__c, comment__c, AssessmentReport__c,
                                       CampaignMember__c, CampaignMember__r.Contact_ID__c
                                       from AssessmentReportStaff__c
                                       where AssessmentReport__c = :targetAssessmentReportId];
        Map <id, AssessmentReportStaff__c> ARSMap = new Map <id, AssessmentReportStaff__c>();

        for (AssessmentReportStaff__c tempARS : tempAmrsList) {
            ARSMap.put(tempARS.CampaignMember__c, tempARS);
        }
        
        for (CampaignMember__c tempCM : CMlist) {
            if (ARSMap.containsKey(tempCM.id)) {
                TempARSInfoList.add(
                    new AssessmentReportStaffInfo(
                        ARSMap.get(tempCM.id),
                        tempCM)
                );
            } else {
                TempARSInfoList.add(
                    new AssessmentReportStaffInfo(
                        new AssessmentReportStaff__c(
                            Name = tempCM.Contact_ID__r.Name,
                            Contact__c = tempCM.Contact_ID__c,
                            CampaignMember__c = tempCM.id,
                            Department__c = tempCM.Department_ID__c
                        ),
                        tempCM)
                );
            }
        }
        ARSInfoList = TempARSInfoList.clone();
        //deloitte-zhj 20231114 PIPL还原
        //awsString = JSON.serialize(ARSInfoList);
        
    }
    public PageReference Submit() {
        system.debug('Submit start:');
        hasError = false;
        ErrorMessages = '';
        Savepoint sp = Database.setSavepoint();

        try {
            CheckSaveInput();
            if (hasError) {
                system.debug(ErrorMessages);
                if (!String.isBlank(ErrorMessages)) {
                    string[] ErrorMessageGroup = ErrorMessages.split('\\|\\|\\|\\|\\|');
                    for (integer i = 0; i < ErrorMessageGroup.size(); i++ ) {
                        ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Error, ErrorMessageGroup[i]));
                    }
                }
                return null;
            }
            if (syncAssessmentReport()) {
                ReadOnly = true;
                Approval.ProcessSubmitRequest psr = new Approval.ProcessSubmitRequest();
                psr.setObjectId(this.AssessmentReport.id);
                Approval.ProcessResult submitResult = Approval.process(psr);
                setCurrentAssessmentReport();
                setCurrentAssessmentReportStaff();

            }
        } catch (DMLException ex) {
            Database.rollback(sp);
            ApexPages.addMessages(ex);
        } catch (Exception ex) {
            Database.rollback(sp);
            ApexPages.addMessages(ex);
        }
        ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO, '提交成功'));
        system.debug('Submit End');

        return null;
    }
    public PageReference save() {
        system.debug('Save start:');
        hasError = false;
        ErrorMessages = '';
        CheckSaveInput();
        if (hasError) {
            system.debug(ErrorMessages);
            if (!String.isBlank(ErrorMessages)) {
                string[] ErrorMessageGroup = ErrorMessages.split('\\|\\|\\|\\|\\|');
                for (integer i = 0; i < ErrorMessageGroup.size(); i++ ) {
                    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Error, ErrorMessageGroup[i]));
                }
            }
            return null;
        }
        if (syncAssessmentReport()) {
            setCurrentAssessmentReport();
            setCurrentAssessmentReportStaff();
            ReadOnly = true;

            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO, '保存好了！'));
        }
        system.debug('Save end');

        return null;
    }

    /** 保存返回 **/
    public PageReference saveAndCancel () {
        system.debug('Save start:');
        hasError = false;
        ErrorMessages = '';
        CheckSaveInput();
        if (hasError) {
            system.debug(ErrorMessages);
            if (!String.isBlank(ErrorMessages)) {
                string[] ErrorMessageGroup = ErrorMessages.split('\\|\\|\\|\\|\\|');
                for (integer i = 0; i < ErrorMessageGroup.size(); i++ ) {
                    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Error, ErrorMessageGroup[i]));
                }
            }
            return null;
        }

        if (syncAssessmentReport()) {
            PageReference ret = null;
            if (this.targetCampaignId != null) {
                ret = new PageReference('/' + this.targetCampaignId);
            }
            return ret;
        }
        return null;
    }

    @TestVisible private Boolean CheckSaveInput() {
        if (string.isblank(AssessmentReport.Type__c)) {
            hasError = true;
            AssessmentReport.Type__c.addError('请选择报告类型！');
            //ErrorMessages = '请选择报告类型！';
        }
        if (string.isblank(AssessmentReport.TeachingHourSelect__c)) {
            hasError = true;
            AssessmentReport.TeachingHourSelect__c.addError('请选择授课课时！');
            if (''.equals(ErrorMessages)) {

                //ErrorMessages = '请选择授课课时！';
            } else {
                //ErrorMessages += '||||| 请选择授课课时！';
            }
        } else if ('其他'.equals(AssessmentReport.TeachingHourSelect__c)
                   && (AssessmentReport.TeachingHourOther__c == null
                       // || string.isblank(AssessmentReport.TeachingHourOther__c)
                      )) {
            hasError = true;
            AssessmentReport.TeachingHourOther__c.addError('授课课时选择其他时，请输入授课课时(其他)！');
            if (''.equals(ErrorMessages)) {
                //ErrorMessages = '授课课时选择其他时，请选择授课课时(其他)！';
            } else {
                //ErrorMessages += '||||| 授课课时选择其他时，请选择授课课时(其他)！';
            }
        }
        system.debug('AssessmentReport.TeachingHourOther__c:' + AssessmentReport.TeachingHourOther__c);
        if (string.isblank(AssessmentReport.TrainedStaffFeedback__c)) {
            hasError = true;
            if (''.equals(ErrorMessages)) {
                ErrorMessages = '请填写培训人员反馈信息汇总！';
            } else {
                ErrorMessages += '||||| 请填写培训人员反馈信息汇总！';
            }
        }
        if (string.isblank(AssessmentReport.HomeworkFeedback__c)) {
            hasError = true;
            if (''.equals(ErrorMessages)) {
                ErrorMessages = '请填写课后作业、复习相关情况汇总！';
            } else {
                ErrorMessages += '||||| 请填写课后作业、复习相关情况汇总！';
            }
        }
        if (string.isblank(AssessmentReport.TeacherFeedback__c)) {
            hasError = true;
            if (''.equals(ErrorMessages)) {
                ErrorMessages = '请填写讲师对活动综合报告/感想！';
            } else {
                ErrorMessages += '||||| 请填写讲师对活动综合报告/感想！';
            }
        }
        if (string.isblank(AssessmentReport.LectureFeedback__c)) {
            hasError = true;
            if (''.equals(ErrorMessages)) {
                ErrorMessages = '请填写课件\\课程设置相关反馈内容(修改意见、亮点等)!';
            } else {
                ErrorMessages += '||||| 请填写课件\\课程设置相关反馈内容(修改意见、亮点等)!';
            }
        }
        if (string.isblank(AssessmentReport.GoodExample__c)) {
            hasError = true;
            if (''.equals(ErrorMessages)) {
                ErrorMessages = '请填写本次活动好的例子&需要改善的地方!';
            } else {
                ErrorMessages += '||||| 请填写本次活动好的例子&需要改善的地方!';
            }
        }
        for (AssessmentReportStaffInfo tempARS : ARSInfoList) {

            if (string.isblank(tempARS.ARS.AttendStatus__c)) {
                hasError = true;
                tempARS.ARS.AttendStatus__c.addError('请填写出勤情况！');
                if (''.equals(ErrorMessages)) {
                    //ErrorMessages = '请选择' + tempARS.CamMem.Contact_ID__r.Name + '的出勤情况！';
                } else {
                    //ErrorMessages += '||||| 请选择' + tempARS.CamMem.Contact_ID__r.Name + '的出勤情况！';
                }
            }

            else if (tempARS.ARS.AttendStatus__c.equals('出勤') || tempARS.ARS.AttendStatus__c.equals('迟到') ) {
                if (string.isblank(tempARS.ARS.AttendRate__c)) {
                    hasError = true;
                    tempARS.ARS.AttendRate__c.addError('请选择课堂参与度！');
                    /*
                    if (''.equals(ErrorMessages)) {
                        ErrorMessages = '请选择' + tempARS.CamMem.Contact_ID__r.Name + '的课堂参与度！';
                    } else {
                        ErrorMessages += '||||| 请选择' + tempARS.CamMem.Contact_ID__r.Name + '的课堂参与度！';
                    }
                    */
                }
                if (string.isblank(tempARS.ARS.HomeworkFeedback__c)) {
                    hasError = true;
                    tempARS.ARS.HomeworkFeedback__c.addError('请选择作业完成情况！');
                    /*
                    if (''.equals(ErrorMessages)) {
                        ErrorMessages = '请选择' + tempARS.CamMem.Contact_ID__r.Name + '的课堂参与度！';
                    } else {
                        ErrorMessages += '||||| 请选择' + tempARS.CamMem.Contact_ID__r.Name + '的课堂参与度！';
                    }
                    */
                }
            }


        }
        return true;
    }

    @TestVisible private Boolean syncAssessmentReport() {
        system.debug('syncInstructReport start');
        Savepoint sp = Database.setSavepoint();

        try {
            if (AssessmentReport.id == null)
                setUpAssessmentReport();
            //LJPH-BRW8SH 精琢技术 wql 2020/08/18 start
            Campaign temCam = [select id, name, TrainingCode__c,
                           Lesson1Date__c, Lesson2Date__c,
                           Lesson3Date__c, Lesson4Date__c,
                           Lesson5Date__c, Lesson6Date__c,
                           Lesson7Date__c, Lesson8Date__c,
                           ServiceDesignDep__c, JingliApprovalManager__c, BuchangApprovalManager__c, FinalExamDate__c,OwnerID,RecordTypeid,Salesdepartment__c 
                           from Campaign where id = : targetCampaignId];
            if(temCam != null){
                setInsertOwner(temCam);
            }
            //LJPH-BRW8SH 精琢技术 wql 2020/08/18 end

            upsert AssessmentReport;
            this.targetAssessmentReportId = AssessmentReport.id;
            //删掉所有带教报告人员
            list<AssessmentReportStaff__c> deleteARS = [select id from AssessmentReportStaff__c
                    where AssessmentReport__c = : targetAssessmentReportId];
            if (deleteARS.size() > 0) {
                delete deleteARS;
            }
            list<AssessmentReportStaff__c> insertARS = new list<AssessmentReportStaff__c>();
            for (AssessmentReportStaffInfo temARS : ARSInfoList) {
                if (temARS.ARS.AssessmentReport__c == null) {
                    temARS.ARS.AssessmentReport__c = targetAssessmentReportId;
                }
                temARS.ARS.id = null;
                insertARS.add(temARS.ARS);

            }
            if (insertARS.size() > 0) {
                insert insertARS;
            }

            return true;
        } catch (Exception ex) {
            Database.rollback(sp);
            ApexPages.addMessages(ex);
        }
        return false;
    }
    public PageReference EditRecord() {
        ReadOnly = !ReadOnly;
        this.AssessmentReport.Status__c  = '草案中';
        return null;
    }

    public PageReference cancel() {
        PageReference ret = null;
        if (this.targetCampaignId != null) {
            ret = new PageReference('/' + this.targetCampaignId);
        }
        return ret;
    }



    public class AssessmentReportStaffInfo {
        public AssessmentReportStaff__c ARS         {get; set;}
        public CampaignMember__c  CamMem            {get; set;}

        public Integer lineNo               {get; private set;}
        public Boolean rec_checkBox         {get; set;}
        public AssessmentReportStaffInfo(Integer lineNo, AssessmentReportStaff__c ARS,
                                         CampaignMember__c  CamMem, boolean selectedLocal) {
            this.lineNo         = lineNo;
            this.ARS            = ARS;
            this.rec_checkBox   = selectedLocal;
            this.CamMem         = CamMem;
        }
        public AssessmentReportStaffInfo(AssessmentReportStaff__c ARS, CampaignMember__c  CamMem) {
            this.ARS            = ARS;
            this.CamMem         = CamMem;
        }
        public AssessmentReportStaffInfo(Integer lineNo, CampaignMember__c  CamMem) {
            this.lineNo         = lineNo;
            this.ARS            = new AssessmentReportStaff__c();
            this.rec_checkBox   = false;
            this.CamMem         = CamMem;
        }
    }
}