<script setup lang="tsx">
import { NButton, NPopconfirm, NTag } from 'naive-ui'
import { reactive } from 'vue'
import { useRouterPush } from '@/hooks/common/router'
import { useNaivePaginatedTable, useTableOperate } from '@/hooks/common/table'
import { fetchDeleteTemplate, 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 statusMap: Record<string, string> = {
  1: '铺码成功',
  2: '未铺码',
}

const { columns, columnChecks, data, getData, getDataByPage, loading, mobilePagination } = useNaivePaginatedTable({
  api: () => fetchTemplateList(searchParams),
  transform: (response) => {
    const transformed = {
      data: response.data?.data || [],
      pageNum: searchParams.currentPage,
      pageSize: searchParams.pageSize,
      total: response.data?.data?.total || 0,
    }
    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: 'Name',
      title: '名称',
      align: 'center',
    },
    {
      key: 'ID',
      title: '模板ID',
      align: 'center',
    },
    {
      key: 'competitionId',
      title: '关联比赛',
      align: 'center',
      render: (row: any) => {
        const label = row?.referenceCompetitionName || '未知比赛'
        return <span>{label}</span>
      },
    },
    {
      key: 'size',
      title: '设计尺寸',
      align: 'center',
      render: (row: any) => `${row.Width / 100 || '0'}mmx${row.Height / 100 || 0}mm`,
    },
    {
      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((row as any).ID || row.id)}>
            {{
              default: () => '确认删除？',
              trigger: () => (
                <NButton type="error" ghost size="small">
                  删除
                </NButton>
              ),
            }}
          </NPopconfirm>
        </div>
      ),
    },
  ],
})

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

async function handleBatchDelete() {
  // request
  onBatchDeleted()
}

async function handleDelete(id: number) {
  const { error } = await fetchDeleteTemplate(id)
  if (!error) {
    onDeleted()
  }
}

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

function handlePageInfo(id: number) {
  routerPushByKey('template_template-detail', { query: { id: id.toString() } })
}
function handleAdd() {
  routerPushByKey('template_template-detail')
}
</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>
