<script setup lang="tsx">
import { computed, ref } from 'vue';
import { NButton, NDivider } from 'naive-ui';
import { useBoolean } from '@sa/hooks';
import { fetchBatchDeleteSchoolMajor, fetchGetSchoolMajorList } from '@/service/api/art/school-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 SchoolImportModal from '../school-import-modal.vue';
import SchoolMajorOperateDrawer from './modules/school-major-operate-drawer.vue';
import SchoolMajorSearch from './modules/school-major-search.vue';

defineOptions({
  name: 'SchoolMajorList'
});

interface Props {
  schoolId?: CommonType.IdType | null;
  inModal?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  schoolId: null,
  inModal: false
});

const appStore = useAppStore();
const { download } = useDownload();
const { hasAuth } = useAuth();
const { bool: importVisible, setTrue: openImportModal } = useBoolean();

const searchParams = ref<Api.Art.SchoolMajorSearchParams>({
  pageNum: 1,
  pageSize: 10,
  schoolId: props.schoolId,
  collegeId: null,
  majorCode: null,
  majorName: null,
  educationLevel: null,
  durationYears: null,
  majorCategory: null,
  degreeType: null,
  introduction: null,
  params: {}
});

const requestParams = computed<Api.Art.SchoolMajorSearchParams>(() => ({
  ...searchParams.value,
  schoolId: props.schoolId ?? searchParams.value.schoolId
}));

const { columns, columnChecks, data, getData, getDataByPage, loading, mobilePagination, scrollX } =
  useNaivePaginatedTable({
    api: () => fetchGetSchoolMajorList(requestParams.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: 'schoolId',
        title: '学校ID(冗余便于查)',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'collegeId',
        title: '学院ID',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'majorCode',
        title: '专业编码(可选)',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'majorName',
        title: '专业名称',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'educationLevel',
        title: '学历层次：本科/专科',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'durationYears',
        title: '学制(3/4/5)',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'majorCategory',
        title: '专业类别：工学/理学/艺术学...',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'degreeType',
        title: '学位类型：工学学士/理学学士/艺术学学士...',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'introduction',
        title: '专业介绍',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'remark',
        title: '备注',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'operate',
        fixed: 'right',
        title: $t('common.operate'),
        align: 'center',
        width: 130,
        render: row => {
          const divider = () => {
            if (!hasAuth('art:schoolMajor:edit') || !hasAuth('art:schoolMajor:remove')) {
              return null;
            }
            return <NDivider vertical />;
          };

          const editBtn = () => {
            if (!hasAuth('art:schoolMajor: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:schoolMajor: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 fetchBatchDeleteSchoolMajor(checkedRowKeys.value);
  if (error) return;
  onBatchDeleted();
}

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

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

function handleExport() {
  download('/art/schoolMajor/export', requestParams.value, `学校专业_${new Date().getTime()}.xlsx`);
}

function handleImport() {
  openImportModal();
}
</script>

<template>
  <div
    :class="
      props.inModal
        ? 'flex-col-stretch gap-16px'
        : 'min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto'
    "
  >
    <SchoolMajorSearch v-model:model="searchParams" :fixed-school-id="props.schoolId" @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:schoolMajor:add')"
          :show-delete="hasAuth('art:schoolMajor:remove')"
          :show-export="hasAuth('art:schoolMajor:export')"
          @add="handleAdd"
          @delete="handleBatchDelete"
          @export="handleExport"
          @refresh="getData"
        >
          <template #after>
            <NButton v-if="hasAuth('art:school:import')" size="small" ghost @click="handleImport">
              <template #icon>
                <icon-material-symbols-upload-rounded class="text-icon" />
              </template>
              {{ $t('common.import') }}
            </NButton>
          </template>
        </TableHeaderOperation>
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile && !props.inModal"
        :scroll-x="scrollX"
        :loading="loading"
        remote
        :row-key="row => row.majorId"
        :pagination="mobilePagination"
        class="sm:h-full"
      />
      <SchoolMajorOperateDrawer
        v-model:visible="drawerVisible"
        :operate-type="operateType"
        :row-data="editingData"
        :default-school-id="props.schoolId"
        @submitted="getDataByPage"
      />
      <SchoolImportModal v-model:visible="importVisible" @submitted="getDataByPage" />
    </NCard>
  </div>
</template>

<style scoped></style>
