<script setup lang="ts">
import type { ContestBookItem } from '../types'
import { CirclePlus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import AppList from '@/components/base/AppList.vue'
import ViewBookPreviewDialog from './ViewBookPreviewDialog.vue'
import { getContestBooks, deleteContestBook } from '../api'

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

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

const appList = $ref<InstanceType<typeof AppList> | null>(null)
// 列表配置
const listOptions = {
  hasPagination: false,
  remote: {
    httpRequest: getContestBooks,
    params: { competition_id: props.id },
    callback(res: any) {
      // return res.detail?.id ? { list: [res.detail] } : { list: [] }
      return res?.items ? { list: res?.items } : { list: [] }
    }
  },
  columns: [
    { label: '序号', type: 'index', width: 60 },
    { label: '训练指导书名称', prop: 'name' },
    { label: '文件类型', prop: 'type' },
    { label: '创建人', prop: 'created_operator.real_name' },
    { label: '创建时间', prop: 'updated_time' },
    { label: '更新时间', prop: 'updated_time' },
    { label: '操作', slots: 'table-x', width: 180 }
  ]
}

let dialogVisible = $ref(false)
const rowData = ref<ContestBookItem>()
// 新增
function handleAdd() {
  rowData.value = undefined
  dialogVisible = true
}
// 编辑
function handleUpdate(row: ContestBookItem) {
  rowData.value = row
  dialogVisible = true
}
// 查阅
let viewVisible = $ref(false)
function handleView(row: ContestBookItem) {
  rowData.value = row
  viewVisible = true
}
// 删除
function handleRemoveClass(row: ContestBookItem) {
  ElMessageBox.confirm('确定要删除吗？', '提示').then(() => {
    deleteContestBook({ 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>
  <ViewBookPreviewDialog v-model="viewVisible" :data="rowData" v-if="viewVisible && rowData"></ViewBookPreviewDialog>
</template>
