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

interface Props {
  experiment_id: string
  list: ExperimentDiscussType[]
}
const props = defineProps<Props>()

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

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

// 提交
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')
    formRef?.resetFields()
  })
}
let publishVisible = $ref(true)
watchEffect(() => {
  publishVisible = !props.list.length
})
</script>

<template>
  <el-row justify="start" style="padding-top: 10px">
    <el-button type="primary" @click="publishVisible = true" v-if="!publishVisible">新话题</el-button>
  </el-row>
  <el-form ref="formRef" :model="form" :rules="rules" style="padding: 20px 0 10px" v-if="publishVisible">
    <el-form-item prop="title">
      <el-input v-model="form.title" placeholder="话题标题"></el-input>
    </el-form-item>
    <el-form-item prop="content">
      <el-input type="textarea" v-model="form.content" placeholder="话题描述" :autosize="{ minRows: 4, maxRows: 6 }" />
    </el-form-item>
    <el-row justify="space-between">
      <el-button type="info" @click="publishVisible = false">收起</el-button>
      <el-button type="primary" @click="handleSubmit">发表</el-button>
    </el-row>
  </el-form>
</template>
