<template>
  <el-dialog
    :model-value="visible"
    title="消息类型"
    width="800px"
    :append-to-body="true"
    :destroy-on-close="true"
    @open="onOpen"
    @close="onClose"
  >
    <editor v-if="content" style="height: 600px" :defaultConfig="editorConfig" @onCreated="onEditorCreate" />

    <template #footer>
      <div>
        <el-button @click="onClose">关闭</el-button>
        <el-button v-if="mode !== 'show' && mode !== ''" type="primary" @click="onSave">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
// todo: 1、import { Editor } from '@wangeditor/editor-for-vue' 有红波浪；2、页面展示时，为什么一点击后出来选择语言的下拉列表？还多了一个回车，删除后有问题

import { computed, ref, shallowRef } from 'vue'
import type { IDomEditor } from '@wangeditor/editor'
import { Editor } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'

import * as apis from '@/apis/heai'
import { SuccessResultCode, type HeaiMessageFlag } from '@cacp/ui'
import { ElMessage } from 'element-plus'

const emits = defineEmits<{
  (e: 'on-close'): void
}>()
const props = defineProps<{
  mode: string
  visible: boolean
  appMsgId: string
  type: boolean
  flag: HeaiMessageFlag
}>()

const content = ref('')
const contentRef = shallowRef<IDomEditor>()
const editorConfig = computed(() => {
  return {
    scroll: true,
    readOnly: props.mode === 'show',
    maxLength: 0,
    hoverbarKeys: {
      pre: {
        menuKeys: []
      }
    },
    MENU_CONF: {
      // codeSelectLang: {
      //   condeLangs: [{ text: 'Javascript', value: 'javascript' }]
      // }
    }
  }
})

async function onOpen() {
  const res = await apis.getRecieve(props.appMsgId, props.type, props.flag) // getSend
  content.value = res.data.content
}

function onClose() {
  if (contentRef.value) {
    contentRef.value.destroy()
  }
  emits('on-close')
}
async function onSave() {
  if (!contentRef.value) {
    return
  }

  const message = {
    appMsgId: props.appMsgId,
    content: contentRef.value!.getText()
  }
  const res = await apis.updateMessage(message)
  if (res.code !== SuccessResultCode) {
    ElMessage.error('保存失败，' + res.message)

    return
  }

  contentRef.value.destroy()

  // todo: 这里直接保存
  emits('on-close')
}

function onEditorCreate(e: IDomEditor) {
  contentRef.value = e

  const node = {
    type: 'pre',
    children: [
      {
        type: 'code',
        language: 'javascript',
        children: [{ text: content.value }]
      }
    ]
  }

  contentRef.value?.clear()
  contentRef.value?.insertNode(node)
}
</script>

<style lang="less" scoped>
.editor {
  width: 100%;
  height: 500px;
  background-color: antiquewhite;
}
</style>
