<script setup name="menuDialog">
import { getCurrentInstance, ref, shallowRef, watch } from 'vue'
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { save } from '@/http/apis/systemManage/noticeManage'
import { findUrlById } from '@/http/apis/commonApi'
import store from '@/store'

const { proxy } = getCurrentInstance(),
  uploadUrl = store.dictStore.uploadUrl,
  props = defineProps({
    visible: {
      type: Boolean,
      default: false,
      required: true
    },
    data: Object
  }),
  emits = defineEmits(['close']),
  formRef = ref(),
  form = ref({}),
  contentValidator = (rule, value, callback) => {
    const str = value?.replace(/<[^<p>]+>/g, '') // 将所有<p>标签 replace ''
      ?.replace(/<[</p>$]+>/g, '') // 将所有</p>标签 replace ''
      ?.replace(/&nbsp;/gi, '') // 将所有 空格 replace ''
      ?.replace(/<[^<br/>]+>/g, '') // 将所有 换行符 replace ''
    const regu = '^[ ]+$'
    const re = new RegExp(regu)
    if (!str || re.test(str)) {
      callback('请填写公告内容')
    } else {
      callback()
    }
  },
  rules = {
    title: [
      { required: true, message: '请填写公告标题', trigger: 'blur' }
    ],
    content: [
      { required: true, validator: contentValidator, trigger: 'blur' }
    ],
    type: [
      { required: true, message: '请选择公告类型', trigger: 'blur' }
    ],
    enabled: [
      { required: true, message: '请选择公告状态', trigger: 'blur' }
    ]
  },
  // 富文本
  editorRef = shallowRef(), // 编辑器实例，必须用 shallowRef
  toolbarConfig = {},
  editorConfig = {
    MENU_CONF: {
      uploadImage: {
        server: uploadUrl,
        fieldName: 'file',
        // 自定义插入图片
        customInsert (res, insertFn) {
          // 因为自定义插入导致onSuccess与onFailed回调函数不起作用,自己手动处理
          // 先关闭等待的ElMessage
          if (res.code === 200) {
            proxy.$message.success('图片上传成功')
            findUrlById([res.data.id]).then(data => {
              insertFn(data.data[res.data.id])
            })
          } else {
            proxy.$message.error(res.message || '图片上传失败，请重新尝试')
          }
        }
      }
    }
  },
  handleCreated = editor => {
    editorRef.value = editor // 记录 editor 实例，重要！
  },
  submit = async formEl => {
    console.log(form.value)
    if (!formEl) return
    await formEl.validate(async valid => {
      if (valid) {
        await save({
          ...form.value
        })
        proxy.$message.success('提交成功！')
        emits('close', true)
      }
    })
  }

watch(
  () => props.visible,
  async val => {
    if (val) {
      if (props.data?.id) form.value = { ...props.data }
    } else {
      formRef.value.resetFields()
      form.value = {}
    }
  }
)
</script>

<template>
  <el-dialog
    :model-value="visible"
    :title="`${data?.id ? '编辑' : '新增'}公告`"
    width="840px"
    destroy-on-close
    @close="emits('close')"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="auto"
    >
      <el-form-item
        label="公告标题"
        prop="title"
      >
        <el-input
          v-model="form.title"
          placeholder="请输入"
        />
      </el-form-item>
      <el-form-item
        label="公告内容"
        prop="content"
      >
        <div class="wangEditor" style="border:1px solid #dcdfe6">
          <Toolbar
            style="border-bottom: 1px solid #dcdfe6"
            :editor="editorRef"
            :default-config="toolbarConfig"
            mode="simple"
          />
          <Editor
            v-model="form.content"
            style="height: 300px; overflow-y: hidden;width:100%"
            :default-config="editorConfig"
            mode="simple"
            @on-created="handleCreated"
          />
        </div>
      </el-form-item>
      <el-form-item
        label="公告类型"
        prop="type"
      >
        <el-radio-group v-model="form.type" class="ml-4">
          <el-radio :label="1">通知公告</el-radio>
          <el-radio :label="2">帮助文档</el-radio>
          <el-radio :label="3">政策文件</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="公告状态"
        prop="enabled"
      >
        <el-radio-group v-model="form.enabled" class="ml-4">
          <el-radio :label="true">启用</el-radio>
          <el-radio :label="false">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button type="primary" @click="submit(formRef)">
        提交
      </el-button>
      <el-button @click="emits('close')">
        关闭
      </el-button>
    </template>
  </el-dialog>
</template>
