<script setup lang="tsx">
import dayjs from 'dayjs'
import { NButton, NCard, NTag } from 'naive-ui'
import { reactive } from 'vue'
import { RankPublishStatus } from '@/enum/business'
import { useRouterPush } from '@/hooks/common/router'
import { useNaivePaginatedTable, useTableOperate } from '@/hooks/common/table'
import { fetchActivityRankList } from '@/service/api/rank'
import { useAppStore } from '@/store/modules/app'
import RankSearch from './modules/rank-search.vue'

const appStore = useAppStore()
const { routerPushByKey } = useRouterPush()

const searchParams: Api.Rank.UserSearchParams = reactive({
  currentPage: 1,
  pageSize: 10,
  publishStatus: undefined,
  competitionActivityName: '',
})

const rankTitle = '排行榜管理列表'

const statusMap: Record<number, string> = {
  [RankPublishStatus.Published]: '已发布',
  [RankPublishStatus.Unpublished]: '未发布',
}

const { columns, data, getData, getDataByPage, loading, mobilePagination } = useNaivePaginatedTable({
  api: () => fetchActivityRankList(searchParams.currentPage, searchParams.pageSize),
  transform: (response) => {
    const rawData = response.data?.data as unknown as Api.Rank.ActivityRankList || {}

    return {
      data: (rawData?.Items || []).map((item) => {
        return {
          ActivityId: item.ActivityId,
          id: item.Id,
          competitionActivityName: item.ActivityName,
          competitionActivityDate: item.StartTime ? dayjs(item.StartTime).format('YYYY-MM-DD') : '',
          competitionTeamScale: `${item.TeamNum} 支队伍`,
          competitionMaxScore: item.MaxPoint,
          createTime: item.LastUpdatetime ? dayjs(item.LastUpdatetime).format('YYYY-MM-DD HH:mm:ss') : '',
          status: item.Status,
        }
      }),
      pageNum: rawData?.PageNumber || 1,
      pageSize: rawData?.PageSize || 10,
      total: rawData?.TotalRecords || 0,
    }
  },
  onPaginationParamsChange: (params) => {
    searchParams.currentPage = params.page || 1
    searchParams.pageSize = params.pageSize || 10
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 40,
    },
    {
      title: '序号',
      align: 'center',
      key: 'index',
      width: 80,
      render: (_row, index) => index + 1,
    },
    {
      key: 'competitionActivityName',
      title: '比赛活动名称',
      align: 'left',
    },
    {
      key: 'competitionActivityDate',
      title: '活动日期',
      align: 'center',
    },
    {
      key: 'competitionTeamScale',
      title: '队伍规模',
      align: 'center',
    },
    {
      key: 'competitionMaxScore',
      title: '最高积分',
      align: 'center',
      minWidth: 100,
      render: row => (
        <span class="text-primary font-bold">
          {row.competitionMaxScore}
          Pts
        </span>
      ),
    },
    {
      key: 'createTime',
      title: '最后更新时间',
      align: 'center',
    },
    {
      key: 'status',
      title: '发布状态',
      align: 'center',
      render: (row) => {
        if (row.status === null || row.status === undefined)
          return null
        const label = statusMap[Number(row.status)] || '未知'
        return <NTag type={Number(row.status) === RankPublishStatus.Published ? 'success' : 'warning'}>{label}</NTag>
      },
    },
    {
      key: 'operate',
      title: '操作',
      align: 'center',
      render: row => (
        <div class="flex-center">
          <NButton type="primary" text onClick={() => edit(row)}>
            进入排行详情
          </NButton>
        </div>
      ),
    },
  ],
})

const {
  checkedRowKeys,
} = useTableOperate(data, 'id', getData)

function edit(item: any) {
  routerPushByKey('rank_rank-detail', {
    query: {
      activityId: item.ActivityId,
      name: item.competitionActivityName,
      date: item.competitionActivityDate,
      Status: item.status,
    },
  })
}

// function handleBatchPublish() {
//   window.$message?.success('批量发布成功')
// }
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <RankSearch v-model:model="searchParams" @search="getDataByPage" />
    <NCard :bordered="false" page-size="small" class="card-wrapper sm:flex-1-hidden">
      <template #header>
        <div class="flex items-center justify-between">
          <div class="mid-title">
            <div class="text-16px font-bold">
              {{ rankTitle }}
            </div>
            <div class="mt-4px text-12px text-gray-500">
              您可以对所有比赛场次的最终积分进行核对、修正，并正式发布结果。
            </div>
          </div>
          <!-- <NButton type="primary" ghost class="ml-auto" @click="handleBatchPublish">
            <template #icon>
              <icon-ic-round-upload class="text-icon" />
            </template>
            批量发布至终端
          </NButton> -->
        </div>
      </template>
      <!-- <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" 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"
      />
    </NCard>
  </div>
</template>

<style scoped></style>
