<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: '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 = `https://qa-center.ezijing.com/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>
