<template>
  <div ref="editor" :style="{ width }" @click="handleClick"> </div>
  <AiAnswerModal @register="registerModal" @get-fill-val="handleFill" />
</template>

<script lang="ts" setup>
  import { onBeforeUnmount, onMounted, ref, watchEffect, computed } from 'vue';
  import WangEditor from 'wangeditor';
  import { AiAnswerModal } from '/@/components/AiAnswer';
  import { uploadMultiApi } from '/@/api/sys/upload';
  import { useModal } from '/@/components/Modal';
  import { getFileList } from '/@/api/system/file';
  import { getFileUrl } from '/@/utils/event/design';

  const props = defineProps({
    value: {
      type: String,
      default: '',
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    width: {
      type: [String, Number],
    },
  });

  const [registerModal, { openModal }] = useModal();

  const emits = defineEmits(['update:value', 'change', 'blur', 'click']);
  const editor = ref();
  const isFirst = ref(true);

  let instance: WangEditor | null;

  const { BtnMenu } = WangEditor;

  class AIMenu extends BtnMenu {
    constructor(editor) {
      // data-title属性表示当鼠标悬停在该按钮上时提示该按钮的功能简述
      const $elem = WangEditor.$(
        `<div class="w-e-menu" data-title="AI">
                <button style="color:#999">AI</button>
            </div>`,
      );
      super($elem, editor);
    }
    // 菜单点击事件
    clickHandler() {
      openModal();
    }
    tryChangeActive() {
      this.active();
    }
  }

  const bgc = computed(() => {
    return props.disabled ? '#f5f5f5' : '#fff';
  });

  onMounted(() => {
    instance = new WangEditor(editor.value);

    const menuKey = 'AiMenuKey';
    instance.menus.extend(menuKey, AIMenu);
    instance.config.menus = instance.config.menus.concat(menuKey);

    instance.config.customUploadImg = async function (resultText) {
      try {
        let res = await uploadMultiApi(
          {
            name: 'file',
            file: resultText,
          },
          '',
        );
        if (res?.length > 0) {
          let fileList = await getFileList({ folderId: res[0].folderId });
          if (fileList.length) {
            fileList.forEach((x) => {
              instance?.cmd.do('insertHTML', '<img src="' + getFileUrl(x) + '"></img>');
            });
          }
        }
      } catch (error) {
        console.error(error);
      }
    };
    Object.assign(instance.config, {
      zIndex: 9,
      onchange: (html: string) => {
        emits('change', html);
        emits('update:value', html);
      },
      onblur: (html: string) => {
        if (!isFirst.value) {
          //第一次进入页面不触发blur
          emits('blur', html);
        }
        isFirst.value = false;
      },
    });
    instance.create();
    setTimeout(() => {
      if (props.value && instance?.txt) {
        instance.txt.html(props.value);
      }
    }, 500);
    watchEffect(() => {
      instance && props.disabled ? instance.disable() : instance?.enable();
      instance?.txt.html(props.value);
    });
  });

  // watch(
  //   () => props.value,
  //   (val) => {
  //     instance?.txt.text(val);
  //   },
  //   {
  //     immediate: true,
  //   },
  // );

  onBeforeUnmount(() => {
    instance && instance.destroy();
    instance = null;
  });

  const handleFill = (info) => {
    instance?.txt.append(info);
  };
  function handleClick() {
    emits('click');
  }
</script>
<style lang="less" scoped>
  :deep(.w-e-text-container) {
    background-color: v-bind(bgc);
    border-radius: 0 0 4px 4px;
    // height: auto !important;
    min-height: 300px;
  }

  :deep(.w-e-toolbar) {
    border-radius: 4px 4px 0 0;
  }
</style>
