<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 { getExamList, 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: getExamList,
    params: { experiment_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: 'created_operator_name' },
    { label: '创建时间', prop: 'created_time' },
    { label: '更新时间', prop: 'updated_time' },
    { label: '操作', slots: 'table-x', width: 120 }
  ]
}

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 handleRemove(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="primary" @click="handleUpdate(row)" v-permission="'competition-book-update'">编辑</el-button>
      <el-button link round type="danger" @click="handleRemove(row)" v-permission="'competition-book-delete'">删除</el-button>
    </template>
  </AppList>
  <FormDialog v-model="dialogVisible" :id="id" :data="rowData" @update="onUpdateSuccess" v-if="dialogVisible"></FormDialog>
</template>
