<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import type { ExperimentInfo } from '../types'
import { ElMessage } from 'element-plus'
import AppEditor from '@/components/base/AppEditor.vue'
import { getExperimentPrepare, updateExperimentPrepare } from '../api'

interface Props {
  data: ExperimentInfo
}

const props = defineProps<Props>()

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

const formRef = $ref<FormInstance>()
const form = reactive({
  experiment_id: props.data.id,
  detail: ''
})
const rules = ref<FormRules>({
  detail: [{ required: true, message: '请输入', trigger: 'blur' }]
})

function fetchInfo() {
  getExperimentPrepare({ experiment_id: props.data.id }).then(res => {
    Object.assign(form, res.data.detail)
  })
}

onMounted(() => {
  fetchInfo()
})
// 提交
function handleSubmit() {
  formRef?.validate().then(update)
}
// 修改
const update = () => {
  updateExperimentPrepare(form).then(() => {
    ElMessage({ message: '保存成功', type: 'success' })
    emit('update:modelValue', false)
  })
}
</script>

<template>
  <el-dialog
    append-to-body
    title="实验准备"
    :close-on-click-modal="false"
    width="800px"
    @update:modelValue="$emit('update:modelValue')">
    <el-form ref="formRef" :model="form" :rules="rules" label-suffix="：">
      <el-form-item label="实验名称">{{ data.name }} </el-form-item>
      <el-form-item prop="detail">
        <AppEditor v-model="form.detail"></AppEditor>
      </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>
