<script lang="ts" setup>
// @ts-ignore
import type { EchartsUIType } from '@vben/plugins/echarts';

// @ts-ignore
import type { VxeGridProps } from '#/adapter/vxe-table';

import { h, onMounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';

// @ts-ignore
import { Page } from '@vben/common-ui';
// @ts-ignore
import { EchartsUI, useEcharts } from '@vben/plugins/echarts';

import { ElTabPane, ElTabs } from 'element-plus';

// @ts-ignore
import { useVbenVxeGrid } from '#/adapter/vxe-table';
// @ts-ignore
import { startExamList } from '#/api/exam/exam/exam';
// @ts-ignore
import { getDetailParticipantList } from '#/api/exam/exam/participant';
// @ts-ignore
import { correctRates } from '#/api/exam/paper/paper';
// @ts-ignore
import { questionTypes } from '#/utils/dicts';

const route = useRoute();
const router = useRouter();

const examId = ref(Number(route.params.id));

// 统一的图表颜色配置
const CHART_COLORS = {
  PARTICIPATION: '#5ab1ef',
  PASS: '#52c41a',
  BACKGROUND: '#f0f2f5',
};

// 响应式数据
// 考试基本信息
const examInfo: any = ref({});

// 标签页切换
const activeDataTab = ref('dataBoard');
const activeStatusTab = ref('participation');

// 图表相关数据
const chartRef = ref<EchartsUIType>();
const { renderEcharts: renderChart } = useEcharts(chartRef);

// 统一的图表更新函数
const updateChart = () => {
  const isParticipationTab = activeStatusTab.value === 'participation';

  const chartData = isParticipationTab
    ? [
        {
          value: examInfo.value.answerCount,
          name: '参与率',
          itemStyle: { color: '#FFB65D' },
        },
        {
          value: examInfo.value.allCount - examInfo.value.answerCount,
          name: '未参与率',
          itemStyle: { color: '#EAEEF8' },
        },
      ]
    : [
        {
          value: examInfo.value.passCount,
          name: '及格率',
          itemStyle: { color: '#38B865' },
        },
        {
          value: examInfo.value.participantCount - examInfo.value.passCount,
          name: '不及格率',
          itemStyle: { color: '#EAEEF8' },
        },
      ];

  renderChart({
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)',
    },
    series: [
      {
        name: isParticipationTab ? '参与率' : '及格率',
        type: 'pie',
        radius: ['70%', '85%'],
        avoidLabelOverlap: false,
        itemStyle: { borderRadius: 0, borderWidth: 0 },
        label: {
          show: true,
          position: 'center',
          formatter: `{b}\n{d}%`,
          fontSize: 20,
          fontWeight: 'bold',
        },
        emphasis: {
          label: { show: true, fontSize: 24, fontWeight: 'bold' },
        },
        labelLine: { show: false },
        data: chartData,
      },
    ],
  });
};

// 表格配置
const questionColumns: VxeGridProps['columns'] = [
  { title: '序号', minWidth: 80, field: 'id' },
  {
    title: '题目类别',
    minWidth: 120,
    field: 'questionType',
    formatter: ({ row }) => {
      const questionType = questionTypes.find(
        (item) => item.value === row.questionType,
      );
      return questionType?.label || '-';
    },
  },
  {
    title: '题目',
    minWidth: 500,
    field: 'questionName',
    slots: {
      default: ({ row }) => {
        return h('div', { innerHTML: row.questionContent });
      },
    },
  },
  { title: '正确数', minWidth: 100, field: 'correctCount' },
  {
    title: '正确率',
    minWidth: 100,
    field: 'correctRate',
    formatter: ({ row }) => `${row.correctRate || '0.0'}%`,
  },
];

const questionGridOptions: VxeGridProps = {
  columns: questionColumns,
  size: 'medium',
  proxyConfig: {
    enabled: true,
    autoLoad: true,
    ajax: {
      query: async ({ page }) => {
        // 模拟API调用，后续替换为实际API
        const res: any = await correctRates(examId.value, {
          pageNum: page.currentPage,
          pageSize: page.pageSize,
        });

        // 确保返回格式正确，使用 items 作为数据键
        return {
          items: res.rows || [],
          total: res.total || 0,
        };
      },
    },
  },
  rowConfig: { keyField: 'id' },
  toolbarConfig: {},
  id: 'exam-question-table',
};

// const logColumns: VxeGridProps['columns'] = [
//   { title: '序号', minWidth: 80, field: 'id' },
//   { title: '操作时间', minWidth: 150, field: 'operationTime' },
//   { title: '操作人', minWidth: 100, field: 'operator' },
//   { title: '操作类型', minWidth: 120, field: 'operationType' },
//   { title: '操作内容', minWidth: 300, field: 'operationContent' },
// ];

// const logGridOptions: VxeGridProps = {
//   columns: logColumns,
//   size: 'medium',
//   proxyConfig: {
//     enabled: true,
//     autoLoad: true,
//     ajax: {
//       query: async () => ({
//         items: MOCK_OPERATION_LOGS,
//         total: MOCK_OPERATION_LOGS.length,
//       }),
//     },
//   },
//   rowConfig: { keyField: 'id' },
//   toolbarConfig: {},
//   id: 'operation-log-table',
// };

const rankingColumns: VxeGridProps['columns'] = [
  {
    title: '名次',
    minWidth: 80,
    field: 'rank',
    type: 'seq',
  },
  { title: '岗位', minWidth: 120, field: 'postName' },
  { title: '人员姓名', minWidth: 120, field: 'userName' },
  { title: '得分', minWidth: 100, field: 'score' },
  {
    title: '操作',
    minWidth: 100,
    field: 'action',
    slots: { default: 'action' },
  },
];

const rankingGridOptions: VxeGridProps = {
  columns: rankingColumns,
  size: 'medium',
  // useSearchForm: false,
  proxyConfig: {
    enabled: true,
    autoLoad: true,
    ajax: {
      query: async ({ page }) => {
        // 模拟API调用，后续替换为实际API
        const res: any = await getDetailParticipantList({
          examId: examId.value,
          status: 'completed',
          reviewStatus: 'reviewed',
          type: 'ranking',
          pageNum: page.currentPage,
          pageSize: page.pageSize,
        });

        // 确保返回格式正确，使用 items 作为数据键
        return {
          items: res.rows || [],
          total: res.total || 0,
        };
      },
    },
  },
  rowConfig: { keyField: 'id' },
  toolbarConfig: {},
  id: 'user-ranking-table',
};

// 创建表格实例
const [QuestionTable] = useVbenVxeGrid({ gridOptions: questionGridOptions });
// const [LogTable] = useVbenVxeGrid({ gridOptions: logGridOptions });
const [RankingTable] = useVbenVxeGrid({ gridOptions: rankingGridOptions });

const init = async () => {
  // 并发调用接口
  const result: any = await startExamList({
    id: examId.value,
  });
  // 处理试卷详情数据
  examInfo.value = result.rows?.[0] || {};
};

// 生命周期钩子和监听
onMounted(() => {
  init().then(() => {
    updateChart();
  });
});

// 监听标签页切换，重新渲染图表
watch(
  () => activeStatusTab.value,
  () => {
    updateChart();
  },
);

const handleViewDetail = (row: any) => {
  router.push({
    name: 'ViewExamResult',
    params: {
      id: row.examId,
    },
    query: {
      pid: row.id,
    },
  });
};
</script>

<template>
  <Page :auto-content-height="true">
    <div class="exam-report-container">
      <!-- 顶部区域 -->
      <div class="top-section">
        <div class="exam-name">{{ examInfo.examName }}</div>
        <div class="exam-stats">
          <span>创建时间: {{ examInfo.createTime }}</span>
          <span class="separator">|</span>
          <span>截止时间: {{ examInfo.examEndTime }}</span>
          <span class="separator">|</span>
          <span>参与人数: {{ examInfo.answerCount }}</span>
          <span class="separator">|</span>
          <span>发放人数: {{ examInfo.allCount }}</span>
        </div>
      </div>

      <!-- 数据看板和操作日志切换 -->
      <div class="tab-container">
        <ElTabs v-model="activeDataTab">
          <ElTabPane label="数据看板" name="dataBoard" />
          <!-- <ElTabPane label="操作日志" name="operationLog" /> -->
        </ElTabs>
      </div>

      <!-- 数据内容区域 -->
      <div class="data-content">
        <!-- 数据看板 -->
        <div v-if="activeDataTab === 'dataBoard'" class="data-board">
          <QuestionTable />
        </div>

        <!-- 操作日志 -->
        <!-- <div v-if="activeDataTab === 'operationLog'" class="operation-log">
          <LogTable />
        </div> -->
      </div>

      <!-- 参与情况和人员排名区域 -->
      <div class="bottom-section">
        <!-- 左侧：参与情况和及格情况 -->
        <div class="left-section">
          <div class="status-tab-container">
            <ElTabs v-model="activeStatusTab">
              <ElTabPane label="参与情况" name="participation" />
              <ElTabPane label="及格情况" name="pass" />
            </ElTabs>
          </div>

          <!-- 统一的图表容器 -->
          <div class="status-content">
            <div class="chart-container">
              <EchartsUI ref="chartRef" style="width: 100%; height: 250px" />
            </div>
            <div class="stats-container">
              <!-- 动态显示统计数据 -->
              <div class="stat-item">
                <div class="stat-label">
                  {{
                    activeStatusTab === 'participation'
                      ? '发放人数'
                      : '参与人数'
                  }}
                </div>
                <div class="stat-value">
                  {{
                    activeStatusTab === 'participation'
                      ? examInfo.allCount
                      : examInfo.answerCount
                  }}
                </div>
              </div>
              <div class="stat-item">
                <div class="stat-label">
                  {{
                    activeStatusTab === 'participation'
                      ? '参与人数'
                      : '及格人数'
                  }}
                </div>
                <div class="stat-value">
                  {{
                    activeStatusTab === 'participation'
                      ? examInfo.answerCount
                      : examInfo.passCount
                  }}
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧：人员得分排名 -->
        <div class="right-section">
          <div class="ranking-header">
            <h3>人员得分排名</h3>
          </div>
          <div class="ranking-table">
            <RankingTable>
              <template #action="{ row }">
                <el-button
                  type="primary"
                  link
                  size="small"
                  @click="handleViewDetail(row)"
                >
                  查看
                </el-button>
              </template>
            </RankingTable>
          </div>
        </div>
      </div>
    </div>
  </Page>
</template>

<style scoped lang="scss">
.exam-report-container {
  min-height: 100vh;
  padding: 16px;
  background-color: #fff;

  .top-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding-bottom: 16px;
    border-bottom: 1px solid #e6e8eb;

    .exam-name {
      font-size: 20px;
      font-weight: bold;
      color: #303133;
    }

    .exam-stats {
      display: flex;
      align-items: center;
      gap: 10px;
      font-size: 14px;
      color: #606266;

      .separator {
        color: #dcdfe6;
      }
    }
  }

  .data-content {
    margin-bottom: 16px;
    background-color: #fff;
    border-radius: 6px;
    padding: 16px;
    padding-top: 0;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  }

  .bottom-section {
    display: flex;
    gap: 16px;

    .left-section {
      flex: 1;
      background-color: #fff;
      border-radius: 6px;
      padding: 16px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);

      .status-tab-container {
        margin-bottom: 16px;
      }

      .status-content {
        display: flex;
        gap: 16px;

        .chart-container {
          flex: 1;
          display: flex;
          justify-content: center;
          align-items: center;
        }

        .stats-container {
          flex: 1;
          display: flex;
          flex-direction: row;
          justify-content: space-between;
          gap: 16px;

          .stat-item {
            align-items: center;
            border-radius: 6px;
            height: 100px;
            text-align: center;
            margin-top: 80px;
            .stat-label {
              font-size: 14px;
              color: #606266;
              background-color: #f2f5ff;
              padding: 4px 8px;
              border-radius: 4px;
              width: 150px;
              height: 32px;
              line-height: 32px;
            }

            .stat-value {
              font-size: 24px;
              font-weight: bold;
              color: #303133;
              background-color: #eaefff;
              padding: 4px 12px;
              border-radius: 4px;
              width: 150px;
              height: 60px;
              line-height: 60px;
            }
          }
        }
      }
    }

    .right-section {
      flex: 1;
      background-color: #fff;
      border-radius: 6px;
      padding: 16px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);

      .ranking-header {
        margin-bottom: 16px;

        h3 {
          font-size: 16px;
          font-weight: 600;
          color: #303133;
        }
      }
    }
  }
}
</style>
