<script setup lang="ts">
import type { ExperimentItem } from '../types'
import { CirclePlus } from '@element-plus/icons-vue'
import AppList from '@/components/base/AppList.vue'
import { getExperimentList } from '../api'

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

const appList = $ref<InstanceType<typeof AppList> | null>(null)

// 列表配置
const listOptions = {
  remote: {
    httpRequest: getExperimentList,
    params: { name: '' },
    callback(data: { total: number; list: ExperimentItem[] }) {
      const { list, total } = data
      const dataList = list.map(item => {
        const teacher_names = item.teacher.map(teacher => teacher.name).join('、')
        return { ...item, teacher_names }
      })
      return { list: dataList, total }
    }
  },
  filters: [{ type: 'input', prop: 'name', label: '实验名称', placeholder: '请输入实验名称' }],
  columns: [
    { label: '序号', type: 'index', width: 60 },
    { label: '实验课程名称', prop: 'course_name' },
    { label: '实验名称', prop: 'name' },
    { label: '实验学时', prop: 'length' },
    { label: '指导教师', prop: 'teacher_names' },
    { label: '实验类型', prop: 'type_name' },
    { label: '实验总成绩', prop: 'score' },
    { label: '更新人', prop: 'updated_operator_name' },
    { label: '更新时间', prop: 'updated_time' },
    { label: '操作', slots: 'table-x', width: 200 }
  ]
}

let dialogVisible = $ref(false)
const rowData = ref<ExperimentItem | undefined | null>(null)

// 新增
function handleAdd() {
  rowData.value = null
  dialogVisible = true
}
// 编辑
function handleUpdate(row: ExperimentItem) {
  rowData.value = row
  dialogVisible = true
}

function onUpdateSuccess() {
  appList?.refetch()
}
</script>

<template>
  <AppCard title="实验管理">
    <AppList v-bind="listOptions" ref="appList">
      <template #header-buttons>
        <el-button type="primary" :icon="CirclePlus" v-permission="'v1-backend-experiment-create'" @click="handleAdd"
          >新增实验</el-button
        >
      </template>

      <template #table-x="{ row }: { row: ExperimentItem }">
        <el-button type="primary" round v-permission="'v1-backend-experiment-view'">
          <router-link :to="`/admin/system/experiment/${row.id}`" target="_blank">查看</router-link>
        </el-button>
        <!-- <el-button type="primary" round v-permission="'v1-backend-experiment-view'">
          <router-link :to="`/admin/system/experiment/${row.id}`" target="_blank">关联班级与分组</router-link>
        </el-button> -->
        <el-button type="primary" round @click="handleUpdate(row)" v-permission="'v1-backend-experiment-update'"
          >编辑</el-button
        >
      </template>
    </AppList>
  </AppCard>
  <FormDialog v-model="dialogVisible" :data="rowData" @update="onUpdateSuccess" v-if="dialogVisible"></FormDialog>
</template>
