<script setup lang="tsx">
import { computed, ref } from 'vue';
import { NDivider } from 'naive-ui';
import { fetchBatchDeleteSchoolMajorTag, fetchGetSchoolMajorTagList } from '@/service/api/art/school-major-tag';
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 SchoolMajorTagOperateDrawer from './modules/school-major-tag-operate-drawer.vue';
import SchoolMajorTagSearch from './modules/school-major-tag-search.vue';

defineOptions({
  name: 'SchoolMajorTagList'
});

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 searchParams = ref<Api.Art.SchoolMajorTagSearchParams>({
  pageNum: 1,
  pageSize: 10,
  majorId: null,
  tagName: null,
  params: {}
});

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

const { columns, columnChecks, data, getData, getDataByPage, loading, mobilePagination, scrollX } =
  useNaivePaginatedTable({
    api: () => fetchGetSchoolMajorTagList(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: 'majorTagId',
        title: '主键ID',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'majorId',
        title: '专业ID',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'tagName',
        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:schoolMajorTag:edit') || !hasAuth('art:schoolMajorTag:remove')) {
              return null;
            }
            return <NDivider vertical />;
          };

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

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

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

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

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

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

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

function handleExport() {
  download('/art/schoolMajorTag/export', requestParams.value, `专业标签_${new Date().getTime()}.xlsx`);
}
</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'
    "
  >
    <SchoolMajorTagSearch 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:schoolMajorTag:add')"
          :show-delete="hasAuth('art:schoolMajorTag:remove')"
          :show-export="hasAuth('art:schoolMajorTag: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 && !props.inModal"
        :scroll-x="scrollX"
        :loading="loading"
        remote
        :row-key="row => row.majorTagId"
        :pagination="mobilePagination"
        class="sm:h-full"
      />
      <SchoolMajorTagOperateDrawer
        v-model:visible="drawerVisible"
        :operate-type="operateType"
        :row-data="editingData"
        @submitted="getDataByPage"
      />
    </NCard>
  </div>
</template>

<style scoped></style>
