<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 { getAllExamList, deleteExam } from '../api'

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

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

const appList = $ref<InstanceType<typeof AppList> | null>(null)
// 列表配置
const listOptions = {
  hasPagination: false,
  remote: {
    httpRequest: getAllExamList,
    params: { competition_id: props.id },
    callback(res: any) {
      return res?.list ? { list: res.list } : { list: [] }
    }
  },
  columns: [
    { label: '序号', type: 'index', width: 60 },
    { label: '试卷名称', prop: 'exam_info.name' },
    {
      label: '试卷类型',
      prop: 'type',
      computed({ row }: { row: any }) {
        const map: Record<string, string> = { '1': '正式比赛试卷', '2': '训练试卷' }
        return map[row.type] || row.type
      }
    },
    {
      label: '模块',
      prop: 'sort',
      computed({ row }: { row: any }) {
        return row.type === '1' ? row.sort : ''
      }
    },
    { label: '创建人', prop: 'created_operator_name' },
    { label: '创建时间', prop: 'created_time' },
    { label: '更新时间', prop: 'updated_time' },
    { label: '操作', slots: 'table-x', width: 180 }
  ]
}

let dialogVisible = $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) {
  const [paper] = row.exam_info.paper_list
  if (!paper) return
  const qaURL = `${import.meta.env.VITE_QA_CENTER_URL}/paper/detail/${paper.paper_id}`
  window.open(qaURL)
}
// 删除
function handleRemoveClass(row: any) {
  ElMessageBox.confirm('确定要删除吗？', '提示').then(() => {
    deleteExam({ 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" v-permission="'competition-book-create'">新增</el-button>
    </template>
    <template #table-x="{ row }">
      <el-button link round type="info" @click="handleView(row)" v-permission="'competition-book-detail'">查阅</el-button>
      <el-button link round type="primary" @click="handleUpdate(row)" v-permission="'competition-book-update'">编辑</el-button>
      <el-button link round type="danger" @click="handleRemoveClass(row)" v-permission="'competition-book-delete'">删除</el-button>
    </template>
  </AppList>
  <FormDialog v-model="dialogVisible" :data="rowData" @update="onUpdateSuccess" v-if="dialogVisible"></FormDialog>
</template>
