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

const SelectExperiment = defineAsyncComponent(() => import('./SelectExperiment.vue'))

const props = defineProps<{
  id: string
  experiments?: ExperimentItem[]
}>()

const emit = defineEmits<{
  (e: 'update'): void
}>()

const appList = ref<InstanceType<typeof AppList> | null>(null)
// 列表配置
const listOptions = computed(() => {
  return {
    data: props.experiments,
    columns: [
      { label: '序号', type: 'index', width: 60 },
      { label: '实验名称', prop: 'name' },
      { label: '实验类型', prop: 'type_name' },
      { label: '更新人', prop: 'updated_operator_name' },
      { label: '更新时间', prop: 'updated_time' },
      { label: '操作', slots: 'table-x', width: 180 },
    ],
  }
})

const dialogVisible = ref(false)
const handleAdd = () => {
  dialogVisible.value = true
}

const handleRemove = (row: ExperimentItem) => {
  ElMessageBox.confirm('确定要删除吗？', '提示').then(() => {
    bindExperiment({ case_id: props.id, experiment_id: row.id, type: 'delete' }).then(() => {
      ElMessage({ message: '删除成功', type: 'success' })
      emit('update')
    })
  })
}
const handleBind = (id: string) => {
  bindExperiment({ case_id: props.id, experiment_id: id, type: 'add' }).then(() => {
    ElMessage({ message: '关联成功', type: 'success' })
    emit('update')
    dialogVisible.value = false
  })
}
</script>

<template>
  <AppList v-bind="listOptions" ref="appList">
    <template #header-buttons>
      <el-button type="primary" :icon="CirclePlus" @click="handleAdd">关联实验</el-button>
    </template>
    <template #table-x="{ row }">
      <el-button text type="primary"
        ><router-link :to="`/admin/lab/experiment/${row.id}`" target="_blank">查看实验</router-link></el-button
      >

      <el-button text type="danger" @click="handleRemove(row)" v-permission="'v1-backend-experiment-class-add'"
        >删除</el-button
      >
    </template>
  </AppList>
  <SelectExperiment v-model="dialogVisible" @bind="handleBind" v-if="dialogVisible" />
</template>
