import { BezierEdge, BezierEdgeModel, h } from '@logicflow/core';
import { useElementsInfoStore } from '../stores/elementsInfo';

const elementsInfoStore = useElementsInfoStore();
class CustomArrow extends BezierEdge {
  getEndArrow(): any {
    const { model } = this.props;
    const {
      properties: { arrowType },
    } = model;

    const { stroke, strokeWidth } = model.getArrowStyle();
    const pathAttr = {
      stroke,
      strokeWidth,
    };

    if (arrowType === 'empty') {
      // 空心箭头
      return h('path', {
        ...pathAttr,
        fill: '#FFF',
        d: 'M 0 0  -7 -3 -15 0 -7 3 z',
        // d: 'M 0 0  -20 -5 -30 0 -20 5 z',
      });
    }
    else if (arrowType === 'half') {
      // 半箭头
      return h('path', {
        ...pathAttr,
        d: 'M 0 0 -7 5',
      });
    }
    return h('path', {
      ...pathAttr,
      d: 'M 0 0 -4 -2 -4 2 z',
      fill: pathAttr.stroke,
      // d: 'M 0 0 -10 -5 -10 5 z',
    });
  }

  render(): any {
    // 原始 edge 的虚拟 DOM'
    const edgeGroup = super.render(); // 具体方法名视 logicflow 版本而定
    const { model } = this.props;
    const { properties: { selected } } = model;
    const end = model.endPoint || { x: 0, y: 0 };
    const x = end.x - 14;
    const y = end.y - 14;

    // 删除图标 (简单“垃圾桶” path)，并绑定点击事件
    const className = selected ? 'lf-edge-delete-icon opt-show' : 'lf-edge-delete-icon opt-hide';
    const delIcon = h('g', {
      class: className,
      transform: `translate(${x}, ${y})`,
      onMouseDown: (e: MouseEvent) => {
        e.stopPropagation();
        e.preventDefault();
        // console.log('delete edge', this.props);
        // 删除当前边并且从存储数据中删除该边信息
        this.props.graphModel.deleteEdgeById(model.id);
        elementsInfoStore.deleteElement(model.id);
      },
    }, [
      // 垃圾桶 path（简化示意，换成你喜欢的 svg）
      h('path', { d: 'M -4 -3 L 4 -3 L 3 6 L -3 6 Z M -2 -3 L -2 -5 L 2 -5 L 2 -3', fill: 'transparent', strokeWidth: 1, stroke: '#b1b1b7' }),
    ]);

    // 将原 edge 与删除图标合并返回
    return h('g', {}, [edgeGroup, delIcon]);
  }
}
class myBezierEdgeModel extends BezierEdgeModel {
  createId() {
    return `edge-${Date.now()}`;
  }

  getData() {
    const data = super.getData();
    data.sourceAnchorId = this.sourceAnchorId;
    data.targetAnchorId = this.targetAnchorId;
    return data;
  }

  getEdgeStyle() {
    const style = super.getEdgeStyle();
    const { properties } = this;
    const selected = properties.selected;
    if (selected) {
      style.stroke = '#155aef';
    }
    else {
      style.stroke = properties.strokeColor || '#b1b1b7';
    }
    style.strokeWidth = 1;
    style.outlineColor = 'transparent';
    style.outlineWidth = 0;
    return style;
  }

  getOutlineStyle() {
    const style = super.getOutlineStyle();
    style.stroke = '#296dff';
    return style;
  }
}

export default {
  type: 'custom-bezier-edge',
  view: CustomArrow,
  model: myBezierEdgeModel,
};
