import { RectNodeModel } from '@logicflow/core';

export default class BaseNodeModel extends RectNodeModel {
  createId() {
    return `node-${Date.now()}`;
  }

  initNodeData(data: any) {
    super.initNodeData(data);
    this.text.value = data.properties.title || '节点';
    this.width = 200;
    this.height = 40;
  }

  getOutlineStyle() {
    const style: any = super.getOutlineStyle();
    style.stroke = 'none';
    style.hover.stroke = 'none';
    return style;
  }

  getDefaultAnchor() {
    const { width, x, y, id } = this as any;

    // 左侧锚点
    const leftAnchor = {
      x: x - width / 2 - 1,
      y,
      name: 'left',
      id: `${id}_left`,
    };
    // 右侧锚点
    const rightAnchor = {
      x: x + width / 2,
      y,
      name: 'right',
      id: `${id}_right`,
    };
    return [leftAnchor, rightAnchor];
  }

  // 连线规则 - 作为起点（outgoing）：仅允许从右侧锚点连出
  getConnectedSourceRules() {
    const rules = super.getConnectedSourceRules();
    const onlyRightAnchor = {
      message: '只能从右侧连出',
      validate(...args: any[]) {
        // args 参数位置为 (sourceNode, targetNode, sourceAnchor, targetAnchor)
        // console.log('getConnectedSourceRules args--->>>', args);
        const sourceAnchor: any = args[2];
        const name = (sourceAnchor.name || '').toString().toLowerCase();
        if (name.includes('right')) {
          return true;
        }
        return false;
      },
    };
    rules.push(onlyRightAnchor);
    return rules;
  }

  // 连线规则 - 作为目标（incoming）：仅允许连入左侧锚点
  getConnectedTargetRules() {
    const rules = super.getConnectedTargetRules();
    const onlyLeftAnchor = {
      message: '只能连入左侧',
      validate(...args: any[]) {
        // args:(sourceNode, targetNode, sourceAnchor, targetAnchor)
        // console.log('getConnectedTargetRules args--->>>', args);
        const targetAnchor: any = args[3];

        const name = (targetAnchor.name || '').toString().toLowerCase();
        if (name.includes('left')) {
          return true;
        }
        return false;
      },
    };
    rules.push(onlyLeftAnchor);
    return rules;
  }
}
