<template>
  <div class="part-box is-border">
    <el-form inline>
      <el-form-item label="科目">
        <select-subject
          v-model="searchModel.subjectCode"
          :clearable="false"
          default-first
          @default-selected="search"
        ></select-subject>
      </el-form-item>
      <el-form-item label="试卷类型">
        <el-select
          v-model="searchModel.paperType"
          placeholder="请选择"
          clearable
          style="width: 150px"
        >
          <el-option label="A卷" value="A" />
          <el-option label="B卷" value="B" />
          <el-option label="C卷" value="C" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-space wrap>
          <el-button type="primary" @click="search">查询</el-button>
          <el-button @click="onExport">导出</el-button>
          <el-button @click="onChart">查看统计图</el-button>
        </el-space>
      </el-form-item>
    </el-form>
    <el-divider class="form-divider" />

    <el-table
      class="page-table"
      :data="dataList"
      :loading="loading"
      border
      stripe
    >
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="questionName" label="题目名称" min-width="150" />
      <el-table-column prop="mainNumber" label="大题号" min-width="80" />
      <el-table-column prop="subNumber" label="小题号" min-width="80" />
      <el-table-column prop="score" label="单题分数" min-width="100" />
      <el-table-column prop="avgScore" label="单题平均分" min-width="120">
        <template #default="scope">
          {{ scope.row.avgScore?.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="stdev" label="单题标准差" min-width="120">
        <template #default="scope">
          {{ scope.row.stdev?.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column label="得分率" min-width="100">
        <template #default="scope">
          {{ (scope.row.scoreRate * 100).toFixed(2) }}%
        </template>
      </el-table-column>
      <el-table-column label="满分率" min-width="100">
        <template #default="scope">
          {{ (scope.row.fullScoreRate * 100).toFixed(2) }}%
        </template>
      </el-table-column>
      <el-table-column prop="paperType" label="试卷类型" min-width="100" />
    </el-table>
    <el-pagination
      v-model:current-page="pagination.pageNumber"
      v-model:page-size="pagination.pageSize"
      :layout="pagination.layout"
      :total="pagination.total"
      @size-change="pageSizeChange"
      @current-change="toPage"
    />
  </div>

  <ChartModal
    ref="chartModalRef"
    title="客观题分析"
    :chart-options="chartOptions"
  />
</template>

<script setup lang="ts">
  import { reactive, ref } from 'vue';
  import { getQuestionAnalysisList } from '@/api/analysis';
  import {
    QuestionAnalysisItem,
    QuestionAnalysisFilter,
  } from '@/api/types/analysis';
  import useTable from '@/hooks/table';
  import { downloadExport } from '@/utils/download-export';
  import ChartModal from '@/components/chart/ChartModal.vue';
  import type { EChartsOption } from 'echarts';

  defineOptions({
    name: 'ObjectiveQuestionAnalysis',
  });

  const searchModel = reactive<QuestionAnalysisFilter>({
    subjectCode: null,
    objective: true,
    paperType: '',
  });

  const { dataList, pagination, loading, toPage, pageSizeChange } =
    useTable<QuestionAnalysisItem>(getQuestionAnalysisList, searchModel, false);

  async function search() {
    await toPage(1);
    updateChartOption();
  }

  async function onExport() {
    await downloadExport('exportQuestionAnalysisList', searchModel);
  }

  // 图表
  const chartOptions = ref<EChartsOption>();
  function updateChartOption() {
    const names = dataList.value.map((item) => item.questionName);
    const avgScores = dataList.value.map((item) => item.avgScore || 0);
    const scoreRates = dataList.value.map(
      (item) => (item.scoreRate || 0) * 100
    );
    const fullScoreRates = dataList.value.map(
      (item) => (item.fullScoreRate || 0) * 100
    );

    chartOptions.value = {
      toolbox: {
        feature: {
          saveAsImage: { show: true },
        },
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          crossStyle: {
            color: '#999',
          },
        },
        formatter(params: any) {
          let result = `${params[0].axisValue}<br/>`;
          params.forEach((param: any) => {
            const unit = param.seriesName.includes('率') ? '%' : '分';
            result += `${param.marker}${param.seriesName}: ${param.value}${unit}<br/>`;
          });
          return result;
        },
      },
      legend: {
        data: ['单题平均分', '得分率', '满分率'],
        top: 30,
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '10%',
        top: '15%',
        containLabel: true,
      },
      xAxis: {
        type: 'category',
        data: names,
        axisPointer: {
          type: 'shadow',
        },
        axisLabel: {
          rotate: 45,
          interval: 0,
        },
      },
      yAxis: [
        {
          type: 'value',
          name: '分数',
          position: 'left',
        },
        {
          type: 'value',
          name: '百分比',
          position: 'right',
          axisLabel: {
            formatter: '{value} %',
          },
          max: 100,
        },
      ],
      series: [
        {
          name: '单题平均分',
          type: 'bar',
          yAxisIndex: 0,
          data: avgScores,
          itemStyle: {
            color: '#5470c6',
          },
          barWidth: '15%',
        },
        {
          name: '得分率',
          type: 'line',
          yAxisIndex: 1,
          data: scoreRates,
          lineStyle: {
            color: '#ee6666',
            width: 3,
          },
          itemStyle: {
            color: '#ee6666',
          },
          symbol: 'circle',
          symbolSize: 6,
        },
        {
          name: '满分率',
          type: 'line',
          yAxisIndex: 1,
          data: fullScoreRates,
          lineStyle: {
            color: '#73c0de',
            width: 3,
          },
          itemStyle: {
            color: '#73c0de',
          },
          symbol: 'circle',
          symbolSize: 6,
        },
      ],
    };
  }
  const chartModalRef = ref<typeof ChartModal>(null);
  function onChart() {
    chartModalRef.value?.open();
  }
</script>
