<template>
  <vab-dialog v-model="dialogFormVisible" append-to-body destroy-on-close :title="title" width="780px" @close="close">
    <el-form ref="formRef" label-width="80px" :model="form" :rules="rules">
      <el-row>
        <el-col :span="12">
          <el-form-item label="公告标题" prop="noticeTitle">
            <el-input v-model="form.noticeTitle" placeholder="请输入公告标题" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="公告类型" prop="noticeType">
            <el-select v-model="form.noticeType" placeholder="请选择">
              <el-option v-for="dict in sys_notice_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="状态">
            <el-radio-group v-model="form.status">
              <el-radio v-for="dict in sys_notice_status" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="内容">
            <div class="notice-editor-container">
              <toolbar :editor="editorRef" style="border-bottom: 1px solid var(--el-border-color)" />
              <editor v-model="form.noticeContent" class="wang-editor-content" :default-config="editorConfig" @on-created="handleCreated" />
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="save">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </template>
  </vab-dialog>
</template>

<script lang="ts" setup>
import type { IDomEditor } from '@wangeditor/editor'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'
import type { FormInstance } from 'element-plus'
import { doAdd, doEdit, getNotice } from '/@/api/noticeManagement'
import { getToken } from '/@/utils/token'

type InsertFnType = (url: string, alt: string, href: string) => void

defineOptions({
  name: 'NoticeManagementEdit',
})

const { proxy } = getCurrentInstance() as any
const { sys_notice_type, sys_notice_status } = proxy.useDict('sys_notice_type', 'sys_notice_status')

const emit = defineEmits(['fetch-data'])

const editorRef = shallowRef<IDomEditor | undefined>()
const editorConfig = reactive<any>({
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      server: `${import.meta.env.VITE_APP_BASE_URL}/common/upload`, // 您的服务器地址，注意：当前接口格式特殊与其他vab接口不同，请查看vip文档
      fieldName: 'file',
      allowedFileTypes: ['image/*'],
      headers: {
        Authorization: `Bearer ${getToken()}`,
      }, // 如需传递token请写到在这里
      // 自定义插入图片
      customInsert(res: any, insertFn: InsertFnType) {
        // TS 语法
        // customInsert(res, insertFn) {                  // JS 语法
        // res 即服务端的返回结果

        // 从 res 中找到 url alt href ，然后插入图片
        console.log(res)
        insertFn(res.url, res.originalFilename, res.url)
      },
    },
  },
})

const formRef = ref<FormInstance>()
const form = ref<any>({
  noticeId: undefined,
  noticeTitle: undefined,
  noticeType: undefined,
  noticeContent: undefined,
  status: '0',
})
const rules = reactive<any>({
  noticeTitle: [{ required: true, message: '公告标题不能为空', trigger: 'blur' }],
  noticeType: [{ required: true, message: '公告类型不能为空', trigger: 'change' }],
})
const title = ref<string>('')
const dialogFormVisible = ref<boolean>(false)

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor: IDomEditor) => {
  editorRef.value = editor
}

const showEdit = (row?: any) => {
  reset()
  if (row && row.noticeId) {
    title.value = '编辑'
    getNotice(row.noticeId).then((response: any) => {
      const { data } = response
      form.value = JSON.parse(JSON.stringify(data))
      dialogFormVisible.value = true
    })
  } else {
    title.value = '添加'
    dialogFormVisible.value = true
  }
}

/** 表单重置 */
function reset() {
  form.value = {
    noticeId: undefined,
    noticeTitle: undefined,
    noticeType: undefined,
    noticeContent: undefined,
    status: '0',
  }
  proxy.resetForm('formRef')
}

const close = () => {
  editorRef.value?.clear()
  formRef.value?.clearValidate()
  formRef.value?.resetFields()
  emit('fetch-data')
}

const cancel = () => {
  close()
  dialogFormVisible.value = false
}

const save = () => {
  formRef.value?.validate(async (valid: any) => {
    if (valid) {
      if (form.value.noticeId) {
        await doEdit(form.value)
        await $baseMessage('修改成功', 'success', 'hey')
      } else {
        await doAdd(form.value)
        await $baseMessage('添加成功', 'success', 'hey')
      }
      cancel()
    }
  })
}

defineExpose({
  showEdit,
})
</script>

<style lang="scss" scoped>
:deep() {
  .el-select {
    width: 100%;
  }
}
</style>

<style lang="scss">
.notice-editor-container {
  padding: 0 !important;
  // margin: -19px -19px 19px -19px;
  overflow: hidden !important;
  background: var(--el-background-color) !important;
  border: 1px solid var(--el-border-color) !important;

  &.w-e-full-screen-container {
    z-index: 9999 !important;
  }

  .w-e-bar-divider {
    display: none;
  }

  .w-e-toolbar-init {
    border-bottom: 1px solid var(--el-border-color) !important;
  }

  .wang-editor-content {
    // width: 70%;
    min-height: calc(var(--el-container-height) - 110px) !important;
    // margin: 20px auto 20px auto;
    background-color: var(--el-color-white);
    border: 0;
  }

  #w-e-textarea-1 {
    // margin: var(--el-margin) !important;
  }

  .w-e-text-placeholder {
    top: 10px !important;
  }

  .wang-editor-footer {
    width: 70%;
    margin: auto;
  }

  @media (max-width: 768px) {
    .wang-editor-title,
    .wang-editor-content,
    .wang-editor-footer {
      width: 90%;
    }
  }
}

.wang-editor-dialog {
  img {
    max-width: 100%;
  }
}
</style>
