import { RectNode, RectNodeModel, h } from "@logicflow/core";
import { getBytesLength } from "../util";
const makeX = (arr) => {
  const len = arr.length;
  let i = len % 2 == 0 ? (len / 2) * -1 : ((len - 1) / 2) * -1;
  let res = [];
  for (let j = i; j <= i * -1; j++) {
    if(len%2==0 && j==0){

    }else{
      res.push(30 * j);
    }
  }
  return res;
};
class RedNodeModel extends RectNodeModel {
  /**
   * 初始化
   */
  initNodeData(data) {
    super.initNodeData(data);
    this.width = 200;
    this.height = 70;
    this.radius = 5;
    this.text.x = this.x + 10;
    this.defaultFill = data.fill || "rgb(253, 208, 162)";

    const rule0 = {
      message: "开始结点只能连接结束节点!",
      validate: (sourceNode, targetNode, sourceAnchor, targetAnchor) => {
        let res= sourceAnchor.type !== targetAnchor.type;
        return res;
      },
    };
    const rule1 = {
      message: "同一算子不能互联!",
      validate: (sourceNode, targetNode, sourceAnchor, targetAnchor) => {        
        return sourceNode.id !== targetNode.id;
      },
    };
    const rule2 = {
      message: "输入类型与输出类型不符!",
      validate: (sourceNode, targetNode, sourceAnchor, targetAnchor) => {
        let sp= sourceNode.properties.data.parameters;
        let tp= targetNode.properties.data.parameters;
        let inStr="";
        let outStr="";
        if(sourceAnchor.type=="start"){
          inStr=sp.inputs.length>=sourceAnchor.idx?sp.inputs[sourceAnchor.idx-1].oper_inout_data_type:"";
        }
        if(sourceAnchor.type=="end"){
          outStr=sp.outputs.length>=sourceAnchor.idx?sp.outputs[sourceAnchor.idx-1].oper_inout_data_type:"";
          if(outStr=="same_as_input"){
            outStr=sp.inputs[0].oper_inout_data_type;
          }
        }
        if(targetAnchor.type=="start"){
          inStr=tp.inputs.length>=targetAnchor.idx?tp.inputs[targetAnchor.idx-1].oper_inout_data_type:"";
        }
        if(targetAnchor.type=="end"){
          outStr=tp.outputs.length>=targetAnchor.idx?tp.outputs[targetAnchor.idx-1].oper_inout_data_type:"";
          if(outStr=="same_as_input"){
            outStr=tp.inputs[0].oper_inout_data_type;
          }
        }
        if(inStr.length>0 && outStr.length>0 ){
            let tmpS=inStr.split(",").filter(d=>d).map(d=>d.toLowerCase());
            let tmpE=outStr.split(",").filter(d=>d).map(d=>d.toLowerCase());
            if(tmpS.sort().join(",")==tmpE.sort().join(",")){
              return true;
            }
            if(tmpS.length>tmpE.length){
              if((","+tmpS.sort().join(",")).indexOf(","+tmpE.sort().join(","))>=0){
                return true;
              }
            }
        }
        return false;
      },
    };
    this.sourceRules.push(rule1);
    this.sourceRules.push(rule0);
    this.sourceRules.push(rule2);
    
  }
  getData() {
    const data = super.getData();
    data.properties.ui = "node-ai";
    return data;
  }

  updateText(val) {
    super.updateText(val);
    this.setAttributes();
  }
  /**
   * 重写节点样式
   */
  getNodeStyle() {
    const style = super.getNodeStyle();
    const dataStyle = this.properties.style || {};
    if (this.isSelected) {
      style.strokeWidth = Number(dataStyle.borderWidth) || 2;
      style.stroke = dataStyle.borderColor || "#ff7f0e";
    } else {
      style.strokeWidth = Number(dataStyle.borderWidth) || 1;
      style.stroke = dataStyle.borderColor || "#999";
    }
    style.fill = dataStyle.backgroundColor || this.defaultFill;
    return style;
  }
  /**
   * 重写定义锚点
   */
  getDefaultAnchor() {
    const { x, y, id, width, height } = this;

    const node = this.properties?.data?.parameters;
    let inputs = makeX(node?.inputs || []).map((d, idx) => {
      return {
        x: x + d,
        y: y - height / 2,
        id: `${idx + 1}_right`,
        type: "start",
        idx: idx + 1,
        className: "anchors-start",
      };
    });
    let outputs = makeX(node?.outputs || []).map((d, idx) => {
      return {
        x: x + d,
        y: y + height / 2,
        id: `${idx + 1}_left`,
        idx: idx + 1,
        type: "end",
        className: "anchors-end",
      };
    });

    const anchors = [...inputs, ...outputs];
    return anchors;
  }
  /**
   *
   */
  getOutlineStyle() {
    const style = super.getOutlineStyle();
    style.stroke = "transparent";
    style.hover.stroke = "transparent";
    return style;
  }
  handleContextMenu(ev) {
  }
}
class RedNode extends RectNode {
  /**
   * 1.1.7版本后支持在view中重写锚点形状。
   * 重写锚点新增
   */
  getAnchorShape(anchorData) {
    const { x, y, type, className, idx } = anchorData;
    if (type == "start") {
      return h(
        "svg",
        {
          width: 20,
          height: 20,
          x: x - 10,
          y: y - 0,
        },
        h("circle", {
          r: 9,
          cx: 10,
          cy: 10,
          fill: "#0bdd0b",
        }),
        h(
          "text",
          {
            x: 9,
            y: 14,
            style: "text-anchor:middle;fill:#fff;font-size:12px;",
          },
          "" + idx
        )
      );
    }
    return h(
      "svg",
      {
        width: 20,
        height: 20,
        x: x - 10,
        y: y - 20,
      },
      h("circle", {
        r: 9,
        cx: 10,
        cy: 10,
        fill: "#ffb01f",
      }),
      h(
        "text",
        {
          x: 9,
          y: 14,
          style: "text-anchor:middle;fill:#fff;font-size:12px;",
        },
        "" + idx
      )
    );
  }

  getShape() {
    const { text, x, y, width, height, radius } = this.props.model;
    const style = this.props.model.getNodeStyle();
    const fillColor=this.props.model.properties.fill||"#FFA726";
    let subText=(this.props.model.properties?.data?.oper_main_type_name||"");
    let subType = (this.props.model.properties?.data?.oper_main_type_name||"").split("").filter(t=>t.length>0).map((t,idx)=>{
      let txtY=y+idx*13-14;
      if(subText.length==3){
        txtY=y+idx*16-10;
      }else if(subText.length==2){
        txtY=y+idx*22-5;
      }
      return h("text",{
          x:x-width/2+8,
          y:txtY,
          style: "text-anchor:left;fill:#fff;font-size:12px;",
      },t)
    }); 
    
    const node = this.props.model.properties?.data?.parameters;    
    let inputs = makeX(node?.inputs || []).map((d, idx) =>
      h(
        "svg",
        {
          width: 20,
          height: 20,
          x: x + d - 10,
          y: y - height / 2 - 0,
        },
        h("circle", {
          r: 9,
          cx: 10,
          cy: 10,
          fill: "#0bdd0b",
        }),
        h(
          "text",
          {
            x: 9,
            y: 14,
            style: "text-anchor:middle;fill:#fff;font-size:12px;",
          },
          "" + (idx + 1)
        )
      )
    );
    let outputs = makeX(node?.outputs || []).map((d, idx) =>
      h(
        "svg",
        {
          width: 20,
          height: 20,
          x: x + d - 10,
          y: y + height / 2 - 20,
        },
        h("circle", {
          r: 9,
          cx: 10,
          cy: 10,
          fill: "#ffb01f",
        }),
        h(
          "text",
          {
            x: 9,
            y: 14,
            style: "text-anchor:middle;fill:#fff;font-size:12px;",
          },
          "" + (idx + 1)
        )
      )
    );

    return h(
      "g",
      {
        className: "lf-ai-node",
      },
      [
        h("rect", {
          ...style,
          x: x - width / 2,
          y: y - height / 2,
          width,
          height,
          fill:fillColor,
          rx: radius,
          ry: radius,
        }),
        h("rect",{
          fill: "#45C4DD",
          x: x - width / 2,
          y: y - height / 2,
          width:30,
          height,
          rx: radius,
          ry: radius,
        }),
        h("rect",{
          fill: "#45C4DD",
          x: x - width / 2+20,
          y: y - height / 2,
          width:10,
          height,
        }),
        ...subType,
        ...inputs,
        ...outputs,
      ]
    );
  }
}

export default {
  type: "ai-node",
  model: RedNodeModel,
  view: RedNode,
};
