<script setup lang="ts">
import type { ContestVideoItem } from '../types'
import { CirclePlus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { usePrecision } from '@vueuse/math'
import AppList from '@/components/base/AppList.vue'
import ViewVideoPreviewDialog from './ViewVideoPreviewDialog.vue'
import { getContestVideoList, deleteContestVideo } from '../api'

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

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

const appList = $ref<InstanceType<typeof AppList> | null>(null)
// 列表配置
const listOptions = {
  hasPagination: false,
  remote: {
    httpRequest: getContestVideoList,
    params: { competition_id: props.id }
  },
  columns: [
    { label: '序号', type: 'index', width: 60 },
    { label: '操作视频名称', prop: 'name' },
    {
      label: '视频时长（分钟）',
      prop: 'duration',
      computed({ row }: { row: ContestVideoItem }) {
        const duration = parseInt(row.duration)
        return duration ? usePrecision(duration / 60, 2).value : 0
      }
    },
    { label: '创建人', prop: 'create_user.real_name' },
    { label: '创建时间', prop: 'created_time' },
    { label: '更新时间', prop: 'updated_time' },
    { label: '操作', slots: 'table-x', width: 180 }
  ]
}

let dialogVisible = $ref(false)
const rowData = ref<ContestVideoItem>()
// 新增
function handleAdd() {
  rowData.value = undefined
  dialogVisible = true
}
// 编辑
function handleUpdate(row: ContestVideoItem) {
  rowData.value = row
  dialogVisible = true
}
// 查阅
let viewVisible = $ref(false)
function handleView(row: ContestVideoItem) {
  rowData.value = row
  viewVisible = true
}
// 删除
function handleRemoveClass(row: ContestVideoItem) {
  ElMessageBox.confirm('确定要删除吗？', '提示').then(() => {
    deleteContestVideo({ 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-video-create'"
        >新增</el-button
      >
    </template>
    <template #table-x="{ row }">
      <el-button link round type="info" @click="handleView(row)" v-permission="'competition-video-detail'"
        >查阅</el-button
      >
      <el-button link round type="primary" @click="handleUpdate(row)" v-permission="'competition-video-update'"
        >编辑</el-button
      >
      <el-button link round type="danger" @click="handleRemoveClass(row)" v-permission="'competition-video-delete'"
        >删除</el-button
      >
    </template>
  </AppList>
  <FormDialog v-model="dialogVisible" :data="rowData" @update="onUpdateSuccess" v-if="dialogVisible"></FormDialog>
  <ViewVideoPreviewDialog v-model="viewVisible" :data="rowData" v-if="viewVisible && rowData"></ViewVideoPreviewDialog>
</template>
