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

const { routerPushByKey } = useRouterPush()

const appStore = useAppStore()

const searchParams: Api.Template.TemplateSearchParams = reactive({
  currentPage: 1,
  pageSize: 10,
  status: null,
  templateName: undefined,
  competitionId: undefined,
  size: undefined,
})

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: () => fetchTemplateList(searchParams),
  transform: (response) => {
    const transformed = defaultTransform(response)
    transformed.data.forEach((item: any, index) => {
      item.code = `MD${String(index + 1).padStart(6, '0')}`
      item.size = '210mmx297mm'
      item.competitionId = (item.competitionId === '1' || item.competitionId === '2') ? item.competitionId : '1'
      // Mock templateName if not present
      if (!item.templateName)
        item.templateName = item.userName || '测试模板'
    })
    return transformed
  },
  onPaginationParamsChange: (params) => {
    searchParams.currentPage = params.page || 1
    searchParams.pageSize = params.pageSize || 10
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48,
    },
    {
      key: 'index',
      title: '序号',
      align: 'center',
      width: 60,
      render: (_, index) => index + 1,
    },
    {
      key: 'templateName',
      title: '名称',
      align: 'center',
    },
    {
      key: 'code',
      title: '模板ID',
      align: 'center',
    },
    {
      key: 'competitionId',
      title: '关联比赛',
      align: 'center',
      render: (row: any) => {
        const label = competitionMap[row.competitionId as string] || '未知比赛'
        return <span>{label}</span>
      },
    },
    {
      key: 'size',
      title: '设计尺寸',
      align: 'center',
    },
    {
      key: 'status',
      title: '状态',
      align: 'center',
      render: (row: Api.Template.CommonRecord) => {
        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={() => handlePageInfo(row.id)}>
            页面信息
          </NButton>
          <NButton size="small" onClick={() => { }}>
            打印
          </NButton>
          <NPopconfirm onPositiveClick={() => handleDelete()}>
            {{
              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
  onBatchDeleted()
}

function handleDelete() {
  onDeleted()
}

function edit(id: number) {
  handleEdit(id)
}

function handlePageInfo(id: number) {
  routerPushByKey('template_template-detail', { query: { id: id.toString() } })
}
</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" page-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 as any" :data="data" page-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>
