<template>
  <textarea ref="textarea"></textarea>
</template>

<script>
import tinymce from 'tinymce/tinymce';
import 'tinymce/skins/ui/oxide/skin';
import 'tinymce/themes/silver/theme';
import 'tinymce/icons/default/icons';
import 'tinymce/models/dom/model';
import 'tinymce/plugins/advlist';
import 'tinymce/plugins/autolink';
import 'tinymce/plugins/autosave';
import 'tinymce/plugins/code';
import 'tinymce/plugins/directionality';
import 'tinymce/plugins/fullscreen';
import 'tinymce/plugins/insertdatetime';
import 'tinymce/plugins/link';
import 'tinymce/plugins/anchor';
import 'tinymce/plugins/lists';
import 'tinymce/plugins/media';
import 'tinymce/plugins/nonbreaking';
import 'tinymce/plugins/pagebreak';
import 'tinymce/plugins/preview';
import 'tinymce/plugins/searchreplace';
import 'tinymce/plugins/table';
import 'tinymce/plugins/visualblocks';
import 'tinymce/plugins/visualchars';
import 'tinymce/plugins/wordcount';
import 'tinymce/plugins/image';

export default {
  components: {},
  props: {
    value: String,
    typeInfo: {
      type: Boolean,
      default: false,
    },
	height:{
		type:String,
		default:500
	}
  },
  data() {
    return {
      editor: null,
      type: this.typeInfo,
    };
  },
  watch: {
    value: {
      handler() {
        this.setValue(this.value);
        this.type = this.typeInfo;
      },
      immediate: true,
    },
    typeInfo: {
      handler(val) {
        console.log(val);
        console.log('this.editor', this.editor)
        if (this.editor) {
          console.log(222222)
          this.editor.setMode(val ? 'readonly' : 'design'); // 更新编辑器的只读状态
        }

      },
      immediate: true,
    }
  },
  mounted() {
    tinymce
      .init({
        valid_elements: '*[*]', // 允许所有元素和属性
        extended_valid_elements: 'span[style|class]', // 明确允许 span 标签的样式
        forced_root_block: '',
        // 添加更宽松的内容解析配置
        paste_as_text: false,
        paste_retain_style_properties: '*', // 保留所有样式属性
        target: this.$refs.textarea,
        ui_mode: 'split',
        // readonly: this.type,
        readonly: false,
        content_css: '/tinymce/skins/ui/oxide/content.css',
        language_url: '/tinymce/langs/zh_CN.js',
        language: 'zh_CN',
        content_style: `
        body {
          font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif;
          line-height: 1.5;
          color: #333;
        }
        p {
          margin: 8px 0;
          line-height: 1.5;
          padding: 0;
        }
        span {
          display: inline-block;
          width: 100%;
          line-height: 1.5;
        }
        p span:first-child {
          font-weight: bold;
          margin-right: 10px;
          color: #333;
        }
      `,
        // 添加这个配置来保留内联样式
        paste_retain_style_properties: 'line-height color font-weight font-size',
        paste_word_valid_elements: 'b,strong,i,em,u,span[style]',
        paste_merge_formats: true,

        // 自定义粘贴预处理
        paste_preprocess: (plugin, args) => {
          // 处理特定的内联样式
          args.content = args.content.replace(
            /style="([^"]*?)"/g,
            (match, styleContent) => {
              // 只保留特定的样式属性
              const validStyles = styleContent
                .split(';')
                .filter(style =>
                  style.includes('line-height') ||
                  style.includes('color') ||
                  style.includes('font-weight')
                )
                .join(';');

              return validStyles ? `style="${validStyles}"` : '';
            }
          );
        },
        // 额外的格式化配置
        formats: {
          // 保留一些基本的内联样式
          inline: {
            bold: { inline: 'span', styles: { 'font-weight': 'bold' } },
            italic: { inline: 'span', styles: { 'font-style': 'italic' } },
            underline: { inline: 'span', styles: { 'text-decoration': 'underline' } }
          }
        },
        plugins:
          'lists link anchor code wordcount image table visualchars visualblocks searchreplace preview pagebreak nonbreaking media insertdatetime fullscreen directionality autosave autolink advlist',
        toolbar: [
          'undo redo removeformat | bold italic underline strikethrough superscript subscript backcolor forecolor | numlist bullist | blocks | searchreplace fullscreen',
          'fontsize fontsizeselect fontsizeinput | alignleft aligncenter alignright alignjustify lineheight outdent indent | ',
          // link unlink image media | preview code
        ],
        font_size_formats:
          '9px 10px 11px 12px 14px 16px 18px 20px 22px 24px 26px 28px 36px 42px 48px 72px',
        font_size_input_default_unit: 'px',
        images_upload_handler: (blobInfo, progress) => {
          return this.uploadImage(blobInfo, progress);
        },
        height: this.height,
        promotion: false,
      })
      .then(([editor]) => {
        this.editor = editor;
        setTimeout(() => {
          this.$forceUpdate();
        }, 600)


        this.setValue(this.value);
        editor.on('change keyup undo redo', () => {
          this.$emit('input', editor.getContent());
        });
      });
  },
  beforeDestroy() {
    this.editor?.destroy();
    this.$forceUpdate();
  },
  methods: {
    setValue(val) {
      setTimeout(() => {
        this.$forceUpdate();
      }, 600)
      const oldValue = this.editor?.getContent();
      if (typeof val === 'string' && val !== oldValue) {
        this.editor?.setContent(val);
      }


      // 解码 HTML 实体
      // const decodedContent = this.decodeHtmlEntities(val);

      // // 清理内容
      // const cleanedContent = this.cleanHtmlContent(decodedContent);

      // const oldValue = this.editor?.getContent();

      // if (typeof cleanedContent === 'string' && cleanedContent !== oldValue) {
      //   this.editor?.setContent(cleanedContent);
      // }
    },

    // 解码 HTML 实体
    decodeHtmlEntities(text) {
      const textArea = document.createElement('textarea');
      textArea.innerHTML = text;
      return textArea.value;
    },

    // 清理 HTML 内容
    cleanHtmlContent(content) {
      return content
        .replace(/\n\t/g, '') // 移除换行和制表符
        .replace(/\n/g, '') // 移除额外换行
        .trim();
    },
    uploadImage(blobInfo, progress) {
      return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.withCredentials = false;
        xhr.open('POST', '/upload');

        xhr.upload.onprogress = (e) => {
          progress((e.loaded / e.total) * 100);
        };

        xhr.onload = () => {
          if (xhr.status === 403) {
            reject({ message: 'HTTP Error: ' + xhr.status, remove: true });
            return;
          }

          if (xhr.status < 200 || xhr.status >= 300) {
            reject('HTTP Error: ' + xhr.status);
            return;
          }

          if (xhr.response.code !== 200) {
            reject('Error: ' + xhr.response.message);
            return;
          }

          resolve(xhr.response.data.list[0].file_url);
        };

        xhr.onerror = () => {
          reject(
            'Image upload failed due to a XHR Transport error. Code: ' +
            xhr.status,
          );
        };
        xhr.setRequestHeader('Authorization', this.$cookie.get('Admin-Token'));

        const formData = new FormData();
        formData.append('file', blobInfo.blob(), blobInfo.filename());
        formData.append('module', 'public');
        formData.append('file_type', 'image');

        xhr.responseType = 'json';
        xhr.send(formData);
      });
    },
  },
};
</script>

<style>
.tox-tinymce-aux {
  z-index: 10000 !important;
}

.tox .tox-number-input .tox-input-wrapper {
  display: none !important;
}

.tox-statusbar__branding {
  display: none !important;
}
</style>
