<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import type { ExperimentItem, ClassItem } from '../types'
import { ElMessage } from 'element-plus'
import { experimentAddClassGroup } from '../api'

interface Props {
  data: ClassItem
}
const props = defineProps<Props>()

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

const detail = $ref<ExperimentItem>(inject('detail'))

const formRef = $ref<FormInstance>()
const form = reactive({ name: '' })
const rules = ref<FormRules>({
  name: [{ required: true, message: '请输入实验小组名称', trigger: 'blur' }]
})

// 提交
function handleSubmit() {
  formRef?.validate().then(handleCreate)
}
// 创建
const handleCreate = () => {
  const params = { ...form, experiment_id: detail.id, class_id: props.data.id }
  experimentAddClassGroup(params).then(() => {
    ElMessage({ message: '创建成功', type: 'success' })
    emit('update')
    emit('update:modelValue', false)
  })
}
</script>

<template>
  <el-dialog
    title="新增实验分组"
    :close-on-click-modal="false"
    width="600px"
    @update:modelValue="$emit('update:modelValue')"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="110px">
      <el-form-item label="实验名称">{{ detail.name }}</el-form-item>
      <el-form-item label="实验小组名称" prop="name">
        <el-input v-model="form.name"></el-input>
      </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>
