// custom-span.js
import { Mark } from '@tiptap/core'
import { Extension } from '@tiptap/vue-3'

export const CustomSpan = Mark.create({
  name: 'customSpan',
  keepOnSplit: false,
  inclusive: false,
  // 定义允许的属性
  addAttributes() {
    return {
      'uuid': {
        default: null,
        parseHTML: element => element.getAttribute('uuid'),
        renderHTML: attributes => {
          if (!attributes['uuid']) return {}
          return { 'uuid': attributes['uuid'] }
        }
      },
      'data-custom': {
        default: null,
        parseHTML: element => element.getAttribute('data-custom'),
        renderHTML: attributes => {
          if (!attributes['data-custom']) return {}
          return { 'data-custom': attributes['data-custom'] }
        }
      }
    }
  },

  // 解析HTML时的规则
  parseHTML() {
    return [
      {
        tag: 'u[uuid]', // 匹配带data-id的span标签
      },
    ]
  },

  // 渲染HTML时的规则
  renderHTML({ HTMLAttributes }) {
    return ['u', HTMLAttributes, 0] // [标签名, 属性, 内容]
  },
})
export const TextIndent = Extension.create({
  name: 'textIndent',
  
  addOptions() {
    return {
      types: ['paragraph', 'heading'],
      step: 2, // 默认缩进步长为2em
    }
  },
  
  addGlobalAttributes() {
    return [
      {
        types: this.options.types,
        attributes: {
          textIndent: {
            default: null,
            parseHTML: element => {
              const textIndent = element.style.textIndent;
              if (!textIndent) return null;
              
              // 解析数字值（支持em/px单位，但存储为纯数字）
              const value = parseFloat(textIndent);
              return isNaN(value) ? null : value;
            },
            renderHTML: attributes => {
              if (!attributes.textIndent) {
                return {}
              }
              return { style: `text-indent: ${attributes.textIndent}em` }
            }
          }
        }
      }
    ]
  },
  
  addCommands():any {
    return {
      // 设置绝对缩进值
      setTextIndent: (indent: any) => ({ commands }: any) => {
        // 确保缩进值不小于0
        // const safeIndent = Math.max(0, indent);
        // return commands.updateAttributes(this.options.types[0], { textIndent: safeIndent });
        const safeIndent = Math.max(0, indent);
        const types = this.options.types;
        let success = false;
        
        // 更新所有在types中定义的类型
        types.forEach((type: any) => {
          // 尝试更新该类型的节点
          const updated = commands.updateAttributes(type, { textIndent: safeIndent });
          if (updated) {
            success = true;
          }
        });
        
        return success;
      },
      
      // 增加缩进（累加）
      increaseIndent: () => ({ commands, state }: any) => {
        const currentNode = state.selection.$head.node(state.selection.$head.depth);
        const currentIndent = currentNode.attrs.textIndent || 0;
        const newIndent = currentIndent + this.options.step;
        return commands.setTextIndent(newIndent);
      },
      
      // 减少缩进（累减）
      decreaseIndent: () => ({ commands, state }: any) => {
        const currentNode = state.selection.$head.node(state.selection.$head.depth);
        const currentIndent = currentNode.attrs.textIndent || 0;
        const newIndent = Math.max(0, currentIndent - this.options.step);
        return commands.setTextIndent(newIndent);
      }
    }
  }
})
export const fontFamilyConfig = [
  {
    label: '宋体',
    value: 'SimSun, serif;',
  },
  {
    label: '仿宋',
    value: 'FangSong, STFangsong, serif',
  },
  {
    label: '黑体',
    value: 'SimHei, Heiti SC, sans-serif;',
  },
  {
    label: '楷体',
    value: 'KaiTi, STKaiti, serif',
  },
  {
    label: '微软雅黑',
    value: '"Microsoft YaHei", "微软雅黑", sans-serif',
  },
  {
    label: '方正仿宋简体GBK',
    value: 'FZFangSong-Z02S',
  },
  {
    label: 'Arial',
    value: 'Arial, sans-serif;',
  },
]
// 默认颜色
export const defaultColor = ["#ffffff", "#000000", "#e9d989", "#2972f4", "#609eec", "#de3c36", "#a1d533", "#7334c5", "#27b5d9", "#ff8926", "#f2f2f2", "#7f7f7f", "#ddd9c3", "#c6d9f0", "#dbe5f1", "#f2dcdb", "#ebf1dd", "#e5e0ec", "#dbeef3", "#fdeada", "#d8d8d8", "#595959", "#c4bd97", "#8db3e2", "#b8cce4", "#e5b9b7", "#d7e3bc", "#ccc1d9", "#b7dde8", "#fbd5b5", "#bfbfbf", "#3f3f3f", "#938953", "#548dd4", "#95b3d7", "#d99694", "#c3d69b", "#b2a2c7", "#92cddc", "#fac08f", "#a5a5a5", "#262626", "#494429", "#17365d", "#366092", "#953734", "#76923c", "#5f497a", "#31859b", "#e36c09", "#6e6e6e", "#0c0c0c", "#1d1b10", "#0f243e", "#244061", "#632423", "#4f6128", "#3f3151", "#205867", "#974806"]
// 标准颜色
export const standardColor = ["#c00000", "#ff0000", "#ffc000", "#ffff00", "#92d050", "#00b050", "#00b0f0", "#0070c0", "#002060", "#7030a0"]


export function mergeNestedUTags(html: any) {
  const parser = new DOMParser();
  const doc = parser.parseFromString(html, 'text/html');
  
  // 从最深层的u标签开始处理
  const uTags = doc.querySelectorAll('u[uuid]');
  const sortedTags = Array.from(uTags).sort((a, b) => {
    // 按嵌套深度排序（深度大的先处理）
    const depthA = getElementDepth(a);
    const depthB = getElementDepth(b);
    return depthB - depthA;
  });
  
  for (const uTag of sortedTags) {
    const parentUTag = findParentUTag(uTag);
    if (!parentUTag) continue; // 没有父级u标签，跳过
    
    // 合并uuid
    const parentUuid = parentUTag.getAttribute('uuid') || '';
    const currentUuid = uTag.getAttribute('uuid') || '';
    const combinedUuid = [parentUuid, currentUuid].filter(Boolean).join(' ');
    parentUTag.setAttribute('uuid', combinedUuid);
    
    // 将内容移动到父级
    moveContentToParent(uTag, parentUTag);
    
    // 移除当前u标签
    uTag.remove();
  }
  
  return doc.body.innerHTML;
}

function getElementDepth(element: any) {
  let depth = 0;
  let current = element;
  while (current.parentElement) {
    depth++;
    current = current.parentElement;
  }
  return depth;
}

function findParentUTag(element: any) {
  let parent = element.parentElement;
  while (parent) {
    if (parent.tagName.toLowerCase() === 'u' && parent.hasAttribute('uuid')) {
      return parent;
    }
    parent = parent.parentElement;
  }
  return null;
}

function moveContentToParent(child: any, parent: any) {
  const fragment = document.createDocumentFragment();
  while (child.childNodes.length > 0) {
    fragment.appendChild(child.childNodes[0]);
  }
  
  // 将内容插入到原位置
  if (child.nextSibling) {
    parent.insertBefore(fragment, child.nextSibling);
  } else {
    parent.appendChild(fragment);
  }
}
