<script setup lang="ts">
import type { ContestItem } from '../types'
import { CirclePlus } from '@element-plus/icons-vue'
import AppList from '@/components/base/AppList.vue'
import { getContestList } from '../api'
import { useMapStore } from '@/stores/map'

// 赛项类型
const types = useMapStore().getMapValuesByKey('competition_type')

const FormDialog = defineAsyncComponent(() => import('../components/FormDialog.vue'))

const appList = $ref<InstanceType<typeof AppList> | null>(null)

// 列表配置
const listOptions = {
  remote: {
    httpRequest: getContestList
  },
  columns: [
    { label: '序号', type: 'index', width: 60 },
    { label: '赛项名称', prop: 'name' },
    { label: '主办单位', prop: 'host_unit.label' },
    {
      label: '承办单位',
      prop: 'organizers',
      computed({ row }: { row: ContestItem }) {
        return row.organizers.map(item => item.label).join(',')
      }
    },
    { label: '技术支持单位', prop: 'technical_support_unit.label' },
    {
      label: '赛项类型',
      prop: 'type',
      computed({ row }: { row: ContestItem }) {
        return types.find(item => item.value === row.type)?.label
      }
    },
    {
      label: '指导老师',
      prop: 'teachers',
      computed({ row }: { row: ContestItem }) {
        return row.teachers.map(item => item.name).join(',')
      }
    },
    { label: '报名人数', prop: 'apply_count' },
    { label: '专家人数', prop: 'expert_count' },
    { label: '更新时间', prop: 'updated_time' },
    { label: '操作', slots: 'table-x', width: 200 }
  ]
}

let dialogVisible = $ref(false)
const rowData = ref<ContestItem | undefined | null>(null)

// 新增
function handleAdd() {
  rowData.value = null
  dialogVisible = true
}
// 编辑
function handleUpdate(row: ContestItem) {
  rowData.value = row
  dialogVisible = true
}

function onUpdateSuccess() {
  appList?.refetch()
}
</script>

<template>
  <AppCard title="赛项管理">
    <AppList v-bind="listOptions" ref="appList">
      <template #header-buttons>
        <el-button type="primary" :icon="CirclePlus" v-permission="'competition-create'" @click="handleAdd">
          新增赛项
        </el-button>
      </template>

      <template #table-x="{ row }: { row: ContestItem }">
        <el-button type="primary" round v-permission="'competition-detail'">
          <router-link :to="`/admin/contest/items/${row.id}`" target="_blank">查看</router-link>
        </el-button>
        <el-button type="primary" round @click="handleUpdate(row)" v-permission="'competition-edit'">编辑</el-button>
      </template>
    </AppList>
  </AppCard>
  <FormDialog v-model="dialogVisible" :data="rowData" @update="onUpdateSuccess" v-if="dialogVisible"></FormDialog>
</template>
