import { createApp, h } from 'vue';
import sms from './sms.vue';
import { randomNumber } from '@/utils/index';

export default function registerConnect(lf) {
  lf.register('sms', ({ HtmlNode, HtmlNodeModel }) => {
    class RuleNode extends HtmlNode {
      setHtml(rootEl) {
        const { model } = this.props;
        console.log(model);
        const el = document.createElement('div');
        el.className = "html-card";
        rootEl.innerHTML = '';
        rootEl.appendChild(el);

        // Vue 3 使用 createApp 来创建应用实例
        const app = createApp({
          render: () =>
            h(sms, {
              properties: model.properties,
            }),
        });

        // 挂载 Vue 应用到元素上
        app.mount(el);
      }
    }
    class RuleModel extends HtmlNodeModel {
      createId() {
        return randomNumber();
      }
      constructor(data, graphModel) {
        super(data, graphModel);
        this.menu = [];
      }
      getDefaultAnchor() { // 设置锚点
        const { height, x, y, id,properties } = this;
        const anchorPositon = [];
        
        anchorPositon.push({
          x,
          y: y - height / 2,
          type: "targetAnchor",
          id: `${id}_targetAnchor`
        });


        if (properties.answers && properties.answers.length > 0) {
          let preOffset = 5;
          properties.answers.forEach((answer) => {
            const text = answer.name;
            // 计算每个锚点的位置，锚点的位置一般相对节点中心点进行偏移
            const offsetX =
              preOffset + (this.getBytesLength(text) * 6 + 4) / 2 - this.width / 2;
            preOffset += this.getBytesLength(text) * 6 + 4 + 10;
            const offsetY = height / 2;
            anchorPositon.push({
              x: x + offsetX,
              y: y + offsetY,
              type: "sourceAnchor",
              id: answer.id
            });
          });
        } else {
          anchorPositon.push({
            x,
            y: y + height / 2,
            id: `${id}_outgoing`,
            type: 'outgoing',
          });
        }
        return anchorPositon;
      }
      getBytesLength(word) {
        if (!word) {
          return 0;
        }
        let totalLength = 0;
        for (let i = 0; i < word.length; i++) {
          const c = word.charCodeAt(i);
          if (word.match(/[A-Z]/)) {
            totalLength += 1.5;
          } else if ((c >= 0x0001 && c <= 0x007e) || (c >= 0xff60 && c <= 0xff9f)) {
            totalLength += 1.2;
          } else {
            totalLength += 2;
          }
        }
        return totalLength;
      }
      initNodeData(data) { // 初始化节点
        super.initNodeData(data);
        const width = 250;
        const height = 100;
        this.width = width;
        this.height = height;
        this.radius = 50;
      }
    }
    return {
      view: RuleNode,
      model: RuleModel,
    };
  });
}
