import { register } from "@antv/x6-react-shape";
import { Graph, Node, EventArgs } from "@antv/x6";
import { useEffect, useMemo, useState } from "react";
import { TopicBorderType } from "@/enum";
import { Button, InputNumber, Popover } from "antd";
import { Icon } from "umi";

const component = ({ node, graph }: { node: Node; graph: Graph }) => {
  const { label, line, fill, type, origin } = node.getData();
  const { width, height } = node.size();
  const [showSetting, setShowSetting] = useState(false);

  useEffect(() => {
    const handleSelect = (args: EventArgs["node:selected"]) => {
      setShowSetting(args.node.id === node.id);
    };
    graph.on("node:selected", handleSelect);
    graph.on("blank:click", () => setShowSetting(false));
    return () => {
      graph.off("node:selected", handleSelect);
      graph.off("blank:click", () => setShowSetting(false));
    };
  }, []);

  // 删除边框
  const handleRemove = () => {
    const parentNode = graph.getCellById(origin);
    parentNode?.prop('changeNodeData', {
      cellId: parentNode.id,
      data: { border: undefined },
      ignoreRender: false
    });
  };

  const handleChange = (key: string, value: any) => {
    node.prop('changeNodeData', {
      cellId: node.id,
      data: { [key]: value },
      ignoreRender: false
    });
  };

  function generateWavePath() {
    return '';
  }

  const colors = [
    "#bf1e1b",
    "#63abf7",
    "#71cb2d",
    "#ff9f1a",
    "#30bfbf",
    "#000",
    "",
  ];

  const ColorBtn = ({
    color,
    value,
    onClick,
  }: {
    color: string;
    value: string;
    onClick: () => void;
  }) => {
    return (
      <div
        className={`relative w-18px h-18px cursor-pointer rounded-4px flex items-center justify-center hover:opacity-80`}
        style={{
          background: color,
          border: !color ? "1px solid #000" : "",
        }}
        onClick={onClick}
      >
        {color === value && (
          <i className="iconfont icon-zhengque-1 color-#fff" />
        )}
        {!color && (
          <i className="absolute left-0 top-0 block w-1px h-24px bg-#de0f18 origin-top-left rotate--45" />
        )}
      </div>
    );
  };

  return (
    <>
      <div className="relative text-0 w-full h-full">
        {showSetting && (
          <Popover
            // trigger={["click"]}
            content={
              <div className="w-240px">
                <div className="flex justify-between items-center m-b-20px">
                  <span className="text-14px font-bold">外框设置</span>
                  <span
                    className="text-12px cursor-pointer color-#666 hover:color-red"
                    onClick={handleRemove}
                  >
                    删除外框
                    <i className="iconfont icon-shanchu m-l-4px" />
                  </span>
                </div>
                <div className="flex items-center gap-8px m-b-8px">
                  <span className="text-12px color-#333">线条样式</span>
                  <InputNumber
                    className="w-100px"
                    size="small"
                    min={1}
                    max={5}
                    precision={0}
                    value={line.width}
                    onChange={(val) =>
                      handleChange("line", { ...line, width: val })
                    }
                  />
                  <Button
                    type="text"
                    size="small"
                    className={line.style === "solid" ? "active" : ""}
                    icon={<i className="iconfont icon-h-line" />}
                    onClick={() =>
                      handleChange("line", { ...line, style: "solid" })
                    }
                  ></Button>
                  <Button
                    type="text"
                    size="small"
                    className={line.style === "dashed" ? "active" : ""}
                    icon={<i className="iconfont icon-xuxian" />}
                    onClick={() =>
                      handleChange("line", { ...line, style: "dashed" })
                    }
                  ></Button>
                </div>
                <div className="flex items-center gap-8px m-b-8px">
                  <span className="text-12px color-#333">填充颜色</span>
                  {colors.map((color) => (
                    <ColorBtn
                      key={color}
                      color={color}
                      value={fill}
                      onClick={() => handleChange("fill", color)}
                    />
                  ))}
                </div>
                <div className="flex items-center gap-8px m-b-8px">
                  <span className="text-12px color-#333">线条颜色</span>
                  {colors.map((color) => (
                    <ColorBtn
                      key={color}
                      color={color}
                      value={line.color}
                      onClick={() => handleChange("line", { ...line, color })}
                    />
                  ))}
                </div>
                <div className="flex items-center gap-8px m-b-8px">
                  <span className="text-12px color-#333">外框样式</span>
                  <Button
                    type="text"
                    size="small"
                    icon={<Icon icon="local:rect" width="16px" />}
                    className={type === TopicBorderType.normal ? "active" : ""}
                    onClick={() => handleChange("type", TopicBorderType.normal)}
                  ></Button>
                  <Button
                    type="text"
                    size="small"
                    icon={<Icon icon="local:rounded" width="16px" />}
                    className={type === TopicBorderType.rounded ? "active" : ""}
                    onClick={() => handleChange("type", TopicBorderType.rounded)}
                  ></Button>
                  <Button
                    type="text"
                    size="small"
                    icon={<Icon icon="local:wavy" width="16px" />}
                    className={type === TopicBorderType.wavy ? "active" : ""}
                    onClick={() => handleChange("type", TopicBorderType.wavy)}
                  ></Button>
                  <Button
                    type="text"
                    size="small"
                    icon={<Icon icon="local:trapezoid" width="16px" />}
                    className={type === TopicBorderType.trapezoid ? "active" : ""}
                    onClick={() => handleChange("type", TopicBorderType.trapezoid)}
                  ></Button>
                </div>
              </div>
            }
          >
            <i
              className="iconfont icon-more text-12px absolute right--5px top--5px cursor-pointer"
              style={{ color: line.color || "#000" }}
            />
          </Popover>
        )}

        <svg
          className="w-full h-full"
          viewBox={`0 0 ${width} ${height}`}
          xmlns="http://www.w3.org/2000/svg"
        >
          { type === TopicBorderType.normal && (
            <rect
              width={width}
              height={height}
              fill={fill}
              fillOpacity={0.1}
              stroke={line.color}
              strokeDasharray={line.style === "dashed" ? "5,5" : ""}
              strokeWidth={line.width}
            />
          )}
          { type === TopicBorderType.rounded && (
            <rect
              rx={10}
              ry={10}
              width={width}
              height={height}
              fill={fill}
              fillOpacity={0.1}
              stroke={line.color}
              strokeDasharray={line.style === "dashed" ? "5,5" : ""}
              strokeWidth={line.width}
            />
          )}
          { type === TopicBorderType.wavy && (
            <path
              d={generateWavePath()}
              fill={fill}
              fillOpacity={0.1}
              stroke={line.color}
              strokeDasharray={line.style === "dashed" ? "5,5" : ""}
              strokeWidth={line.width}
            />
          )}
        </svg>
      </div>
    </>
  );
};

// 主题节点
register({
  shape: "mind-map-border",
  effect: ["data"],
  component: component,
});

export default {
  shape: "mind-map-border",
  data: {
    line: {
      width: 2,
      color: "#939aa8",
      style: "dashed",
    },
    fill: "#f4f4f6",
    label: "",
    type: TopicBorderType.normal,
  },
};
