<script setup lang="tsx">
import { computed, ref } from 'vue';
import { NDivider } from 'naive-ui';
import { fetchBatchDeleteSchoolDetail, fetchGetSchoolDetailList } from '@/service/api/art/school-detail';
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 SchoolDetailOperateDrawer from './modules/school-detail-operate-drawer.vue';
import SchoolDetailSearch from './modules/school-detail-search.vue';

defineOptions({
  name: 'SchoolDetailList'
});

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.SchoolDetailSearchParams>({
  pageNum: 1,
  pageSize: 10,
  schoolId: props.schoolId,
  introduction: null,
  address: null,
  contact: null,
  email: null,
  website: null,
  params: {}
});

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

const { columns, columnChecks, data, getData, getDataByPage, loading, mobilePagination, scrollX } =
  useNaivePaginatedTable({
    api: () => fetchGetSchoolDetailList(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: 'detailId',
        title: '主键ID',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'schoolId',
        title: '关联学校主表ID',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'introduction',
        title: '学校详细介绍（大文本）',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'address',
        title: '学校地址',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'contact',
        title: '联系电话',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'email',
        title: '邮箱',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'website',
        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:schoolDetail:edit') || !hasAuth('art:schoolDetail:remove')) {
              return null;
            }
            return <NDivider vertical />;
          };

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

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

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

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

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

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

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

function handleExport() {
  download('/art/schoolDetail/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'
    "
  >
    <SchoolDetailSearch 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:schoolDetail:add')"
          :show-delete="hasAuth('art:schoolDetail:remove')"
          :show-export="hasAuth('art:schoolDetail: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.detailId"
        :pagination="mobilePagination"
        class="sm:h-full"
      />
      <SchoolDetailOperateDrawer
        v-model:visible="drawerVisible"
        :operate-type="operateType"
        :row-data="editingData"
        :default-school-id="props.schoolId"
        @submitted="getDataByPage"
      />
    </NCard>
  </div>
</template>

<style scoped></style>
