/**
 * 安全教育考试系统 - Vue实例
 */
new Vue({
  el: '#app',
  data: function() {
    return {
      activePage: 'workbench',
      activeRole: 'newGraduate',
      activeResourceTab: '化学类',
      activeVideoTab: '化学类',
      videoSearch: '',
      videoPage: 1,
      // 弹窗
      showBindDialog: false,
      showNoticeDetail: false,
      labSearchKey: '',
      selectedLabId: '',
      noLabMode: false,
      noticeChecked: false,
      bindReason: '',
      bindDialogMode: 'graduate',
      labFilteredList: [],
      // 数据
      menuItems: menuItems,
      roleButtons: roleButtons,
      resourceTabs: resourceTabs,
      videoTabs: videoTabs,
      rolesData: JSON.parse(JSON.stringify(roleProfiles)),
      prdContent: '',
      // 数据统计
      statisticsData: statisticsData,
      statsTopTab: 'current',
      statsExamType: 'graduate',
      examFilterCollege: '',
      examFilterExamType: '',
      labFilterCollege: '',
      labFilterLevel: '',
      hoursFilterType: '',
      hoursFilterCollege: '',
      hoursFilterGrade: '',
      hoursFilterKey: '',
      hoursPage: 1,
      hoursPageSize: 8,
      // 人员审批
      approvalList: JSON.parse(JSON.stringify(approvalData)),
      approvalFilter: 'all',
      showRejectDialog: false,
      rejectReasonInput: '',
      rejectingItem: null,
      // 配置表
      configTableData: [
        { level: 'Ⅰ', levelLabel: 'Ⅰ级（重大风险）', firstYear: levelHoursConfig['Ⅰ'].firstYear, annual: levelHoursConfig['Ⅰ'].annual },
        { level: 'Ⅱ', levelLabel: 'Ⅱ级（高风险）', firstYear: levelHoursConfig['Ⅱ'].firstYear, annual: levelHoursConfig['Ⅱ'].annual },
        { level: 'Ⅲ', levelLabel: 'Ⅲ级（中风险）', firstYear: levelHoursConfig['Ⅲ'].firstYear, annual: levelHoursConfig['Ⅲ'].annual },
        { level: 'Ⅳ', levelLabel: 'Ⅳ级（低风险）', firstYear: levelHoursConfig['Ⅳ'].firstYear, annual: levelHoursConfig['Ⅳ'].annual }
      ],
      // 业务流程数据
      flowData: [
        { role: '新入学研究生（绑定实验室）', steps: [
          { text: '首次进入系统', type: 'start' },
          { text: '弹出绑定实验室弹窗', condition: '搜索并选择实验室' },
          { text: '勾选须知并提交绑定申请' },
          { text: '实验室负责人审批', type: 'decision', condition: '7天未处理自动通过' },
          { text: '审批通过，确定学时要求（按实验室分级）' },
          { text: '完成准入学时学习（Ⅰ:24h / Ⅱ:16h / Ⅲ:8h / Ⅳ:4h）' },
          { text: '参加分级考试（内容匹配实验室分级分类）' },
          { text: '通过考试，获取准入证书', type: 'end' }
        ]},
        { role: '新入学研究生（无需进入实验室）', steps: [
          { text: '首次进入系统', type: 'start' },
          { text: '弹出绑定实验室弹窗' },
          { text: '选择"无需进入实验室"', condition: '人文/体育等学院' },
          { text: '完成4学时安全通识学习' },
          { text: '参加应知应会考试' },
          { text: '通过考试，获取证书', type: 'end' }
        ]},
        { role: '研二三（在读研究生）', steps: [
          { text: '新学年开始，进入系统', type: 'start' },
          { text: '查看年度学时要求（按实验室分级：Ⅰ:8h / Ⅱ:4h / Ⅲ:2h / Ⅳ:0h）' },
          { text: '完成年度安全学时学习' },
          { text: '参加应知应会考试', condition: '学时完成后解锁' },
          { text: '通过考试，更新准入证书', type: 'end' }
        ]},
        { role: '新入学本科生', steps: [
          { text: '首次进入系统', type: 'start' },
          { text: '完成4学时安全通识学习' },
          { text: '参加新生入学考试', condition: '学时完成后解锁' },
          { text: '通过新生入学考试，获取证书', type: 'decision' },
          { text: '（可选）点击绑定实验室', condition: '毕设/科创等需求' },
          { text: '填写进入原因，提交绑定申请' },
          { text: '审批通过，完成对应分级学时' },
          { text: '参加分级考试并通过', type: 'end' }
        ]},
        { role: '本科二三四（在读本科生）', steps: [
          { text: '新学年开始，进入系统', type: 'start' },
          { text: '无学时要求，直接参加考试' },
          { text: '参加应知应会考试' },
          { text: '通过考试，获取年度证书', type: 'end' }
        ]},
        { role: '新入职教职工', steps: [
          { text: '入职后首次进入系统', type: 'start' },
          { text: '完成4学时安全通识学习' },
          { text: '参加应知应会考试', condition: '学时完成后解锁' },
          { text: '通过考试，获取证书', type: 'end' }
        ]},
        { role: '存量教职工（第二年起）', steps: [
          { text: '新学年开始，进入系统', type: 'start' },
          { text: '无学时要求，直接参加考试' },
          { text: '参加应知应会考试' },
          { text: '通过考试，获取年度证书', type: 'end' }
        ]}
      ]
    };
  },
  computed: {
    currentRole: function() { return this.rolesData[this.activeRole]; },
    visibleMenuItems: function() {
      var isStaff = this.activeRole === 'newStaff' || this.activeRole === 'existingStaff';
      return this.menuItems.filter(function(item) {
        if (item.staffOnly) return isStaff;
        return true;
      });
    },
    filteredApprovalData: function() {
      var filter = this.approvalFilter;
      if (filter === 'all') return this.approvalList;
      return this.approvalList.filter(function(d) { return d.status === filter; });
    },
    currentPageLabel: function() {
      var p = this.activePage;
      var item = this.menuItems.find(function(m) { return m.key === p; });
      return item ? item.label : '';
    },
    hoursPercentage: function() {
      var r = this.currentRole;
      if (!r.requiredHours) return 0;
      return Math.min(100, Math.round((r.completedHours / r.requiredHours) * 100));
    },
    isStaffRole: function() {
      return this.activeRole === 'newStaff' || this.activeRole === 'existingStaff';
    },
    collegeTasks: function() {
      // 只显示学院/人事处下发的学习任务
      return (this.currentRole.tasks || []).filter(function(t) {
        return t.note && (t.note.indexOf('下发') !== -1);
      });
    },
    bindingStatusText: function() {
      var s = this.currentRole.bindingStatus;
      var map = { unbound: '待绑定', pending: '审批中', approved: '已通过', rejected: '已驳回', nolab: '无需进入实验室', none: '不适用' };
      return map[s] || s;
    },
    resolvedResourceTab: function() {
      var r = this.currentRole;
      if (r.resourceType === 'lab-bindable' && r.lab) return r.lab.category;
      return '应知应会通识';
    },
    examChipClass: function() {
      var s = this.currentRole.examStatus;
      if (s === '已通过') return 'success';
      if (s === '未开始' || s === '待绑定后确认') return 'locked';
      return 'pending';
    },
    certChipClass: function() {
      var s = this.currentRole.certificateStatus;
      if (s.indexOf('已获') !== -1) return 'success';
      return 'locked';
    },
    approvalChipClass: function() {
      var s = this.currentRole.bindingStatus;
      if (s === 'approved') return 'success';
      if (s === 'pending') return 'pending';
      if (s === 'rejected') return 'danger';
      return 'locked';
    },
    examCardDesc: function() {
      var r = this.currentRole;
      if (r.requiredHours > 0 && !r.examUnlocked) return '完成 ' + r.requiredHours + ' 学时后开放考试';
      if (r.examStatus === '已通过') return '已通过，成绩：' + r.examScore + '分';
      return '满足前置条件后可参加考试';
    },
    filteredLabs: function() { return this.labFilteredList; },
    selectedLabDetail: function() {
      if (!this.selectedLabId) return null;
      var lab = labList.find(function(l) { return l.id === this.selectedLabId; }.bind(this));
      if (!lab) return null;
      var name = lab.director.replace(/\*+/g, '');
      var masked = name.length === 2 ? name[0] + '*' : name.length >= 3 ? name[0] + '*' + name.slice(2) : name;
      return Object.assign({}, lab, { directorMasked: masked });
    },
    canBind: function() {
      if (!this.noticeChecked) return false;
      if (this.bindDialogMode === 'graduate') { if (!this.noLabMode && !this.selectedLabId) return false; }
      if (this.bindDialogMode === 'undergraduate') { if (!this.selectedLabId || !this.bindReason.trim()) return false; }
      return true;
    },
    filteredVideos: function() {
      var videos = videoData[this.activeVideoTab] || [];
      var s = this.videoSearch.toLowerCase();
      if (!s) return videos;
      return videos.filter(function(v) { return v.title.toLowerCase().includes(s); });
    },
    paginatedVideos: function() {
      var start = (this.videoPage - 1) * 4;
      return this.filteredVideos.slice(start, start + 4);
    },
    currentExamData: function() {
      return statisticsData.undergraduateExam.map(function(d) {
        var total = d.freshTotal + d.seniorTotal;
        var passed = d.freshPassed + d.seniorPassed;
        return { college: d.college, total: total, passed: passed, failed: d.freshFailed + d.seniorFailed, absent: d.freshAbsent + d.seniorAbsent, rate: Math.round(passed / total * 100) + '%' };
      });
    },
    undergraduateDetailData: function() {
      var rows = [];
      statisticsData.undergraduateExam.forEach(function(d) {
        var freshRate = Math.round(d.freshPassed / d.freshTotal * 100) + '%';
        var seniorRate = Math.round(d.seniorPassed / d.seniorTotal * 100) + '%';
        var allTotal = d.freshTotal + d.seniorTotal;
        var allPassed = d.freshPassed + d.seniorPassed;
        var allFailed = d.freshFailed + d.seniorFailed;
        var allAbsent = d.freshAbsent + d.seniorAbsent;
        var allRate = Math.round(allPassed / allTotal * 100) + '%';
        rows.push({ college: d.college, examType: '新生入学考试', total: d.freshTotal, passed: d.freshPassed, failed: d.freshFailed, absent: d.freshAbsent, rate: freshRate });
        rows.push({ college: d.college, examType: '应知应会考试', total: d.seniorTotal, passed: d.seniorPassed, failed: d.seniorFailed, absent: d.seniorAbsent, rate: seniorRate });
        rows.push({ college: d.college, examType: '汇总', total: allTotal, passed: allPassed, failed: allFailed, absent: allAbsent, rate: allRate });
      });
      return rows;
    },
    graduateDetailData: function() {
      var rows = [];
      statisticsData.graduateExamDetail.forEach(function(d) {
        var newRate = Math.round(d.newPassed / d.newTotal * 100) + '%';
        var seniorRate = Math.round(d.seniorPassed / d.seniorTotal * 100) + '%';
        var allTotal = d.newTotal + d.seniorTotal;
        var allPassed = d.newPassed + d.seniorPassed;
        var allFailed = d.newFailed + d.seniorFailed;
        var allAbsent = d.newAbsent + d.seniorAbsent;
        var allRate = Math.round(allPassed / allTotal * 100) + '%';
        rows.push({ college: d.college, examType: '新生分级考试', total: d.newTotal, passed: d.newPassed, failed: d.newFailed, absent: d.newAbsent, rate: newRate });
        rows.push({ college: d.college, examType: '应知应会考试', total: d.seniorTotal, passed: d.seniorPassed, failed: d.seniorFailed, absent: d.seniorAbsent, rate: seniorRate });
        rows.push({ college: d.college, examType: '汇总', total: allTotal, passed: allPassed, failed: allFailed, absent: allAbsent, rate: allRate });
      });
      return rows;
    },
    labCollegeData: function() {
      return statisticsData.labCollegeStats.map(function(d) {
        return Object.assign({}, d, { totalCount: d.level1 + d.level2 + d.level3 + d.level4 });
      });
    },
    filteredGraduateData: function() {
      var data = this.graduateDetailData;
      var college = this.examFilterCollege;
      var examType = this.examFilterExamType;
      if (college) data = data.filter(function(d) { return d.college === college; });
      if (examType) data = data.filter(function(d) { return d.examType === examType; });
      return data;
    },
    filteredUndergraduateData: function() {
      var data = this.undergraduateDetailData;
      var college = this.examFilterCollege;
      var examType = this.examFilterExamType;
      if (college) data = data.filter(function(d) { return d.college === college; });
      if (examType) data = data.filter(function(d) { return d.examType === examType; });
      return data;
    },
    filteredLabCollegeData: function() {
      var data = this.labCollegeData;
      var college = this.labFilterCollege;
      var level = this.labFilterLevel;
      if (college) data = data.filter(function(d) { return d.college === college; });
      if (level) {
        var key = { 'Ⅰ': 'level1', 'Ⅱ': 'level2', 'Ⅲ': 'level3', 'Ⅳ': 'level4' }[level];
        if (key) data = data.filter(function(d) { return d[key] > 0; });
      }
      return data;
    },
    labLevelTableData: function() {
      return statisticsData.labLevelStats;
    },
    hoursDetailFiltered: function() {
      var data = statisticsData.studyDetail;
      var type = this.hoursFilterType;
      var college = this.hoursFilterCollege;
      var grade = this.hoursFilterGrade;
      var key = this.hoursFilterKey.toLowerCase();
      if (type) data = data.filter(function(d) { return d.type === type; });
      if (college) data = data.filter(function(d) { return d.college === college; });
      if (grade) data = data.filter(function(d) { return d.grade === grade; });
      if (key) data = data.filter(function(d) { return d.name.toLowerCase().includes(key) || d.code.toLowerCase().includes(key); });
      return data;
    },
    gradeOptions: function() {
      var grades = {};
      statisticsData.studyDetail.forEach(function(d) { grades[d.grade] = true; });
      return Object.keys(grades).sort();
    },
    filteredHoursDetail: function() {
      var start = (this.hoursPage - 1) * this.hoursPageSize;
      return this.hoursDetailFiltered.slice(start, start + this.hoursPageSize);
    }
  },
  methods: {
    switchRole: function(key) {
      this.activeRole = key;
      if (key === 'newGraduate' && this.rolesData.newGraduate.bindingStatus === 'unbound') {
        this.openBindDialog('graduate');
      }
    },
    openBindDialog: function(mode) {
      this.bindDialogMode = mode || 'graduate';
      this.resetBindForm();
      this.showBindDialog = true;
    },
    labFilterMethod: function(query) {
      if (!query) { this.labFilteredList = []; return; }
      var key = query.toLowerCase();
      this.labFilteredList = labList.filter(function(lab) {
        return lab.name.toLowerCase().includes(key) || lab.room.toLowerCase().includes(key) ||
               lab.building.toLowerCase().includes(key) || lab.college.toLowerCase().includes(key);
      });
    },
    onLabSelect: function(labId) { if (labId) this.noLabMode = false; },
    levelTagType: function(level) {
      return { 'Ⅰ': 'danger', 'Ⅱ': 'warning', 'Ⅲ': '', 'Ⅳ': '' }[level] || '';
    },
    levelClass: function(level) {
      return { 'Ⅰ': 'level-i', 'Ⅱ': 'level-ii', 'Ⅲ': 'level-iii', 'Ⅳ': 'level-iv' }[level] || '';
    },
    simulatePassExam: function() {
      var role = this.rolesData[this.activeRole];
      role.examStatus = '已通过';
      role.examScore = Math.floor(Math.random() * 20) + 80;
      role.certificateStatus = '已获得';
      this.$message.success('考试通过！成绩：' + role.examScore + '分');
      // 本科生通过新生入学考试后开放绑定实验室
      if (this.activeRole === 'newUndergraduate') {
        role.bindingStatus = 'unbound'; // 从none变为unbound，允许绑定
        this.$notify({ title: '提示', message: '恭喜通过新生入学考试！如需进入实验室开展科研，请点击"绑定实验室"按钮。', type: 'success', duration: 5000 });
      }
    },
    confirmBind: function() {
      var role = this.rolesData[this.activeRole];
      if (this.noLabMode && this.bindDialogMode === 'graduate') {
        role.bindingStatus = 'nolab';
        role.requiredHours = 4;
        role.lab = null;
        role.examType = '应知应会考试';
        role.examStatus = '未开始';
        role.tasks = [
          { title: '完成安全通识学习', note: '0 / 4 学时', status: 'in-progress' },
          { title: '通过应知应会考试', note: '完成学时后解锁', status: 'locked' }
        ];
      } else {
        var lab = labList.find(function(l) { return l.id === this.selectedLabId; }.bind(this));
        if (lab) {
          role.bindingStatus = 'pending'; // 提交后进入审批中
          role.lab = JSON.parse(JSON.stringify(lab));
          var cfg = this.configTableData.find(function(c) { return c.level === lab.level; });
          role.requiredHours = cfg ? (role.isFirstYear ? cfg.firstYear : cfg.annual) : 8;
          role.examStatus = '未开始';
          if (this.bindDialogMode === 'undergraduate') {
            role.examType = '分级考试';
          }
          // 更新任务
          var bindTask = role.tasks.find(function(t) { return t.title.indexOf('绑定') !== -1; });
          if (bindTask) { bindTask.note = '已提交，审批中'; bindTask.status = 'pending'; }
          var hoursTask = role.tasks.find(function(t) { return t.title.indexOf('学时') !== -1; });
          if (hoursTask) { hoursTask.note = '0 / ' + role.requiredHours + ' 学时'; hoursTask.status = 'in-progress'; }
        }
      }
      this.showBindDialog = false;
      this.resetBindForm();
      this.$message.success('已提交绑定申请！');
      // 模拟3秒后审批通过
      var self = this;
      setTimeout(function() {
        if (role.bindingStatus === 'pending') {
          role.bindingStatus = 'approved';
          var t = role.tasks.find(function(t) { return t.title.indexOf('绑定') !== -1; });
          if (t) { t.note = '审批通过'; t.status = 'in-progress'; }
          self.$notify({ title: '审批通知', message: '实验室绑定已通过审批！', type: 'success' });
        }
      }, 3000);
    },
    // 模拟审批操作
    simulateApproval: function(status) {
      var role = this.currentRole;
      role.bindingStatus = status;
      if (status === 'rejected') {
        this.$message.warning('绑定申请已被驳回');
      } else {
        this.$message.success('绑定申请已通过');
      }
    },
    resetBindForm: function() {
      this.labSearchKey = ''; this.selectedLabId = ''; this.noLabMode = false;
      this.noticeChecked = false; this.bindReason = ''; this.labFilteredList = [];
    },
    saveConfig: function() {
      var self = this;
      this.configTableData.forEach(function(item) {
        levelHoursConfig[item.level] = { firstYear: item.firstYear, annual: item.annual };
      });
      // 联动更新已绑定实验室的角色学时
      Object.keys(this.rolesData).forEach(function(key) {
        var role = self.rolesData[key];
        if (role.lab && role.lab.level) {
          var cfg = levelHoursConfig[role.lab.level];
          role.requiredHours = role.isFirstYear ? cfg.firstYear : cfg.annual;
        }
      });
      this.$message.success('配置保存成功，已联动更新角色学时要求');
    },
    getResourceDocs: function(tab) { return (resourceData[tab] && resourceData[tab].docs) || []; },
    getResourceQuestions: function(tab) { return (resourceData[tab] && resourceData[tab].questions) || { total: 0, categories: [] }; },
    viewDocDetail: function(doc) { this.$message({ message: '正在打开：' + doc.title, type: 'info' }); },
    renderCharts: function() {},  // Charts removed in favor of record-list display
    renderStatsCharts: function() {
      if (this.activePage !== 'statistics') return;
      var self = this;
      this.$nextTick(function() {
        self.renderExamCharts();
        self.renderLabChart();
        self.renderHoursChart();
      });
    },
    renderExamCharts: function() {
      var barEl = this.$refs.examBarChart;
      var pieEl = this.$refs.examPieChart;
      if (!barEl || !pieEl) return;
      var data = this.statsExamType === 'graduate'
        ? statisticsData.graduateExamDetail.map(function(d) { return { college: d.college, passed: d.newPassed + d.seniorPassed, failed: d.newFailed + d.seniorFailed, absent: d.newAbsent + d.seniorAbsent }; })
        : statisticsData.undergraduateExam.map(function(d) { return { college: d.college, passed: d.freshPassed + d.seniorPassed, failed: d.freshFailed + d.seniorFailed, absent: d.freshAbsent + d.seniorAbsent }; });
      var colleges = data.map(function(d) { return d.college.replace('学院',''); });
      var barChart = echarts.init(barEl);
      barChart.setOption({
        tooltip: { trigger: 'axis' },
        legend: { top: 0, textStyle: { fontSize: 11 } },
        grid: { top: 36, bottom: 30, left: 50, right: 10 },
        xAxis: { type: 'category', data: colleges, axisLabel: { fontSize: 10, rotate: 20 } },
        yAxis: { type: 'value', axisLabel: { fontSize: 10 } },
        series: [
          { name: '通过', type: 'bar', stack: 'total', data: data.map(function(d){return d.passed}), itemStyle: { color: '#36b37e' }, label: { show: true, position: 'inside', fontSize: 10 } },
          { name: '未通过', type: 'bar', stack: 'total', data: data.map(function(d){return d.failed}), itemStyle: { color: '#e84d5b' }, label: { show: true, position: 'inside', fontSize: 10 } },
          { name: '未考', type: 'bar', stack: 'total', data: data.map(function(d){return d.absent}), itemStyle: { color: '#c0c8d4' }, label: { show: true, position: 'inside', fontSize: 10 } }
        ]
      });
      var totalPassed = data.reduce(function(s,d){return s+d.passed},0);
      var totalFailed = data.reduce(function(s,d){return s+d.failed},0);
      var totalAbsent = data.reduce(function(s,d){return s+d.absent},0);
      var pieChart = echarts.init(pieEl);
      pieChart.setOption({
        tooltip: { trigger: 'item' },
        legend: { bottom: 0, textStyle: { fontSize: 11 } },
        series: [{ type: 'pie', radius: ['40%','65%'], center: ['50%','45%'],
          data: [
            { value: totalPassed, name: '通过', itemStyle: { color: '#36b37e' } },
            { value: totalFailed, name: '未通过', itemStyle: { color: '#e84d5b' } },
            { value: totalAbsent, name: '未考', itemStyle: { color: '#c0c8d4' } }
          ],
          label: { fontSize: 11 }
        }]
      });
      this._statsCharts = this._statsCharts || [];
      this._statsCharts.push(barChart, pieChart);
    },
    renderLabChart: function() {
      var el = this.$refs.labLevelChart;
      if (!el) return;
      var chart = echarts.init(el);
      var data = statisticsData.labLevelStats;
      chart.setOption({
        tooltip: { trigger: 'axis' },
        grid: { top: 20, bottom: 30, left: 60, right: 20 },
        xAxis: { type: 'category', data: data.map(function(d){return d.level}), axisLabel: { fontSize: 11 } },
        yAxis: { type: 'value', axisLabel: { fontSize: 11 } },
        series: [{ type: 'bar', barWidth: 50, data: data.map(function(d){ return { value: d.count, itemStyle: { color: d.color } } }), label: { show: true, position: 'top', fontSize: 11 } }]
      });
      this._statsCharts = this._statsCharts || [];
      this._statsCharts.push(chart);
    },
    renderHoursChart: function() {
      var el = this.$refs.hoursChart;
      if (!el) return;
      var chart = echarts.init(el);
      var data = statisticsData.studyHoursByType;
      var colleges = data.map(function(d){return d.college.replace('学院','')});
      chart.setOption({
        tooltip: { trigger: 'axis' },
        legend: { top: 0, textStyle: { fontSize: 11 } },
        grid: { top: 36, bottom: 30, left: 50, right: 10 },
        xAxis: { type: 'category', data: colleges, axisLabel: { fontSize: 10, rotate: 20 } },
        yAxis: { type: 'value', name: '学时', axisLabel: { fontSize: 10 } },
        series: [
          { name: '研究生', type: 'bar', data: data.map(function(d){return d.graduate}), itemStyle: { color: '#5b95f7' }, label: { show: true, position: 'top', fontSize: 10 } },
          { name: '本科生', type: 'bar', data: data.map(function(d){return d.undergraduate}), itemStyle: { color: '#36b37e' }, label: { show: true, position: 'top', fontSize: 10 } },
          { name: '教职工', type: 'bar', data: data.map(function(d){return d.staff}), itemStyle: { color: '#ffb020' }, label: { show: true, position: 'top', fontSize: 10 } }
        ]
      });
      this._statsCharts = this._statsCharts || [];
      this._statsCharts.push(chart);
    },
    examSpanMethod: function(params) {
      // Only merge college column when no examType filter is active (showing all 3 rows per college)
      if (this.examFilterExamType) return;
      var rowIndex = params.rowIndex;
      var columnIndex = params.columnIndex;
      if (columnIndex === 0) {
        if (rowIndex % 3 === 0) return { rowspan: 3, colspan: 1 };
        return { rowspan: 0, colspan: 0 };
      }
    },
    approveItem: function(item) {
      item.status = 'approved';
      this.$message.success('已通过 ' + item.studentName + ' 的绑定申请');
    },
    openRejectDialog: function(item) {
      this.rejectingItem = item;
      this.rejectReasonInput = '';
      this.showRejectDialog = true;
    },
    confirmReject: function() {
      if (this.rejectingItem) {
        this.rejectingItem.status = 'rejected';
        this.rejectingItem.rejectReason = this.rejectReasonInput;
        this.$message.warning('已驳回 ' + this.rejectingItem.studentName + ' 的绑定申请');
      }
      this.showRejectDialog = false;
      this.rejectingItem = null;
      this.rejectReasonInput = '';
    }
  },
  watch: {
    activePage: function() {
      if (this.activePage === 'workbench') this.$nextTick(this.renderCharts);
      if (this.activePage === 'statistics') this.renderStatsCharts();
    },
    activeRole: function() {
      var role = this.currentRole;
      if (role && role.lab && role.lab.category && this.resourceTabs.indexOf(role.lab.category) !== -1) {
        this.activeResourceTab = role.lab.category;
      }
    },
    statsExamType: function() { this.renderStatsCharts(); }
  },
  mounted: function() {
    var self = this;
    window.addEventListener('resize', function() { if (self._charts) self._charts.forEach(function(c) { c.resize(); }); });
    // 加载PRD markdown
    fetch('../prd/需求规格说明书.md').then(function(res) { return res.text(); }).then(function(md) {
      self.prdContent = marked.parse(md);
    }).catch(function() { self.prdContent = '<p>文档加载失败，请确保通过HTTP服务访问。</p>'; });
  }
});
