<template>
  <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>
        <el-checkbox v-model="searchModel.showGroupNumber"
          >显示分组</el-checkbox
        >
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="toPage(1)">查询</el-button>
        <el-button @click="onExport">导出</el-button>
      </el-form-item>
    </el-form>
    <el-divider class="form-divider" />

    <el-table
      class="page-table"
      :data="dataList"
      :loading="loading"
      border
      stripe
      @sort-change="handleSortChange"
    >
      <el-table-column
        prop="subjectText"
        label="科目"
        min-width="200"
        sortable
      />
      <el-table-column
        v-if="searchModel.showGroupNumber"
        prop="groupNumber"
        label="分组"
        min-width="100"
      />
      <el-table-column
        prop="totalCount"
        label="任务总数"
        min-width="100"
        sortable
      />
      <el-table-column
        prop="finishCount"
        label="已完成"
        min-width="100"
        sortable
      />
      <el-table-column
        prop="rejectCount"
        label="打回数量"
        min-width="100"
        sortable
      />
      <el-table-column
        prop="rejectRatio"
        label="打回率"
        min-width="100"
        sortable
      >
        <template #default="scope">
          {{ formatPercentage(scope.row.rejectRatio) }}
        </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>
</template>

<script setup lang="ts">
  import { reactive } from 'vue';
  import { getRejectStatisticsList } from '@/api/reject';
  import {
    RejectStatisticsItem,
    RejectStatisticsFilter,
  } from '@/api/types/reject';
  import useTable from '@/hooks/table';
  import { downloadExport } from '@/utils/download-export';

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

  const searchModel = reactive<RejectStatisticsFilter>({
    subjectCode: null,
    showGroupNumber: false,
  });

  const {
    dataList,
    pagination,
    loading,
    toPage,
    pageSizeChange,
    handleSortChange,
  } = useTable<RejectStatisticsItem>(
    getRejectStatisticsList,
    searchModel,
    true
  );

  function formatPercentage(rate: number): string {
    if (rate === 0) return '0%';
    return `${(rate * 100).toFixed(1)}%`;
  }

  async function onExport() {
    await downloadExport('exportRejectStat', searchModel);
  }
</script>
