<script setup lang="tsx">
import { computed, ref } from 'vue';
import { NButton, NDivider } from 'naive-ui';
import { useBoolean } from '@sa/hooks';
import { fetchBatchDeleteSchoolDorm, fetchGetSchoolDormList } from '@/service/api/art/school-dorm';
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 SchoolDormOperateDrawer from './modules/school-dorm-operate-drawer.vue';
import SchoolDormSearch from './modules/school-dorm-search.vue';

defineOptions({
  name: 'SchoolDormList'
});

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.SchoolDormSearchParams>({
  pageNum: 1,
  pageSize: 10,
  campusId: null,
  roomSize: null,
  bunkBedDesk: null,
  privateBath: null,
  tags: null,
  description: null,
  params: {}
});

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

const { columns, columnChecks, data, getData, getDataByPage, loading, mobilePagination, scrollX } =
  useNaivePaginatedTable({
    api: () => fetchGetSchoolDormList(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: 'dormId',
        title: '主键ID',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'campusId',
        title: '校区ID',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'roomSize',
        title: '几人间(4/6/8...)',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'bunkBedDesk',
        title: '是否上床下桌(0否1是)',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'privateBath',
        title: '是否独立卫浴(0否1是)',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'tags',
        title: '宿舍标签(冗余文本：空调/热水/洗衣房...)',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'description',
        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:schoolDorm:edit') || !hasAuth('art:schoolDorm:remove')) {
              return null;
            }
            return <NDivider vertical />;
          };

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

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

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

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

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

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

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

function handleExport() {
  download('/art/schoolDorm/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'
    "
  >
    <SchoolDormSearch 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:schoolDorm:add')"
          :show-delete="hasAuth('art:schoolDorm:remove')"
          :show-export="hasAuth('art:schoolDorm: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.dormId"
        :pagination="mobilePagination"
        class="sm:h-full"
      />
      <SchoolDormOperateDrawer
        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>
