<template>
  <div class="ri-wrap">
    <!-- 公式弹窗 -->
    <el-popover
      v-model="formulaVisible"
      popper-class="ri-formula-popover"
      placement="top-start"
      trigger="manual"
    >
      <div class="ri-formula-container">
        <iframe
          :src="`https://zjyw.icve.com.cn/kityformula-editor/kityFormula.html?c=${formulaValue}`"
          ref="editorFrame"
          class="ri-formula-iframe"
        ></iframe>
        <el-button type="primary" size="small" class="ri-formula-save" @click="saveFormula">保存</el-button>
      </div>
      <!-- 触发锚点（隐藏，通过 v-model 手动控制） -->
      <span slot="reference"></span>
    </el-popover>

    <!-- 编辑器容器 -->
    <div
      class="ri-editor-wrap"
      :style="{ minHeight: height + 'px' }"
      :class="{ 'ri-editor-focus': isFocused }"
    >
      <Editor
        class="ri-editor"
        :style="{ minHeight: height + 'px' }"
        :defaultConfig="editorConfig"
        :mode="'simple'"
        @onCreated="onCreated"
        @onChange="onChange"
        @onFocus="isFocused = true"
        @onBlur="isFocused = false"
        @customPaste="customPaste"
      />
    </div>

    <!-- 插入公式按钮 -->
    <div class="ri-toolbar">
      <span class="ri-formula-btn" @click="openFormula">
        <img src="../static/formula.png" class="ri-fx-img" alt="fx" />
        插入公式
      </span>
    </div>
  </div>
</template>

<script>
import { Boot } from '@wangeditor/editor';
import formulaModule from '@wangeditor/plugin-formula';
import { Editor } from '@wangeditor/editor-for-vue';

let _booted = false;
function ensureBoot() {
  if (!_booted) {
    try {
      Boot.registerModule(formulaModule);
    } catch (e) {}
    _booted = true;
  }
}
ensureBoot();

export default {
  name: 'RichInput',
  components: { Editor },
  props: {
    value: {
      type: String,
      default: '',
    },
    placeholder: {
      type: String,
      default: '请输入内容，支持公式编辑',
    },
    height: {
      type: Number,
      default: 90,
    },
  },
  data() {
    return {
      editor: null,
      isFocused: false,
      formulaVisible: false,
      formulaValue: '',
      editorConfig: {
        placeholder: this.placeholder,
        hoverbarKeys: {
          formula: {
            menuKeys: [],
          },
        },
      },
    };
  },
  watch: {
    value(val) {
      if (!this.editor) return;
      try {
        const current = this.editor.getHtml();
        if (val !== current) {
          // 直接 nextTick 就够，因为此时编辑器已经初始化完成
          this.$nextTick(() => {
            try {
              this.editor.setHtml(val || '<p><br></p>');
            } catch (e) {}
          });
        }
      } catch (e) {}
    },
  },
  mounted() {
    window.addEventListener('message', this.latexMessage);
  },
  beforeDestroy() {
    window.removeEventListener('message', this.latexMessage);
    if (this.editor) {
      this.editor.destroy();
    }
  },
  methods: {
    onCreated(editor) {
      this.editor = Object.seal(editor);
    },

    onChange(editor) {
      this.$emit('input', editor.getHtml());
    },

    openFormula() {
      if (!this.editor) return;
      this.editor.focus();
      this.formulaValue = '';
      this.formulaVisible = true;
    },

    saveFormula() {
      if (this.$refs.editorFrame) {
        this.$refs.editorFrame.contentWindow.postMessage('message', '*');
      }
      setTimeout(() => {
        this.formulaVisible = false;
      }, 100);
    },

    latexMessage(event) {
      if (!this.formulaVisible) return;
      const { mceAction, content } = event.data || {};
      if (mceAction !== 'insertContent') return;
      if (!content) return;

      const match = content.match(/data-latex="([^"]+)"/);
      if (!match) return;

      let latex = match[1].replace(/\s/g, '');
      if (latex === '\\placeholder') return;

      if (!this.editor) return;

      try {
        this.editor.restoreSelection(); // 加 try-catch 兜底
      } catch (e) {
        // restoreSelection 失败时，把光标移到末尾
        this.editor.focus(true);
      }

      const formulaNode = {
        type: 'formula',
        value: latex,
        children: [{ text: '' }],
      };
      this.editor.insertNode(formulaNode);
    },

    customPaste(editor, event, callback) {
      const text = event.clipboardData.getData('text/plain');
      editor.insertText(text);
      event.preventDefault();
      callback(false);
    },
  },
};
</script>

<style lang="scss" scoped>
.ri-wrap {
  width: 100%;
}

.ri-editor-wrap {
  border: 1px solid #e0d8ff;
  border-radius: 8px;
  overflow: hidden;
  transition: border-color 0.2s;
  background: #fff;

  &.ri-editor-focus {
    border-color: #6040e0;
  }
}

.ri-editor {
  background: transparent;
  font-size: 13px;
  color: #333;
}

.ri-toolbar {
  display: flex;
  justify-content: flex-end;
  margin-top: 4px;
}

.ri-formula-btn {
  display: inline-flex;
  align-items: center;
  gap: 3px;
  font-size: 12px;
  color: #6040e0;
  cursor: pointer;
  user-select: none;
  font-weight: bold;
  padding: 2px 6px;
  border-radius: 4px;
  transition: background 0.2s;

  &:hover {
    background: rgba(96, 64, 224, 0.08);
  }
}

.ri-fx-img {
  width: 16px;
  height: 16px;
  object-fit: contain;
  vertical-align: middle;
}

.ri-formula-iframe {
  width: 782px;
  height: 420px;
  border: none;
  outline: none;
}

.ri-formula-save {
  position: absolute;
  right: 24px;
  bottom: 10px;
}

.ri-formula-container {
  position: relative;
  padding: 24px;
  border-radius: 16px;
  background: linear-gradient(
    103.5deg,
    rgba(255, 238, 238, 1) 0%,
    rgba(255, 255, 255, 1) 29%,
    rgba(255, 255, 255, 1) 71%,
    rgba(204, 238, 255, 1) 100%
  );
}
</style>

<style lang="scss">
.ri-formula-popover {
  padding: 2px;
  border-radius: 16px;
  z-index: 3000 !important;
}

/* 覆盖 wangeditor 默认样式，使其适配字段高度 */
.ri-editor-wrap {
  .w-e-text-container {
    background: transparent !important;

    p {
      span {
        background-color: transparent !important;
      }
    }
  }

  .w-e-text-placeholder {
    font-size: 13px;
    color: #bbb;
  }

  /* 隐藏工具栏（simple 模式无工具栏，仅保留悬浮栏） */
  .w-e-toolbar {
    display: none !important;
  }
}
</style>

<style src="@wangeditor/editor/dist/css/style.css"></style>
