<template>
  <div class="part-box is-border">
    <!-- 统计图表区域 -->
    <div class="chart-container">
      <div class="chart-item">
        <h3>阅卷总进度</h3>
        <Chart :options="taskChartOptions" width="400px" height="300px" />
      </div>
      <div class="chart-item">
        <h3>科目阅卷进度</h3>
        <Chart :options="courseChartOptions" width="400px" height="300px" />
      </div>
    </div>
  </div>

  <div class="part-box is-border">
    <el-form inline>
      <el-form-item label="科目">
        <select-subject v-model="searchModel.subjectCode"></select-subject>
      </el-form-item>
      <el-form-item label="完成进度">
        <el-select
          v-model="searchModel.finished"
          placeholder="请选择"
          clearable
          style="width: 120px"
        >
          <el-option label="已完成" :value="true" />
          <el-option label="未完成" :value="false" />
        </el-select>
      </el-form-item>
    </el-form>
    <el-divider class="form-divider" />
    <div class="part-action">
      <el-space wrap>
        <el-button type="primary" @click="toPage(1)">查询</el-button>
        <el-button :loading="closeLoading" @click="onCloseSubject"
          >关闭</el-button
        >
        <el-button @click="onExportCommand('exportMarkProgress')"
          >导出评卷进度</el-button
        >
        <el-button @click="onExportCommand('exportMarkWorkload')"
          >导出工作量</el-button
        >
      </el-space>
    </div>

    <el-table
      class="page-table"
      :data="dataList"
      :loading="loading"
      border
      stripe
      @selection-change="handleSelectionChange"
      @sort-change="handleSortChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="subjectName" label="科目" min-width="200" />
      <el-table-column label="选做异常" sortable min-width="110">
        <template #default="scope">
          <el-tag :type="scope.row.selectiveError ? 'danger' : 'success'">
            {{ scope.row.selectiveError ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="uploadCount"
        label="上传人数"
        min-width="110"
        sortable
      />
      <el-table-column
        prop="subjectiveScore"
        label="主观总分"
        min-width="110"
        sortable
      />
      <el-table-column
        prop="groupCount"
        label="分组总数"
        sortable
        min-width="110"
      />
      <el-table-column label="完成进度" min-width="120">
        <template #default="scope">
          <el-progress
            :percentage="scope.row.percent"
            :color="scope.row.percent === 100 ? '#67c23a' : '#409eff'"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="markedCount"
        label="待复核量"
        min-width="110"
        sortable
      />
    </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>
</template>

<script setup lang="ts">
  import { reactive, ref, computed, onMounted } from 'vue';
  import { ElMessage } from 'element-plus';
  import { useAppStore } from '@/store';

  import {
    getMarkStatInfo,
    getMarkStatList,
    markSubjectClose,
  } from '@/api/mark';
  import {
    MarkStatInfo,
    MarkStatItem,
    MarkStatListFilter,
  } from '@/api/types/mark';
  import useTable from '@/hooks/table';
  import useLoading from '@/hooks/loading';
  import { modalConfirm } from '@/utils/ui';
  import { downloadExport } from '@/utils/download-export';

  defineOptions({
    name: 'MarkProgress',
  });
  const appStore = useAppStore();

  const searchModel = reactive<MarkStatListFilter>({
    subjectCode: null,
    finished: undefined,
  });

  const {
    dataList,
    pagination,
    loading,
    selectedRows,
    toPage,
    pageSizeChange,
    handleSelectionChange,
    handleSortChange,
  } = useTable<MarkStatItem>(getMarkStatList, searchModel, false);

  // 统计信息
  const statInfo = ref<MarkStatInfo>({
    taskFinishedCount: 0,
    taskUnfinishedCount: 0,
    courseFinishedCount: 0,
    courseUnfinishedCount: 0,
  });

  // 任务进度饼状图配置
  const taskChartOptions = computed(() => ({
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)',
    },
    legend: {
      orient: 'horizontal',
      bottom: '10%',
      data: ['任务待完成', '任务已完成'],
    },
    series: [
      {
        name: '任务进度',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['50%', '40%'],
        data: [
          {
            value: statInfo.value.markedCount,
            name: '任务待完成',
            itemStyle: { color: '#5470c6' },
          },
          {
            value: statInfo.value.unMarkedCount,
            name: '任务已完成',
            itemStyle: { color: '#ff7875' },
          },
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
      },
    ],
  }));

  // 科目进度饼状图配置
  const courseChartOptions = computed(() => ({
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)',
    },
    legend: {
      orient: 'horizontal',
      bottom: '10%',
      data: ['科目待完成', '科目已完成'],
    },
    series: [
      {
        name: '科目进度',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['50%', '40%'],
        data: [
          {
            value: statInfo.value.unFinishCount,
            name: '科目待完成',
            itemStyle: { color: '#5470c6' },
          },
          {
            value: statInfo.value.finishCount,
            name: '科目已完成',
            itemStyle: { color: '#ff7875' },
          },
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
      },
    ],
  }));

  // 关闭科目
  const { loading: closeLoading, setLoading } = useLoading();
  async function onCloseSubject() {
    if (!selectedRows.value.length) {
      ElMessage.warning('请选择科目');
      return;
    }
    const confirm = await modalConfirm('确认关闭所选科目吗？', '提示 ').catch(
      () => false
    );
    if (!confirm) return;

    try {
      setLoading(true);
      const ids = selectedRows.value.map((item) => item.subjectCode);
      await markSubjectClose(ids);
      ElMessage.success('关闭成功');
      toPage(1);
    } catch (error) {
      console.error('关闭科目失败:', error);
    } finally {
      setLoading(false);
    }
  }

  // 导出
  const onExportCommand = async (
    command: 'exportMarkProgress' | 'exportMarkWorkload'
  ) => {
    downloadExport(command);
  };

  // 获取统计信息
  async function getStatInfo() {
    if (!appStore.curExam?.id) return;

    try {
      const data = await getMarkStatInfo(appStore.curExam.id);
      statInfo.value = data;
    } catch (error) {
      console.error('获取统计信息失败:', error);
    }
  }

  onMounted(() => {
    getStatInfo();
  });
</script>

<style scoped lang="scss">
  .chart-container {
    display: flex;
    justify-content: space-around;
    align-items: center;
    padding: 20px;
    gap: 40px;

    .chart-item {
      text-align: center;

      h3 {
        margin-bottom: 20px;
        color: #333;
        font-size: 16px;
        font-weight: 500;
      }
    }
  }
</style>
