import { nodes } from 'prosemirror-schema-basic'
import type { Node, NodeSpec } from 'prosemirror-model'
import { listItem as _listItem } from 'prosemirror-schema-list'

interface Attr {
  [key: string]: number | string
}

const orderedList: NodeSpec = {
  attrs: {
    order: {
      default: 1,
    },
    listStyleType: {
      default: '',
    },
    fontsize: {
      default: '',
    },
    color: {
      default: '',
    },
  },
  content: 'list_item+',
  group: 'block',
  parseDOM: [
    {
      tag: 'ol',
      getAttrs: dom => {
        const order = ((dom as HTMLElement).hasAttribute('start') ? (dom as HTMLElement).getAttribute('start') : 1) || 1
        const attr: Attr = { order: +order }

        const { listStyleType, fontSize, color } = (dom as HTMLElement).style
        if (listStyleType) attr['listStyleType'] = listStyleType
        if (fontSize) attr['fontsize'] = fontSize
        if (color) attr['color'] = color

        return attr
      }
    }
  ],
  toDOM: (node: Node) => {
    const { order, listStyleType, fontsize, color } = node.attrs
    let style = ''
    if (listStyleType) style += `list-style-type: ${listStyleType};`
    if (fontsize) style += `font-size: ${fontsize};`
    if (color) style += `color: ${color};`

    const attr: Attr = { style }
    if (order !== 1) attr['start'] = order


    return ['ol', attr, 0]
  },
}

const bulletList: NodeSpec = {
  attrs: {
    listStyleType: {
      default: '',
    },
    fontsize: {
      default: '',
    },
    color: {
      default: '',
    },
  },
  content: 'list_item+',
  group: 'block',
  parseDOM: [
    {
      tag: 'ul',
      getAttrs: dom => {
        const attr: Attr = {}

        const { listStyleType, fontSize, color } = (dom as HTMLElement).style
        if (listStyleType) attr['listStyleType'] = listStyleType
        if (fontSize) attr['fontsize'] = fontSize
        if (color) attr['color'] = color

        return attr
      }
    }
  ],
  toDOM: (node: Node) => {
    const { listStyleType, fontsize, color } = node.attrs
    let style = ''
    if (listStyleType) style += `list-style-type: ${listStyleType};`
    if (fontsize) style += `font-size: ${fontsize};`
    if (color) style += `color: ${color};`

    return ['ul', { style }, 0]
  },
}

/*
const listItem: NodeSpec = {
  ..._listItem,
  content: 'paragraph block*',
  group: 'block',
}
*/
const listItem: NodeSpec = {
  attrs: {
    textAlign: { default: '' },
    textAlignLast: { default: '' },
    textIndent: { default: '' },
    marginTop: { default: '' },
    marginBottom: { default: '' },
    marginLeft: { default: '' },
    marginRight: { default: '' },
    lineHeight: { default: '' },
    paddingTop: { default: '' },
    paddingRight: { default: '' },
    paddingBottom: { default: '' },
    paddingLeft: { default: '' },
    whiteSpace: { default: 'normal' },
    writingMode: { default: '' },
    // 新增字体相关属性
    fontWeight: { default: '' },
    fontStyle: { default: '' },
    textDecoration: { default: '' },
    textDecorationLine: { default: '' },
    verticalAlign: { default: '' },
    letterSpacing: { default: '' },
    textShadow: { default: '' },
  },
  content: 'paragraph block*',
  group: 'block',
  parseDOM: [
    {
      tag: 'li',
      getAttrs(dom) {
        const el = dom as HTMLElement;
        const style = el.style;

        const textAlign = style.textAlign || '';
        const textAlignLast = style.textAlignLast || '';
        const textIndent = style.textIndent || '';
        const marginTop = style.marginTop || '';
        const marginBottom = style.marginBottom || '';
        const marginLeft = style.marginLeft || '';
        const marginRight = style.marginRight || '';
        const lineHeight = style.lineHeight || '';
        const paddingTop = style.paddingTop || '';
        const paddingRight = style.paddingRight || '';
        const paddingBottom = style.paddingBottom || '';
        const paddingLeft = style.paddingLeft || '';
        const whiteSpace = style.whiteSpace || 'normal';
        const writingMode = style.writingMode || '';

        // 读取新增属性
        const fontWeight = style.fontWeight || '';
        const fontStyle = style.fontStyle || '';
        const textDecoration = style.textDecoration || '';
        const textDecorationLine = style.textDecorationLine || '';
        const verticalAlign = style.verticalAlign || '';
        const letterSpacing = style.letterSpacing || '';
        const textShadow = style.textShadow || '';

        return {
          textAlign,
          textAlignLast,
          textIndent,
          marginTop,
          marginBottom,
          marginLeft,
          marginRight,
          lineHeight,
          paddingTop,
          paddingRight,
          paddingBottom,
          paddingLeft,
          whiteSpace,
          writingMode,
          fontWeight,
          fontStyle,
          textDecoration,
          textDecorationLine,
          verticalAlign,
          letterSpacing,
          textShadow,
        };
      },
    },
  ],
  toDOM(node) {
    const {
      textAlign,
      textAlignLast,
      textIndent,
      marginTop,
      marginBottom,
      marginLeft,
      marginRight,
      lineHeight,
      paddingTop,
      paddingRight,
      paddingBottom,
      paddingLeft,
      whiteSpace,
      writingMode,
      fontWeight,
      fontStyle,
      textDecoration,
      textDecorationLine,
      verticalAlign,
      letterSpacing,
      textShadow,
    } = node.attrs;

    let style = '';

    if (textAlign && textAlign !== 'left') {
      style += `text-align: ${textAlign};`;
    }
    if (textAlignLast) {
      style += `text-align-last: ${textAlignLast};`;
    }
    if (textIndent) {
      style += `text-indent: (100% - ${textIndent});`;
    }
    if (marginTop) style += `margin-top: ${marginTop};`;
    if (marginBottom) style += `margin-bottom: ${marginBottom};`;
    if (marginLeft) {
      const str = String(marginLeft).trim();
      const match = str.match(/^([+-]?\d*\.?\d+)(px|pt|em|rem|%|vw|vh)?$/i);
      if (match) {
        let num = parseFloat(match[1]);
        const unit = match[2] || 'px';
        const absNum = Math.abs(num);
        const val = absNum + unit;
        style += `margin-left: max(min(0px, 100% - ${val}), 0px);`;
      } else {
        style += `margin-left: ${marginLeft};`;
      }
    }
    if (marginRight) style += `margin-right: ${marginRight};`;
    if (lineHeight) {
      let finalValue;
      const str = String(lineHeight).trim();
      if (/^-?\d+(\.\d+)?$/.test(str)) {
        finalValue = parseFloat(str) * 1.2;
      } else {
        finalValue = lineHeight;
      }
      style += `line-height: ${finalValue};`;
    }
    else{
      style += `line-height: 1.2;`;
    }
    if (paddingTop) style += `padding-top: ${paddingTop};`;
    if (paddingRight) style += `padding-right: ${paddingRight};`;
    if (paddingBottom) style += `padding-bottom: ${paddingBottom};`;
    if (paddingLeft) style += `padding-left: ${paddingLeft};`;
    if (whiteSpace && whiteSpace !== 'normal') {
      style += `white-space: ${whiteSpace};`;
    }
    if (writingMode) {
      style += `writing-mode: ${writingMode};`;
    }

    // 新增字体相关样式输出
    if (fontWeight) style += `font-weight: ${fontWeight};`;
    if (fontStyle) style += `font-style: ${fontStyle};`;
    if (textDecoration) style += `text-decoration: ${textDecoration};`;
    if (textDecorationLine) style += `text-decoration-line: ${textDecorationLine};`;
    if (verticalAlign) style += `vertical-align: ${verticalAlign};`;
    if (letterSpacing) style += `letter-spacing: ${letterSpacing};`;
    if (textShadow) style += `text-shadow: ${textShadow};`;

    let isEmpty = false;
    const firstChild = node.content.firstChild;
    if (firstChild && firstChild.type.name === 'paragraph') {
      if (firstChild.content.size === 0) {
        isEmpty = true;
      }
    }
    if (node.content.size === 0) isEmpty = true;

    const attrs: { style?: string; class?: string } = {};
    if (style) attrs.style = style;
    if (isEmpty) attrs.class = 'empty-li';

    return ['li', attrs, 0];
  },
};

const paragraph: NodeSpec = {
  whitespace: "pre",
  attrs: {
    textAlign: { default: '' },
    textAlignLast: { default: '' },
    indent: { default: 0 },
    textIndent: { default: 0 },
    marginTop: { default: '' },
    marginBottom: { default: '' },
    marginLeft: { default: '' },
    marginRight: { default: '' },
    lineHeight: { default: '' },
    paddingTop: { default: '' },
    paddingRight: { default: '' },
    paddingBottom: { default: '' },
    paddingLeft: { default: '' },
    whiteSpace: { default: 'normal' },
    writingMode: { default: '' },
    // 新增字体相关属性
    fontWeight: { default: '' },
    fontStyle: { default: '' },
    textDecoration: { default: '' },
    textDecorationLine: { default: '' },
    verticalAlign: { default: '' },
    letterSpacing: { default: '' },
    textShadow: { default: '' },
  },
  content: 'inline*',
  group: 'block',
  parseDOM: [
    {
      tag: 'p',
      getAttrs: dom => {
        const el = dom as HTMLElement;
        const style = el.style;

        const textAlign = style.textAlign || '';
        const textAlignLast = style.textAlignLast || '';
        const marginTop = style.marginTop || '';
        const marginBottom = style.marginBottom || '';
        const marginLeft = style.marginLeft || '';
        const marginRight = style.marginRight || '';
        const textIndent = style.textIndent || '';
        const lineHeight = style.lineHeight || '';
        const paddingTop = style.paddingTop || '';
        const paddingRight = style.paddingRight || '';
        const paddingBottom = style.paddingBottom || '';
        const paddingLeft = style.paddingLeft || '';
        const whiteSpace = style.whiteSpace || 'normal';
        const writingMode = style.writingMode || '';

        // 读取新增属性
        const fontWeight = style.fontWeight || '';
        const fontStyle = style.fontStyle || '';
        const textDecoration = style.textDecoration || '';
        const textDecorationLine = style.textDecorationLine || '';
        const verticalAlign = style.verticalAlign || '';
        const letterSpacing = style.letterSpacing || '';
        const textShadow = style.textShadow || '';

        return {
          textAlign,
          textAlignLast,
          textIndent,
          marginTop,
          marginBottom,
          marginLeft,
          marginRight,
          lineHeight,
          paddingTop,
          paddingRight,
          paddingBottom,
          paddingLeft,
          whiteSpace,
          writingMode,
          fontWeight,
          fontStyle,
          textDecoration,
          textDecorationLine,
          verticalAlign,
          letterSpacing,
          textShadow,
        };
      },
    },
    {
      tag: 'img',
      ignore: true,
    },
    {
      tag: 'pre',
      skip: true,
    },
  ],
  toDOM: (node: Node) => {
    const {
      textAlign,
      textAlignLast,
      textIndent,
      marginTop,
      marginBottom,
      marginLeft,
      marginRight,
      lineHeight,
      paddingTop,
      paddingRight,
      paddingBottom,
      paddingLeft,
      whiteSpace,
      writingMode,
      fontWeight,
      fontStyle,
      textDecoration,
      textDecorationLine,
      verticalAlign,
      letterSpacing,
      textShadow,
    } = node.attrs;

    let style = '';

    if (textAlign && textAlign !== 'left') {
      style += `text-align: ${textAlign};`;
    }
    if (textAlignLast) {
      style += `text-align-last: ${textAlignLast};`;
    }
    if (textIndent) {
      style += `text-indent: (100% - ${textIndent});`;
    }
    if (marginTop) style += `margin-top: ${marginTop};`;
    if (marginBottom) style += `margin-bottom: ${marginBottom};`;
    if (marginLeft) style += `margin-left: ${marginLeft};`;
    if (marginRight) style += `margin-right: ${marginRight};`;
    if (lineHeight) {
      let finalValue;
      const str = String(lineHeight).trim();
      if (/^-?\d+(\.\d+)?$/.test(str)) {
        finalValue = parseFloat(str) * 1.2;
      } else {
        finalValue = lineHeight;
      }
      style += `line-height: ${finalValue};`;
    }
    else{
      style += `line-height: 1.2;`;
    }
    if (paddingTop) style += `padding-top: ${paddingTop};`;
    if (paddingRight) style += `padding-right: ${paddingRight};`;
    if (paddingBottom) style += `padding-bottom: ${paddingBottom};`;
    if (paddingLeft) style += `padding-left: ${paddingLeft};`;
    if (whiteSpace && whiteSpace !== 'normal') {
      style += `white-space: ${whiteSpace};`;
    }
    if (writingMode) {
      style += `writing-mode: ${writingMode};`;
    }

    // 新增字体相关样式输出
    if (fontWeight) style += `font-weight: ${fontWeight};`;
    if (fontStyle) style += `font-style: ${fontStyle};`;
    if (textDecoration) style += `text-decoration: ${textDecoration};`;
    if (textDecorationLine) style += `text-decoration-line: ${textDecorationLine};`;
    if (verticalAlign) style += `vertical-align: ${verticalAlign};`;
    if (letterSpacing) style += `letter-spacing: ${letterSpacing};`;
    if (textShadow) style += `text-shadow: ${textShadow};`;

    const attrs: { style?: string; class?: string } = {};
    if (style) attrs.style = style;
    return ['p', attrs, 0];
  },
};

const hardBreak: NodeSpec = {
  inline: true,       // 内联节点
  group: 'inline',    // 属于 inline 组
  selectable: false,  // 不可被光标单独选中
  parseDOM: [{ tag: 'br' }],
  toDOM() {
    return ['br'];
  },
};

const {
  doc,
  blockquote,
  text,
} = nodes

export default {
  doc,
  paragraph,
  blockquote,
  text,
  'ordered_list': orderedList,
  'bullet_list': bulletList,
  'list_item': listItem,
  hard_break: hardBreak,  // 新增
}
