import CustomColorPicker from "@/components/CustomColorPicker";
import {
  BoldOutlined,
  FontSizeOutlined,
  ItalicOutlined,
  StrikethroughOutlined,
  UnderlineOutlined,
} from "@ant-design/icons";
import { Button, Checkbox, Divider, InputNumber, Select, Tooltip } from "antd";
import { Icon, useModel } from "umi";
import { useEffect, useRef, useState } from "react";
import { ImageFillType, BorderSize, TopicType } from "@/enum";
import { set, cloneDeep } from "lodash-es";
import { Cell } from "@antv/x6";
import { fontFamilyOptions } from "@/pages/flow/data";
import { updateTopic } from "../../render";

export default function GraphStyle() {
  const { selectedCell, setMindProjectInfo } = useModel("mindmap.mindMapModel");
  const eventNodeList = useRef<Cell[]>([]);

  const [formModel, setFormModel] = useState({
    width: 100,
    fixedWidth: false,
    borderSize: BorderSize.medium,
    type: TopicType.main,
    text: {
      fontFamily: "normal",
      color: "#000000",
      fontSize: 14,
      lineHeight: 1.25,
      textAlign: "center",
      bold: false,
      italic: false,
      textDecoration: "none",
    },
    isFill: true,
    fill: {
      fillType: "color",
      color1: "#FFFFFF",
      color2: "#eeeeee",
      gradientType: "linear",
      gradientValue: 0,
      objectFit: ImageFillType.Fill,
      imageUrl: "",
    },
    isStroke: false,
    stroke: {
      type: "solid",
      color: "#323232",
      width: 1,
    },
    edge: {
      color: "#000000",
      width: 2,
    },
  });

  useEffect(() => {
    const firstNode = selectedCell?.find((item) => item.isNode());
    eventNodeList.current = [];
    if (firstNode) {
      const size = firstNode.size();
      const data = firstNode.getData();
      setFormModel({
        ...formModel,
        width: size.width,
        text: data.text,
        fill: data.fill,
        edge: data.edge,
        fixedWidth: data.fixedWidth,
        borderSize: data.borderSize,
        type: data.type,
        isFill: data.fill.color1 !== "transparent",
        isStroke: data.stroke.width > 0,
        stroke: {
          ...data.stroke,
          width: data.stroke.width || 1,
        },
      });

      // 监听当前选中节点的属性变化
      if (!eventNodeList.current.find((item) => item.id === firstNode.id)) {
        eventNodeList.current.push(firstNode);
        firstNode.on("change:*", (args) => {
          if (args.key === "position") {
            setFormModel((state) => {
              return {
                ...state,
                x: parseInt(args.current.x),
                y: parseInt(args.current.y),
              };
            });
          }
          if (args.key === "size") {
            setFormModel((state) => {
              return {
                ...state,
                width: args.current.width,
                height: args.current.height,
              };
            });
          }
          if (args.key === "data") {
            setFormModel((state) => {
              return {
                ...state,
                fixedWidth: args.current.fixedWidth,
                type: args.current.type,
                text: args.current.text,
                fill: args.current.fill,
                stroke: args.current.stroke,
                edge: args.current.edge,
              };
            });
          }
        });
      }
    }
  }, [selectedCell]);

  // 表单值改变，修改元素属性
  const handleChange = (model: typeof formModel) => {
    selectedCell?.forEach((cell) => {
      if (cell.isNode()) {
        model.fixedWidth && cell.setSize(model.width, cell.size().height);
        const updateData = {
          text: model.text,
          edge: model.edge,
          borderSize: model.borderSize,
          fixedWidth: model.fixedWidth,
          fill: {
            ...model.fill,
            color1: model.isFill ? model.fill.color1 : "transparent",
          },
          stroke: {
            ...model.stroke,
            width: model.isStroke ? model.stroke.width : 0,
          },
        };
        updateTopic(cell.id, updateData as any, setMindProjectInfo);
      }
    });
  };

  // 设置表单数据
  const handleSetFormModel = (key: string, value: any) => {
    const obj = cloneDeep(formModel);
    set(obj, key, value);
    setFormModel(obj);
    handleChange(obj);
  };

  return (
    <div>
      <section className="px-16px">
        <div className="flex justify-between items-center">
          <div className="font-bold mb-8px">形状</div>
          <div className="flex gap-12px mb-8px">
            <div className="bg-white rounded-s flex justify-between items-center">
              <Button
                type="text"
                icon={
                  <Icon
                    icon="local:round-rect"
                    className="text-14px"
                    width="20"
                  />
                }
                className={
                  formModel.borderSize === BorderSize.none ? "active" : ""
                }
                disabled={!selectedCell.length}
                onClick={() =>
                  handleSetFormModel("borderSize", BorderSize.none)
                }
              />
              <Button
                type="text"
                icon={<Icon icon="local:round-small" width="20" />}
                className={
                  formModel.borderSize === BorderSize.medium ? "active" : ""
                }
                disabled={!selectedCell.length}
                onClick={() =>
                  handleSetFormModel("borderSize", BorderSize.medium)
                }
              />
              <Button
                type="text"
                icon={<Icon icon="local:round-big" width="20" />}
                className={
                  formModel.borderSize === BorderSize.large ? "active" : ""
                }
                disabled={!selectedCell.length}
                onClick={() =>
                  handleSetFormModel("borderSize", BorderSize.large)
                }
              />
            </div>
          </div>
        </div>
        <div className="flex items-center justify-between">
          <Checkbox
            disabled={!selectedCell?.length}
            checked={formModel.fixedWidth}
            onChange={(e) => handleSetFormModel("fixedWidth", e.target.checked)}
          >
            固定宽度
          </Checkbox>
          <InputNumber
            className="w-96px"
            suffix={<FontSizeOutlined />}
            step={1}
            min={12}
            max={10000}
            formatter={(val) => `${val}px`}
            parser={(val) => Number(val?.replace("px", ""))}
            disabled={!formModel.fixedWidth}
            value={formModel.width}
            onChange={(val) => handleSetFormModel("width", val)}
          />
        </div>
      </section>
      <Divider className="my-8px" />
      <section className="px-16px">
        <div className="font-bold mb-8px">文本</div>
        <div className="flex items-center  gap-12px mb-8px">
          <Select
            className="flex-1"
            disabled={!selectedCell?.length}
            options={fontFamilyOptions}
            value={formModel.text.fontFamily}
            labelRender={(item) => item.value}
            onChange={(val) => handleSetFormModel("text.fontFamily", val)}
          />
          <CustomColorPicker
            disabled={!selectedCell?.length}
            color={formModel.text.color}
            onChange={(color) => handleSetFormModel("text.color", color)}
          />
        </div>
        <div className="flex items-center gap-12px mb-8px">
          <InputNumber
            className="flex-1"
            prefix={<FontSizeOutlined />}
            step={1}
            min={12}
            max={10000}
            formatter={(val) => `${val}px`}
            parser={(val) => Number(val?.replace("px", ""))}
            disabled={!selectedCell?.length}
            value={formModel.text.fontSize}
            onChange={(val) => handleSetFormModel("text.fontSize", val)}
          />
          <div className="bg-white rounded-s flex justify-between items-center">
            <Tooltip placement="bottom" title="字体加粗">
              <Button
                type="text"
                icon={<BoldOutlined />}
                className={formModel.text.bold ? "active" : ""}
                disabled={!selectedCell?.length}
                onClick={() =>
                  handleSetFormModel("text.bold", !formModel.text.bold)
                }
              />
            </Tooltip>
            <Tooltip placement="bottom" title="字体倾斜">
              <Button
                type="text"
                icon={<ItalicOutlined />}
                className={formModel.text.italic ? "active" : ""}
                disabled={!selectedCell?.length}
                onClick={() =>
                  handleSetFormModel("text.italic", !formModel.text.italic)
                }
              />
            </Tooltip>
            <Tooltip placement="bottom" title="下划线">
              <Button
                type="text"
                icon={<UnderlineOutlined />}
                className={
                  formModel.text.textDecoration === "underline" ? "active" : ""
                }
                disabled={!selectedCell?.length}
                onClick={() =>
                  handleSetFormModel(
                    "text.textDecoration",
                    formModel.text.textDecoration === "underline"
                      ? "none"
                      : "underline"
                  )
                }
              />
            </Tooltip>
            <Tooltip placement="bottom" title="中划线">
              <Button
                type="text"
                icon={<StrikethroughOutlined />}
                className={
                  formModel.text.textDecoration === "line-through"
                    ? "active"
                    : ""
                }
                disabled={!selectedCell?.length}
                onClick={() =>
                  handleSetFormModel(
                    "text.textDecoration",
                    formModel.text.textDecoration === "line-through"
                      ? "none"
                      : "line-through"
                  )
                }
              />
            </Tooltip>
          </div>
        </div>
        <div className="flex items-center gap-12px">
          <div className="bg-white rounded-s flex justify-between items-center">
            <Tooltip title="左对齐">
              <Button
                type="text"
                icon={<i className="iconfont icon-zuoduiqi" />}
                className={formModel.text.textAlign === "left" ? "active" : ""}
                disabled={!selectedCell?.length}
                onClick={() => handleSetFormModel("text.textAlign", "left")}
              />
            </Tooltip>
            <Tooltip title="居中">
              <Button
                type="text"
                icon={<i className="iconfont icon-juzhong" />}
                className={
                  formModel.text.textAlign === "center" ? "active" : ""
                }
                disabled={!selectedCell?.length}
                onClick={() => handleSetFormModel("text.textAlign", "center")}
              />
            </Tooltip>
            <Tooltip title="右对齐">
              <Button
                type="text"
                icon={<i className="iconfont icon-youduiqi" />}
                className={formModel.text.textAlign === "right" ? "active" : ""}
                disabled={!selectedCell?.length}
                onClick={() => handleSetFormModel("text.textAlign", "right")}
              />
            </Tooltip>
          </div>
        </div>
      </section>
      <Divider className="my-8px" />
      <section className="px-16px">
        <div className="flex items-center justify-between mb-8px">
          <Checkbox
            disabled={!selectedCell?.length}
            checked={formModel.isStroke}
            onChange={(e) => handleSetFormModel("isStroke", e.target.checked)}
          >
            边框
          </Checkbox>
          <CustomColorPicker
            disabled={!formModel.isStroke}
            color={formModel.stroke.color}
            onChange={(color) => handleSetFormModel("stroke.color", color)}
          />
        </div>
        <div className="flex gap-12px mb-8px">
          <InputNumber
            className="flex-1"
            step={1}
            min={1}
            max={10}
            formatter={(val) => `${val}px`}
            parser={(val) => Number(val?.replace("px", ""))}
            disabled={!formModel.isStroke}
            value={formModel.stroke.width}
            onChange={(val) => handleSetFormModel("stroke.width", val)}
          />
          <Select
            className="flex-1"
            options={[
              { label: "实线", value: "solid" },
              { label: "虚线", value: "dashed" },
              { label: "点线", value: "dotted" },
            ]}
            disabled={!formModel.isStroke}
            value={formModel.stroke.type}
            onChange={(value) => handleSetFormModel("stroke.type", value)}
          />
        </div>
      </section>
      <Divider className="my-8px" />
      <section className="px-16px">
        <div className="flex items-center justify-between mb-8px">
          <Checkbox
            disabled={!selectedCell?.length}
            checked={formModel.isFill}
            onChange={(e) => handleSetFormModel("isFill", e.target.checked)}
          >
            填充
          </Checkbox>
          <CustomColorPicker
            disabled={!formModel.isFill}
            color={formModel.fill.color1}
            onChange={(color) => handleSetFormModel("fill.color1", color)}
          />
        </div>
      </section>
      <Divider className="my-8px" />
      <section className="px-16px">
        <div className="flex items-center justify-between mb-8px">
          <div className="font-bold mb-8px">连线</div>
          <CustomColorPicker
            disabled={
              !selectedCell?.length || formModel.type === TopicType.main
            }
            color={formModel.edge.color}
            onChange={(color) => handleSetFormModel("edge.color", color)}
          />
        </div>
        <div className="flex gap-12px mb-8px">
          <InputNumber
            className="flex-1"
            step={1}
            min={1}
            max={10}
            formatter={(val) => `${val}px`}
            parser={(val) => Number(val?.replace("px", ""))}
            disabled={
              !selectedCell?.length || formModel.type === TopicType.main
            }
            value={formModel.edge.width}
            onChange={(val) => handleSetFormModel("edge.width", val)}
          />
        </div>
      </section>
    </div>
  );
}
