import { Node, mergeAttributes } from '@tiptap/core';

export default Node.create({
  name: 'imageResizable',
  group: 'block',
  draggable: true,  // 启用TipTap原生拖拽
  selectable: true,

  addAttributes() {
    return {
      src: { default: null },
      alt: { default: null },
      title: { default: null },
      width: { default: 300 },
      height: { default: 200 },
      textAlign: { default: 'left' },
    };
  },

  parseHTML() {
    return [{ tag: 'div[data-type="imageResizable"]' }];
  },

  renderHTML({ HTMLAttributes }) {
    const alignStyle = HTMLAttributes.textAlign === 'center' ? 'margin:0 auto;' : 
                      HTMLAttributes.textAlign === 'right' ? 'margin-left:auto;' : '';
    
    return [
      'div',
      mergeAttributes(HTMLAttributes, { 
        'data-type': 'imageResizable', 
        'data-text-align': HTMLAttributes.textAlign || 'left',
        style: `display:block;position:relative;width:${HTMLAttributes.width}px;height:${HTMLAttributes.height}px;${alignStyle}` 
      }),
      [
        'img',
        {
          src: HTMLAttributes.src,
          alt: HTMLAttributes.alt,
          title: HTMLAttributes.title,
          style: `width:100%;height:100%;display:block;object-fit:contain;`,
        },
      ],
    ];
  },

  addNodeView() {
    return ({ node, getPos, editor }) => {
      const dom = document.createElement('div');
      dom.setAttribute('data-type', 'imageResizable');
      dom.setAttribute('data-text-align', node.attrs.textAlign || 'left');
      dom.style.position = 'relative';
      dom.style.display = 'block';
      dom.style.width = (node.attrs.width || 300) + 'px';
      dom.style.height = (node.attrs.height || 200) + 'px';
      dom.style.userSelect = 'none';
      
      // 应用对齐样式
      if (node.attrs.textAlign === 'center') {
        dom.style.margin = '0 auto';
      } else if (node.attrs.textAlign === 'right') {
        dom.style.marginLeft = 'auto';
      } else {
        dom.style.marginLeft = '0';
        dom.style.marginRight = 'auto';
      }

      const img = document.createElement('img');
      img.src = node.attrs.src;
      img.alt = node.attrs.alt || '';
      img.title = node.attrs.title || '';
      img.style.width = '100%';
      img.style.height = '100%';
      img.style.display = 'block';
      img.style.objectFit = 'contain';
      img.style.pointerEvents = 'none';
      dom.appendChild(img);

      // 缩放手柄
      const resizeHandle = document.createElement('div');
      resizeHandle.style.position = 'absolute';
      resizeHandle.style.right = '0';
      resizeHandle.style.bottom = '0';
      resizeHandle.style.width = '20px';
      resizeHandle.style.height = '20px';
      resizeHandle.style.background = '#1fc76f';
      resizeHandle.style.cursor = 'se-resize';
      resizeHandle.style.borderRadius = '50%';
      resizeHandle.style.boxShadow = '0 0 2px #1fc76f';
      resizeHandle.style.zIndex = '2';
      resizeHandle.className = 'image-resize-handle';
      dom.appendChild(resizeHandle);

      // 缩放功能
      let isResizing = false;
      let resizeStartX = 0;
      let resizeStartY = 0;
      let startWidth = 0;
      let startHeight = 0;

      const onResizeStart = (e) => {
        e.preventDefault();
        e.stopPropagation();
        
        isResizing = true;
        const clientX = e.clientX || (e.touches && e.touches[0] ? e.touches[0].clientX : 0);
        const clientY = e.clientY || (e.touches && e.touches[0] ? e.touches[0].clientY : 0);
        
        resizeStartX = clientX;
        resizeStartY = clientY;
        startWidth = parseInt(dom.style.width) || (node.attrs.width || 300);
        startHeight = parseInt(dom.style.height) || (node.attrs.height || 200);
        
        editor.view.focus();
        
        document.addEventListener('mousemove', onResizeMove);
        document.addEventListener('mouseup', onResizeEnd);
        document.addEventListener('touchmove', onResizeMove);
        document.addEventListener('touchend', onResizeEnd);
      };

      const onResizeMove = (e) => {
        if (!isResizing) return;
        
        e.preventDefault();
        e.stopPropagation();
        
        const clientX = e.clientX || (e.touches && e.touches[0] ? e.touches[0].clientX : 0);
        const clientY = e.clientY || (e.touches && e.touches[0] ? e.touches[0].clientY : 0);
        
        const deltaX = clientX - resizeStartX;
        const deltaY = clientY - resizeStartY;
        
        const newWidth = Math.max(startWidth + deltaX, 50);
        const newHeight = Math.max(startHeight + deltaY, 30);
        
        dom.style.width = newWidth + 'px';
        dom.style.height = newHeight + 'px';
        
        // 更新节点属性
        editor.commands.command(({ tr }) => {
          tr.setNodeMarkup(getPos(), undefined, {
            ...node.attrs,
            width: newWidth,
            height: newHeight,
          });
          return true;
        });
      };

      const onResizeEnd = (e) => {
        e.preventDefault();
        e.stopPropagation();
        
        isResizing = false;
        
        document.removeEventListener('mousemove', onResizeMove);
        document.removeEventListener('mouseup', onResizeEnd);
        document.removeEventListener('touchmove', onResizeMove);
        document.removeEventListener('touchend', onResizeEnd);
      };

      // 缩放手柄事件 - 阻止拖拽
      resizeHandle.addEventListener('mousedown', (e) => {
        e.stopPropagation(); // 阻止拖拽事件
        onResizeStart(e);
      });
      resizeHandle.addEventListener('touchstart', (e) => {
        e.stopPropagation(); // 阻止拖拽事件
        onResizeStart(e);
      });

      return {
        dom,
        contentDOM: null,
        update: updatedNode => {
          if (updatedNode.type.name !== 'imageResizable') return false;
          
          img.src = updatedNode.attrs.src;
          dom.style.width = (updatedNode.attrs.width || 300) + 'px';
          dom.style.height = (updatedNode.attrs.height || 200) + 'px';
          dom.setAttribute('data-text-align', updatedNode.attrs.textAlign || 'left');
          
          // 更新对齐样式
          if (updatedNode.attrs.textAlign === 'center') {
            dom.style.margin = '0 auto';
            dom.style.marginLeft = 'auto';
            dom.style.marginRight = 'auto';
          } else if (updatedNode.attrs.textAlign === 'right') {
            dom.style.margin = '0';
            dom.style.marginLeft = 'auto';
            dom.style.marginRight = '0';
          } else {
            dom.style.margin = '0';
            dom.style.marginLeft = '0';
            dom.style.marginRight = 'auto';
          }
          
          return true;
        },
        destroy: () => {
          // 清理事件监听器
          document.removeEventListener('mousemove', onResizeMove);
          document.removeEventListener('mouseup', onResizeEnd);
          document.removeEventListener('touchmove', onResizeMove);
          document.removeEventListener('touchend', onResizeEnd);
        }
      };
    };
  }
}); 