<script setup lang="tsx">
import { ref } from 'vue';
import { NDivider } from 'naive-ui';
import { fetchBatchDeleteHistoryScoreControlLine, fetchGetHistoryScoreControlLineList } from '@/service/api/art/history-score-control-line';
import { useAppStore } from '@/store/modules/app';
import { useAuth } from '@/hooks/business/auth';
import { useDownload } from '@/hooks/business/download';
import { defaultTransform, useNaivePaginatedTable, useTableOperate } from '@/hooks/common/table';
import { $t } from '@/locales';
import ButtonIcon from '@/components/custom/button-icon.vue';
import HistoryScoreControlLineOperateDrawer from './modules/history-score-control-line-operate-drawer.vue';
import HistoryScoreControlLineSearch from './modules/history-score-control-line-search.vue';

defineOptions({
  name: 'HistoryScoreControlLineList'
});


const appStore = useAppStore();
const { download } = useDownload();
const { hasAuth } = useAuth();

const searchParams = ref<Api.Art.HistoryScoreControlLineSearchParams>({
  pageNum: 1,
  pageSize: 10,
  provinceCode: null,
  provinceName: null,
  year: null,
  majorCategory: null,
  batchName: null,
  subjectType: null,
  cultureScore: null,
  majorScore: null,
  cultureScoreExam: null,
  majorScoreExam: null,
  params: {}
});

const { columns, columnChecks, data, getData, getDataByPage, loading, mobilePagination, scrollX } =
  useNaivePaginatedTable({
  api: () => fetchGetHistoryScoreControlLineList(searchParams.value),
  transform: response => defaultTransform(response),
  onPaginationParamsChange: params => {
    searchParams.value.pageNum = params.page;
    searchParams.value.pageSize = params.pageSize;
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'index',
      title: $t('common.index'),
      align: 'center',
      width: 64,
      render: (_, index) => index + 1
    },
    {
      key: 'controlId',
      title: '省控线主键',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'provinceCode',
      title: '省份行政区划代码',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'provinceName',
      title: '省份名称',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'year',
      title: '年份',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'majorCategory',
      title: '专业类别',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'batchName',
      title: '批次',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'subjectType',
      title: '科类(文/理)',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'cultureScore',
      title: '文化成绩分数',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'majorScore',
      title: '专业成绩分数',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'cultureScoreExam',
      title: '文化成绩校考分数',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'majorScoreExam',
      title: '专业成绩校考分数',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'remark',
      title: '备注',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      width: 130,
      render: row => {
        const divider = () => {
          if (!hasAuth('art:historyScoreControlLine:edit') || !hasAuth('art:historyScoreControlLine:remove')) {
            return null;
          }
          return <NDivider vertical />;
        };

        const editBtn = () => {
          if (!hasAuth('art:historyScoreControlLine:edit')) {
            return null;
          }
          return (
            <ButtonIcon
              text
              type="primary"
              icon="material-symbols:drive-file-rename-outline-outline"
              tooltipContent={$t('common.edit')}
              onClick={() => edit(row.controlId)}
            />
          );
        };

        const deleteBtn = () => {
          if (!hasAuth('art:historyScoreControlLine:remove')) {
            return null;
          }
          return (
            <ButtonIcon
              text
              type="error"
              icon="material-symbols:delete-outline"
              tooltipContent={$t('common.delete')}
              popconfirmContent={$t('common.confirmDelete')}
              onPositiveClick={() => handleDelete(row.controlId)}
            />
          );
        };

        return (
          <div class="flex-center gap-8px">
            {editBtn()}
            {divider()}
            {deleteBtn()}
          </div>
        );
      }
    }
  ]
});

const { drawerVisible, operateType, editingData, handleAdd, handleEdit, checkedRowKeys, onBatchDeleted, onDeleted } =
  useTableOperate(data, 'controlId', getData);

async function handleBatchDelete() {
  // request
  const { error } = await fetchBatchDeleteHistoryScoreControlLine(checkedRowKeys.value);
  if (error) return;
  onBatchDeleted();
}

async function handleDelete(controlId: CommonType.IdType) {
  // request
  const { error } = await fetchBatchDeleteHistoryScoreControlLine([controlId]);
  if (error) return;
  onDeleted();
}

function edit(controlId: CommonType.IdType) {
  handleEdit(controlId);
}

function handleExport() {
  download('/art/historyScoreControlLine/export', searchParams.value, `历年省控线_${new Date().getTime()}.xlsx`);
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <HistoryScoreControlLineSearch v-model:model="searchParams" @search="getDataByPage" />
    <NCard title="历年省控线列表" :bordered="false" size="small" class="card-wrapper sm:flex-1-hidden">
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          :show-add="hasAuth('art:historyScoreControlLine:add')"
          :show-delete="hasAuth('art:historyScoreControlLine:remove')"
          :show-export="hasAuth('art:historyScoreControlLine:export')"
          @add="handleAdd"
          @delete="handleBatchDelete"
          @export="handleExport"
          @refresh="getData"
        />
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="scrollX"
        :loading="loading"
        remote
        :row-key="row => row.controlId"
        :pagination="mobilePagination"
        class="sm:h-full"
      />
      <HistoryScoreControlLineOperateDrawer
        v-model:visible="drawerVisible"
        :operate-type="operateType"
        :row-data="editingData"
        @submitted="getDataByPage"
      />
    </NCard>
  </div>
</template>

<style scoped></style>
