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

interface Props {
  experiment_id: string
}
const props = defineProps<Props>()

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

const formRef = $ref<FormInstance>()
const form = reactive({ title: '', content: '' })
const rules = ref<FormRules>({
  title: [{ required: true, message: '请输入话题标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入话题描述', trigger: 'blur' }]
})

// 提交
function handleSubmit() {
  formRef?.validate().then(handleAdd)
}
// 创建话题
function handleAdd() {
  const params = { ...form, experiment_id: props.experiment_id }
  addExperimentDiscuss(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">
      <el-form-item label="话题标题" prop="title">
        <el-input v-model="form.title"></el-input>
      </el-form-item>
      <el-form-item label="话题描述" prop="content">
        <el-input type="textarea" v-model="form.content" :autosize="{ minRows: 4, maxRows: 6 }" />
      </el-form-item>
      <el-row justify="center">
        <el-button round auto-insert-space @click="$emit('update:modelValue', false)">取消</el-button>
        <el-button type="primary" round auto-insert-space @click="handleSubmit">发布</el-button>
      </el-row>
    </el-form>
  </el-dialog>
</template>
