<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-input
          v-model="searchModel.collegeName"
          placeholder="请输入学院名称"
          clearable
          style="width: 200px"
        />
      </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="collegeName" label="学生院系" min-width="150" />
      <el-table-column prop="totalCount" label="报考人数" min-width="100" />
      <el-table-column prop="realityCount" label="有效人数" min-width="100" />
      <el-table-column prop="avgScore" label="平均分" min-width="100">
        <template #default="scope">
          {{ scope.row.avgScore?.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="maxScore" label="最高分" min-width="100" />
      <el-table-column prop="minScore" label="最低分" min-width="100" />
      <el-table-column prop="passCount" label="及格人数" min-width="100" />
      <el-table-column label="及格率" min-width="100">
        <template #default="scope">
          {{ (scope.row.passRate * 100).toFixed(2) }}%
        </template>
      </el-table-column>
      <el-table-column prop="excellentCount" label="优秀人数" min-width="100" />
      <el-table-column label="优秀率" min-width="100">
        <template #default="scope">
          {{ (scope.row.excellentRate * 100).toFixed(2) }}%
        </template>
      </el-table-column>
    </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 { getCollegeAnalysisList } from '@/api/analysis';
  import {
    CollegeAnalysisItem,
    CollegeAnalysisFilter,
  } 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: 'CollegeAnalysis',
  });

  const searchModel = reactive<CollegeAnalysisFilter>({
    subjectCode: null,
    collegeName: '',
  });

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

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

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

  // 图表
  const chartOptions = ref<EChartsOption>();
  function updateChartOption() {
    const collegeNames = dataList.value.map((item) => item.collegeName);
    const avgScores = dataList.value.map((item) => item.avgScore || 0);
    const maxScores = dataList.value.map((item) => item.maxScore || 0);
    const minScores = dataList.value.map((item) => item.minScore || 0);
    const passRates = dataList.value.map((item) => (item.passRate || 0) * 100);
    const excellentRates = dataList.value.map(
      (item) => (item.excellentRate || 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: collegeNames,
        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: 'bar',
          yAxisIndex: 0,
          data: maxScores,
          itemStyle: {
            color: '#91cc75',
          },
          barWidth: '15%',
        },
        {
          name: '最低分',
          type: 'bar',
          yAxisIndex: 0,
          data: minScores,
          itemStyle: {
            color: '#fac858',
          },
          barWidth: '15%',
        },
        {
          name: '及格率',
          type: 'line',
          yAxisIndex: 1,
          data: passRates,
          lineStyle: {
            color: '#ee6666',
            width: 3,
          },
          itemStyle: {
            color: '#ee6666',
          },
          symbol: 'circle',
          symbolSize: 6,
        },
        {
          name: '优秀率',
          type: 'line',
          yAxisIndex: 1,
          data: excellentRates,
          lineStyle: {
            color: '#73c0de',
            width: 3,
          },
          itemStyle: {
            color: '#73c0de',
          },
          symbol: 'circle',
          symbolSize: 6,
        },
      ],
    };
  }
  const chartModalRef = ref<typeof ChartModal>(null);
  function onChart() {
    chartModalRef.value?.open();
  }
</script>
