<template>
  <el-dialog v-model="visible" :title="title" width="800px" destroy-on-close>
    <el-form ref="formRef" :model="form" label-width="80px" label-position="top">
      <el-form-item label="文章标题">
        <el-input v-model="form.title" placeholder="请输入标题" />
      </el-form-item>
      <el-form-item label="所属栏目">
        <el-select v-model="form.category" style="width: 100%">
          <el-option label="通知公告" value="notice" />
          <el-option label="新闻资讯" value="news" />
          <el-option label="规章制度" value="rule" />
          <el-option label="安全教育" value="safety" />
        </el-select>
      </el-form-item>
      <el-form-item label="设置">
        <el-checkbox v-model="form.top">置顶显示</el-checkbox>
        <el-checkbox v-model="form.push">发送推送通知</el-checkbox>
      </el-form-item>
      <el-form-item label="文章内容">
        <vab-editor v-model="form.content" height="400px" />
      </el-form-item>
      <el-form-item label="附件">
        <el-upload action="#" :auto-upload="false" multiple>
          <el-button icon="upload-line">点击上传附件</el-button>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button @click="handleSaveDraft">存草稿</el-button>
      <el-button type="primary" @click="handleSubmit">立即发布</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'

const emit = defineEmits(['success'])

const visible = ref(false)
const isEdit = ref(false)

const form = reactive({
  title: '',
  category: 'notice',
  top: false,
  push: true,
  content: ''
})

const title = computed(() => isEdit.value ? '编辑文章' : '发布新文章')

const open = (row) => {
  if (row) {
    isEdit.value = true
    Object.assign(form, row)
  } else {
    isEdit.value = false
    Object.assign(form, { title: '', category: 'notice', top: false, push: true, content: '' })
  }
  visible.value = true
}

const handleSaveDraft = () => {
  visible.value = false
  ElMessage.info('已保存至草稿箱')
  emit('success')
}

const handleSubmit = () => {
  visible.value = false
  ElMessage.success('发布成功！' + (form.push ? '已推送至全校师生' : ''))
  emit('success')
}

defineExpose({
  open
})
</script>
