const BASE_URL = import.meta.env.BASE_URL;

// 默认加载插件
const PLUGINS = [
  'code',
  'preview',
  'fullscreen',
  'paste',
  'searchreplace',
  'save',
  'autosave',
  'link',
  'autolink',
  'image',
  'media',
  'table',
  'codesample',
  'lists',
  'advlist',
  'hr',
  'charmap',
  'emoticons',
  'anchor',
  'directionality',
  'pagebreak',
  'quickbars',
  'nonbreaking',
  'visualblocks',
  'visualchars',
  'wordcount',
  'indent2em'
].join(' ');

// 默认工具栏布局
const TOOLBAR = [
  'fullscreen',
  'preview',
  'image',
  'indent2em',
  '|',
  'undo',
  'redo',
  '|',
  'forecolor',
  'backcolor',
  '|',
  'bold',
  'italic',
  'underline',
  'strikethrough',
  '|',
  'formatselect',
  'fontselect',
  'fontsizeselect',
  '|',
  'alignleft',
  'aligncenter',
  'alignright',
  'alignjustify',
  '|',
  'outdent',
  'indent',
  '|',
  'numlist',
  'bullist',
  '|',
  'link',
  'media',
  'emoticons',
  'charmap',
  'anchor',
  'pagebreak',
  'codesample',
  '|',
  'ltr',
  'rtl',
  'code',
].join(' ');

// 默认配置
export const DEFAULT_CONFIG = {
  height: 300,
  branding: false,
  skin_url: BASE_URL + 'tinymce/skins/ui/oxide',
  content_css: BASE_URL + 'tinymce/skins/content/default/content.min.css',
  language_url: BASE_URL + 'tinymce/langs/zh_CN.js',
  language: 'zh_CN',
  plugins: PLUGINS,
  toolbar: TOOLBAR,
  draggable_modal: true,
  toolbar_mode: 'sliding',
  quickbars_insert_toolbar: '',
  // 粘贴文本处理
  paste_preprocess: (plugin, args) => {
    // args.preventDefault();
    let content = args?.content;
    if (content) {
      let _validateImgTags = validateImgTags(content);
      if (_validateImgTags.validImgTags > 0) {
        alert('粘贴的图片中包含外部链接，请在内容编辑器中上传图片!');
        let imgTags = extractImgTags(content);
        for (let i = 0; i < imgTags.length; i++) {
          // 移除img标签
          args.content = args.content.replace(imgTags[i], '')
        }
      }
    }
  },
  images_upload_handler: (blobInfo, success, error) => {
    if (blobInfo.blob().size / 1024 > 2048) {
      error('大小不能超过 2MB');
      return;
    }
    success('data:image/jpeg;base64,' + blobInfo.base64());
  },
  file_picker_types: 'media',
  file_picker_callback: () => {}
};

// 暗黑主题配置
export const DARK_CONFIG = {
  skin_url: BASE_URL + 'tinymce/skins/ui/oxide-dark',
  content_css: BASE_URL + 'tinymce/skins/content/dark/content.min.css'
};

// 支持监听的事件
export const VALID_EVENTS = [
  'onActivate',
  'onAddUndo',
  'onBeforeAddUndo',
  'onBeforeExecCommand',
  'onBeforeGetContent',
  'onBeforeRenderUI',
  'onBeforeSetContent',
  'onBeforePaste',
  'onBlur',
  'onChange',
  'onClearUndos',
  'onClick',
  'onContextMenu',
  'onCopy',
  'onCut',
  'onDblclick',
  'onDeactivate',
  'onDirty',
  'onDrag',
  'onDragDrop',
  'onDragEnd',
  'onDragGesture',
  'onDragOver',
  'onDrop',
  'onExecCommand',
  'onFocus',
  'onFocusIn',
  'onFocusOut',
  'onGetContent',
  'onHide',
  'onInit',
  'onKeyDown',
  'onKeyPress',
  'onKeyUp',
  'onLoadContent',
  'onMouseDown',
  'onMouseEnter',
  'onMouseLeave',
  'onMouseMove',
  'onMouseOut',
  'onMouseOver',
  'onMouseUp',
  'onNodeChange',
  'onObjectResizeStart',
  'onObjectResized',
  'onObjectSelected',
  'onPaste',
  'onPostProcess',
  'onPostRender',
  'onPreProcess',
  'onProgressState',
  'onRedo',
  'onRemove',
  'onReset',
  'onSaveContent',
  'onSelectionChange',
  'onSetAttrib',
  'onSetContent',
  'onShow',
  'onSubmit',
  'onUndo',
  'onVisualAid'
];

let unique = 0;

/**
 * 生成编辑器 id
 */
export function uuid(prefix) {
  const time = Date.now();
  const random = Math.floor(Math.random() * 1000000000);
  unique++;
  return prefix + '_' + random + unique + String(time);
}

/**
 * 绑定事件
 */
export function bindHandlers(initEvent, listeners, editor) {
  const validEvents = VALID_EVENTS.map((event) => event.toLowerCase());
  Object.keys(listeners)
    .filter((key) => validEvents.includes(key.toLowerCase()))
    .forEach((key) => {
      const handler = listeners[key];
      if (typeof handler === 'function') {
        if (key === 'onInit') {
          handler(initEvent, editor);
        } else {
          editor.on(key.substring(2), (e) => handler(e, editor));
        }
      }
    });
}

/**
 * 弹出提示框
 */
export function openAlert(editor, option = {}) {
  editor?.windowManager?.open({
    title: option.title ?? '提示',
    body: {
      type: 'panel',
      items: [
        {
          type: 'htmlpanel',
          html: `<p>${option.content ?? ''}</p>`
        }
      ]
    },
    buttons: [
      {
        type: 'cancel',
        name: 'closeButton',
        text: '确定',
        primary: true
      }
    ]
  });
}


/**
 * 判断是否是否有效的url
 * @param url
 * @returns {boolean}
 */
function isUrlValid(url) {
  // 正则表达式匹配 HTTP 或 HTTPS 网址
  const urlRegex = /^(http|https):\/\//;
  return urlRegex.test(url);
}

/**
 * 匹配出img标签中的Url
 * @param htmlString
 * @returns {*|*[]}
 */
function extractImgTagsUrl(htmlString) {
  const imgSrcRegex = /<img\s+[^>]*src=["']([^"']+)["'][^>]*>/gi;
  const matches = htmlString.match(imgSrcRegex);
  return matches ? matches.map(match => {
    const srcMatch = match.match(/src=["']([^"']+)["']/i);
    return srcMatch ? srcMatch[1] : null;
  }) : [];
}

/**
 * 匹配出img标签
 * @param htmlString
 * @returns {*|*[]}
 */
function extractImgTags(htmlString) {
  const imgSrcRegex = /<img\s+[^>]*src=["']([^"']+)["'][^>]*>/gi;
  const matches = htmlString.match(imgSrcRegex);
  return matches;
}

/**
 * 验证img标签
 * @param htmlString
 * @returns {{imgSrcs: (*|*[]), validUrls: T[], validImgTags: number, totalImgTags: number, invalidImgTags: number}}
 */
function validateImgTags(htmlString) {
  const imgSrcs = extractImgTagsUrl(htmlString);
  const validUrls = imgSrcs.filter(src => isUrlValid(src));
  return {
    totalImgTags: imgSrcs.length,
    validImgTags: validUrls.length,
    invalidImgTags: imgSrcs.length - validUrls.length,
    imgSrcs: imgSrcs,
    validUrls: validUrls
  };
}
