<script setup lang="tsx">
import { reactive } from 'vue';
import { NButton, NPopconfirm, NTag } from 'naive-ui';
import { fetchGetUserList } from '@/service/api';
import { useAppStore } from '@/store/modules/app';
import { defaultTransform, useNaivePaginatedTable, useTableOperate } from '@/hooks/common/table';
import TemplateOperateDrawer from './modules/template-operate-drawer.vue';
import TemplateSearch from './modules/template-search.vue';

const appStore = useAppStore();

const searchParams: Api.SystemManage.UserSearchParams = reactive({
  current: 1,
  size: 10,
  status: null,
  userName: null,
  userGender: null,
  nickName: null,
  userPhone: null,
  userEmail: null
});

const templateTitle = '模板管理';

const competitionMap: Record<string, string> = {
  1: '第九届阅读之星大赛',
  2: '科普阅读大赛'
};

const statusMap: Record<string, string> = {
  1: '铺码成功',
  2: '未铺码'
};

const { columns, columnChecks, data, getData, getDataByPage, loading, mobilePagination } = useNaivePaginatedTable({
  api: () => fetchGetUserList(searchParams),
  transform: response => {
    const transformed = defaultTransform(response);
    transformed.data.forEach((item, index) => {
      item.nickName = `MD${String(index + 1).padStart(6, '0')}`;
      item.userPhone = '210mmx297mm';
      item.userGender = (item.userGender === '1' || item.userGender === '2') ? item.userGender : '1';
    });
    return transformed;
  },
  onPaginationParamsChange: params => {
    searchParams.current = params.page;
    searchParams.size = params.pageSize;
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'index',
      title: '序号',
      align: 'center',
      width: 60,
      render: (_, index) => index + 1
    },
    {
      key: 'userName',
      title: '名称',
      align: 'center',
    },
    {
      key: 'nickName',
      title: '模板ID',
      align: 'center',
    },
    {
      key: 'userGender',
      title: '关联比赛',
      align: 'center',
      render: row => {
        const label = competitionMap[row.userGender as string] || '未知比赛';
        return <span>{label}</span>;
      }
    },
    {
      key: 'userPhone',
      title: '设计尺寸',
      align: 'center',
    },
    {
      key: 'status',
      title: '状态',
      align: 'center',
      width: 100,
      render: row => {
        if (row.status === null) {
          return null;
        }
        const label = statusMap[row.status] || '未知';
        return <NTag type={row.status === '1' ? 'success' : 'warning'}>{label}</NTag>;
      }
    },
    {
      key: 'operate',
      title: '操作',
      align: 'center',
      // width: 430,
      render: row => (
        <div class="flex-center gap-8px">
          <NButton type="primary" ghost size="small" onClick={() => edit(row.id)}>
            基础信息
          </NButton>
          <NButton size="small" onClick={() => { }}>
            铺码
          </NButton>
          <NButton size="small" onClick={() => { }}>
            预览
          </NButton>
          <NButton size="small" onClick={() => { }}>
            页面信息
          </NButton>
          <NButton size="small" onClick={() => { }}>
            打印
          </NButton>
          <NPopconfirm onPositiveClick={() => handleDelete(row.id)}>
            {{
              default: () => '确认删除？',
              trigger: () => (
                <NButton type="error" ghost size="small">
                  删除
                </NButton>
              )
            }}
          </NPopconfirm>
        </div>
      )
    }
  ]
});

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

async function handleBatchDelete() {
  // request
  console.log(checkedRowKeys.value);

  onBatchDeleted();
}

function handleDelete(id: number) {
  // request
  console.log(id);

  onDeleted();
}

function edit(id: number) {
  handleEdit(id);
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <TemplateSearch v-model:model="searchParams" @search="getDataByPage" />
    <NCard :title="templateTitle" :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" @add="handleAdd" @delete="handleBatchDelete" @refresh="getData" />
      </template>
      <NDataTable v-model:checked-row-keys="checkedRowKeys" :columns="columns" :data="data" size="small" striped
        :flex-height="!appStore.isMobile" :scroll-x="962" :loading="loading" remote :row-key="row => row.id"
        :pagination="mobilePagination" class="sm:h-full" />
      <TemplateOperateDrawer v-model:visible="drawerVisible" :operate-type="operateType" :row-data="editingData"
        @submitted="getDataByPage" />
    </NCard>
  </div>
</template>

<style scoped></style>
