<script setup lang="ts">
import { CirclePlus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import AppList from '@/components/base/AppList.vue'
import { getDrawLotList, deleteDrawLot } from '../api'

const FormDialog = defineAsyncComponent(() => import('./ViewDrawLotsFormDialog.vue'))
const StudentsDialog = defineAsyncComponent(() => import('./ViewDrawLotsStudentsDialog.vue'))

interface Props {
  id: string
}
const props = defineProps<Props>()

const appList = $ref<InstanceType<typeof AppList> | null>(null)
// 列表配置
const listOptions = {
  hasPagination: false,
  remote: {
    httpRequest: getDrawLotList,
    params: { competition_id: props.id },
    callback(res: any) {
      return res?.items ? { list: res.items } : { list: [] }
    }
  },
  columns: [
    { label: '序号', type: 'index', width: 60 },
    {
      label: '考试类型',
      prop: 'type',
      computed({ row }: { row: any }) {
        const map: Record<string, string> = { '1': '1+X理论考试', '2': '商业数据分析师实操考试' }
        return map[row.type] || row.type
      }
    },
    { label: '总桌数', prop: 'total' },
    { label: '创建人', prop: 'created_operator.real_name' },
    { label: '创建时间', prop: 'created_time' },
    { label: '更新时间', prop: 'updated_time' },
    { label: '操作', slots: 'table-x', width: 220 }
  ]
}

let dialogVisible = $ref(false)
let studentsDialogVisible = $ref(false)
const rowData = ref<any>()
// 新增
function handleAdd() {
  rowData.value = undefined
  dialogVisible = true
}
// 编辑
function handleUpdate(row: any) {
  rowData.value = row
  dialogVisible = true
}
// 查阅
function handleView(row: any) {
  rowData.value = row
  studentsDialogVisible = true
}
// 删除
function handleRemoveClass(row: any) {
  ElMessageBox.confirm('确定要删除吗？', '提示').then(() => {
    deleteDrawLot({ id: row.id }).then(() => {
      ElMessage({ message: '删除成功', type: 'success' })
      onUpdateSuccess()
    })
  })
}
function onUpdateSuccess() {
  appList?.refetch()
}
</script>

<template>
  <AppList v-bind="listOptions" ref="appList">
    <template #header-buttons>
      <el-button type="primary" :icon="CirclePlus" @click="handleAdd">新增</el-button>
    </template>
    <template #table-x="{ row }">
      <el-button link round type="primary">
        <router-link :to="{ path: '/drawLots', query: { competition_id: id, id: row.id, type: row.type } }" target="_blank">去抽签</router-link>
      </el-button>
      <el-button link round type="info" @click="handleView(row)">查看</el-button>
      <el-button link round type="primary" @click="handleUpdate(row)">编辑</el-button>
      <el-button link round type="danger" @click="handleRemoveClass(row)">删除</el-button>
    </template>
  </AppList>
  <FormDialog v-model="dialogVisible" :data="rowData" @update="onUpdateSuccess" v-if="dialogVisible"></FormDialog>
  <StudentsDialog v-model="studentsDialogVisible" :data="rowData" v-if="studentsDialogVisible"></StudentsDialog>
</template>
