<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import { getExperimentsList, bindExperiment } from '../api'

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

const emit = defineEmits<{
  (e: 'update'): void
  (e: 'update:modelValue', visible: boolean): void
}>()

const formRef = $ref<FormInstance>()
const form = reactive<any>({
  id: ''
})

const title = $computed(() => {
  return '关联实验'
})

let list = $ref<Record<string, any>[]>([])
const loading = ref(false)
// 获取关联考试列表
function fetchExamList(query?: string) {
  loading.value = true
  getExperimentsList({ type: 4, name: query, 'per-page': 1000 }).then((res: any) => {
    loading.value = false
    list = res.data?.list || []
  })
}
onMounted(() => {
  fetchExamList()
})
// 提交
function handleSubmit() {
  bindExperiment({ id: props.id, experiment_id: form.id }).then(() => {
    ElMessage({ message: '绑定成功', type: 'success' })
    emit('update')
    emit('update:modelValue', false)
  })
}
</script>

<template>
  <el-dialog
    :title="title"
    :close-on-click-modal="false"
    width="500px"
    @update:modelValue="value => $emit('update:modelValue', value)"
  >
    <el-form ref="formRef" :model="form" label-width="90px">
      <el-form-item label="选择实验">
        <el-select
          v-model="form.id"
          filterable
          remote
          reserve-keyword
          placeholder="输入实验名称"
          remote-show-suffix
          :remote-method="fetchExamList"
          :loading="loading"
          style="width: 340px"
        >
          <el-option v-for="item in list" :key="item.value" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-row justify="center">
        <el-button type="primary" round auto-insert-space @click="handleSubmit">保存</el-button>
        <el-button round auto-insert-space @click="$emit('update:modelValue', false)">取消</el-button>
      </el-row>
    </el-form>
  </el-dialog>
</template>
