<script setup lang="tsx">
import { ref } from 'vue';
import { NDivider } from 'naive-ui';
import { fetchBatchDeleteSchoolRecruitMajorHistory, fetchGetSchoolRecruitMajorHistoryList } from '@/service/api/art/school-recruit-major-history';
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 SchoolRecruitMajorHistoryOperateDrawer from './modules/school-recruit-major-history-operate-drawer.vue';
import SchoolRecruitMajorHistorySearch from './modules/school-recruit-major-history-search.vue';

defineOptions({
  name: 'SchoolRecruitMajorHistoryList'
});


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

const searchParams = ref<Api.Art.SchoolRecruitMajorHistorySearchParams>({
  pageNum: 1,
  pageSize: 10,
  recruitMajorId: null,
  schoolId: null,
  schoolCode: null,
  collegeCode: null,
  schoolName: null,
  majorId: null,
  majorCode: null,
  majorName: null,
  enrollCode: null,
  majorType: null,
  majorTypeSub: null,
  mainExamSubject: null,
  year: null,
  subjectType: null,
  batchName: null,
  admissionFormula: null,
  probabilityOperator: null,
  controlScore: null,
  admissionScore: null,
  planEnroll: null,
  filedAmount: null,
  admitAmount: null,
  firstChoiceAdmitAmount: null,
  minScoreDiff: null,
  tuitionFee: null,
  params: {}
});

const { columns, columnChecks, data, getData, getDataByPage, loading, mobilePagination, scrollX } =
  useNaivePaginatedTable({
  api: () => fetchGetSchoolRecruitMajorHistoryList(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: 'historyId',
      title: '历年录取数据ID',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'recruitMajorId',
      title: '对应招录专业ID',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'schoolId',
      title: '学校ID',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'schoolCode',
      title: '学校代码',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'collegeCode',
      title: '院校代码',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'schoolName',
      title: '学校名称',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'majorId',
      title: '专业ID',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'majorCode',
      title: '专业代码',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'majorName',
      title: '专业名称',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'enrollCode',
      title: '招生代码',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'majorType',
      title: '专业类型',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'majorTypeSub',
      title: '专业类别子级',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'mainExamSubject',
      title: '主考科目',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'year',
      title: '年份',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'subjectType',
      title: '科类(文/理)',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'batchName',
      title: '批次',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'admissionFormula',
      title: '录取方式(文*x+专*y)',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'probabilityOperator',
      title: '录取概率规则运算符',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'controlScore',
      title: '省控线',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'admissionScore',
      title: '录取线',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'planEnroll',
      title: '招生人数',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'filedAmount',
      title: '实际投档人数',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'admitAmount',
      title: '录取数',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'firstChoiceAdmitAmount',
      title: '一志愿录取数',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'minScoreDiff',
      title: '最低分数差',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'tuitionFee',
      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:schoolRecruitMajorHistory:edit') || !hasAuth('art:schoolRecruitMajorHistory:remove')) {
            return null;
          }
          return <NDivider vertical />;
        };

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

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

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

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

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

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

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

function handleExport() {
  download('/art/schoolRecruitMajorHistory/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">
    <SchoolRecruitMajorHistorySearch 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:schoolRecruitMajorHistory:add')"
          :show-delete="hasAuth('art:schoolRecruitMajorHistory:remove')"
          :show-export="hasAuth('art:schoolRecruitMajorHistory: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.historyId"
        :pagination="mobilePagination"
        class="sm:h-full"
      />
      <SchoolRecruitMajorHistoryOperateDrawer
        v-model:visible="drawerVisible"
        :operate-type="operateType"
        :row-data="editingData"
        @submitted="getDataByPage"
      />
    </NCard>
  </div>
</template>

<style scoped></style>
