<script setup lang="tsx">
import { ref } from 'vue';
import { NDivider } from 'naive-ui';
import { fetchBatchDeleteMajor, fetchGetMajorList } from '@/service/api/art/major';
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 MajorOperateDrawer from './modules/major-operate-drawer.vue';
import MajorSearch from './modules/major-search.vue';

defineOptions({
  name: 'MajorList'
});


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

const searchParams = ref<Api.Art.MajorSearchParams>({
  pageNum: 1,
  pageSize: 10,
  majorName: null,
  educationLevel: null,
  majorIcon: null,
  schoolingYears: null,
  disciplinePrimary: null,
  disciplineSecondary: null,
  degreeAwarded: null,
  summary: null,
  trainingDirection: null,
  coreCourses: null,
  params: {}
});

const { columns, columnChecks, data, getData, getDataByPage, loading, mobilePagination, scrollX } =
  useNaivePaginatedTable({
  api: () => fetchGetMajorList(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: 'majorId',
      title: '专业主键ID',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'majorName',
      title: '专业名称',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'educationLevel',
      title: '学历层次',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'majorIcon',
      title: '专业图标',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'schoolingYears',
      title: '学制(年)',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'disciplinePrimary',
      title: '所属一级学科',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'disciplineSecondary',
      title: '所属二级学科',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'degreeAwarded',
      title: '授予学士学位',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'summary',
      title: '专业概括',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'trainingDirection',
      title: '培养方向',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'coreCourses',
      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:major:edit') || !hasAuth('art:major:remove')) {
            return null;
          }
          return <NDivider vertical />;
        };

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

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

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

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

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

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

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

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

<style scoped></style>
