import { SearchOutlined, SwapOutlined } from "@ant-design/icons";
import {
  Button,
  Descriptions,
  Form,
  Input,
  InputNumber,
  Popconfirm,
  Popover,
  Select,
  Tooltip,
} from "antd";
import React, { useEffect } from "react";
import { RELATION_TYPE_OPTIONS } from "@/constants";
import { useModel } from "umi";
import noData from "@/assets/no-data.png";
import { ColumnRelation } from "@/type";
import { useSessionStorageState } from "ahooks";
import CustomColorPicker from "@/components/CustomColorPicker";
import { RelationLineType } from "@/enum";

// import line1 from "@/assets/image/line-dashdot.png";
import line2 from "@/assets/image/line-dashed.png";
import line3 from "@/assets/image/line-solid.png";
import line4 from "@/assets/image/line-dotted.png";

export default function RelationPanel() {
  const { project, updateRelation, deleteRelation } = useModel("erModel");
  const [search, setSearch] = React.useState("");

  const list = React.useMemo(() => {
    return project.relations.filter((item) => item.name.includes(search));
  }, [search, project.relations]);

  const [active, setActive] = useSessionStorageState("relation-active", {
    defaultValue: "",
    listenStorageChange: true,
  });

  const handleChange = (index: number, key: string, value: any) => {
    const data = project.relations[index];
    updateRelation({
      ...data,
      [key]: value,
    });
  };

  const handleSwitchChange = (record: ColumnRelation) => {
    updateRelation({
      ...record,
      primaryTable: record.foreignTable,
      primaryKey: record.foreignKey,
      foreignTable: record.primaryTable,
      foreignKey: record.primaryKey,
    });
  };

  const getPrimaryColumn = (item: ColumnRelation) => {
    const tableItem = project.tables.find(
      (table) => table.table.id === item.primaryTable
    );

    return {
      table: tableItem?.table,
      column: tableItem?.tableColumnList.find(
        (column) => column.id === item.primaryKey
      ),
    };
  };

  const getForeignColumn = (item: ColumnRelation) => {
    const tableItem = project.tables.find(
      (table) => table.table.id === item.foreignTable
    );
    return {
      table: tableItem?.table,
      column: tableItem?.tableColumnList.find(
        (column) => column.id === item.foreignKey
      ),
    };
  };

  const CustomInput = ({
    value,
    onChange,
  }: {
    value: string;
    onChange: (value: string) => void;
  }) => {
    const [name, setName] = React.useState(value);
    useEffect(() => {
      setName(value);
    }, [value]);
    return (
      <Input
        value={name}
        onChange={(e) => {
          setName(e.target.value);
        }}
        onBlur={() => {
          if (name.trim()) {
            onChange(name);
          } else {
            setName(value);
          }
        }}
      />
    );
  };

  return (
    <div className="px-12px">
      <Input
        placeholder="输入关键字搜索"
        className="m-b-10px"
        suffix={<SearchOutlined />}
        value={search}
        onChange={(e) => setSearch(e.target.value)}
      />
      {list.map((item, index) => {
        return (
          <div
            className="
            border-b-solid 
            border-b-[#e4e4e4] 
            border-b-[1px]"
            key={item.id}
          >
            <div
              className="
              header 
              flex 
              items-center 
              justify-between 
              leading-[40px] 
              hover:bg-[#fafafa] 
              cursor-pointer 
              m-b-[10px]"
              onClick={() => setActive(active === item.id ? "" : item.id)}
            >
              <div className="font-bold truncate">{item.name}</div>
              <div>
                <i
                  className="iconfont icon-open m-r-10px inline-block"
                  style={{
                    transform:
                      active === item.id ? "rotate(180deg)" : "rotate(0deg)",
                    transition: "all 0.3s",
                  }}
                />
              </div>
            </div>
            <div
              className="content overflow-hidden grid"
              style={{
                gridTemplateRows: active === item.id ? "1fr" : "0fr",
                transition: "all 0.3s",
              }}
            >
              <Form layout="vertical" className="overflow-hidden">
                <Form.Item label="名称" layout="horizontal">
                  <CustomInput
                    value={item.name}
                    onChange={(val) => handleChange(index, "name", val)}
                  />
                </Form.Item>
                <div className="flex justify-between gap-25px">
                  <Form.Item className="w-120px" label="主键">
                    <Tooltip title={getPrimaryColumn(item)?.table?.schemaName}>
                      <div className="truncate">
                        {getPrimaryColumn(item)?.table?.schemaName}
                      </div>
                    </Tooltip>
                  </Form.Item>
                  <Form.Item className="w-120px" label="外键">
                    <Tooltip title={getForeignColumn(item)?.table?.schemaName}>
                      <div className="truncate">
                        {getForeignColumn(item)?.table?.schemaName}
                      </div>
                    </Tooltip>
                  </Form.Item>
                  <Popover
                    trigger="click"
                    placement="right"
                    content={
                      <div className="min-w-200px">
                        <Descriptions
                          layout="vertical"
                          bordered
                          items={[
                            {
                              key: "1",
                              label: "主键",
                              children: (
                                <span>
                                  {getPrimaryColumn(item)?.table?.schemaName}(
                                  {getPrimaryColumn(item)?.column?.schemaName})
                                </span>
                              ),
                            },
                            {
                              key: "2",
                              label: "外键",
                              children: (
                                <span>
                                  {getForeignColumn(item)?.table?.schemaName}(
                                  {getForeignColumn(item)?.column?.schemaName})
                                </span>
                              ),
                            },
                          ]}
                        />
                        <Button
                          className="w-full m-y-4px"
                          icon={<SwapOutlined />}
                          type="primary"
                          onClick={() => handleSwitchChange(item)}
                        >
                          交换
                        </Button>
                      </div>
                    }
                  >
                    <div className="rounded-4px cus-btn w-32px h-32px bg-#eee flex-none text-center leading-32px cursor-pointer hover:bg-#ddd">
                      <i className="iconfont icon-gengduo" />
                    </div>
                  </Popover>
                </div>
                <div className="flex justify-between">
                  <Form.Item label="连线类型" className="flex-1 m-r-12px">
                    <Select
                      placeholder="请选择"
                      options={[
                        {
                          value: RelationLineType.Dash,
                          label: <img className="h-16px" src={line2} />,
                        },
                        {
                          value: RelationLineType.Solid,
                          label: <img className="h-16px" src={line3} />,
                        },
                        {
                          value: RelationLineType.Dotted,
                          label: <img className="h-16px" src={line4} />,
                        },
                      ]}
                      value={item.style?.lineType}
                      onChange={(val) =>
                        handleChange(index, "style", {
                          ...item.style,
                          lineType: val,
                        })
                      }
                    />
                  </Form.Item>
                  <Form.Item label="宽度" className="flex-1 m-r-12px">
                    <InputNumber
                      min={1}
                      max={10}
                      value={item.style?.width}
                      className="w-full"
                      onChange={(val) =>
                        handleChange(index, "style", {
                          ...item.style,
                          width: val,
                        })
                      }
                    />
                  </Form.Item>
                  <Form.Item label="颜色">
                    <CustomColorPicker
                      color={item.style?.color}
                      onChange={(color) =>
                        handleChange(index, "style", { ...item.style, color })
                      }
                    >
                      <div
                        className="rounded-4px cus-btn w-32px h-32px bg-#eee flex-none cursor-pointer shadow-inner"
                        style={{ background: item.style?.color || "#eee" }}
                      ></div>
                    </CustomColorPicker>
                  </Form.Item>
                </div>
                <Form.Item label="对应关系" layout="vertical">
                  <Select
                    placeholder="请选择对应关系"
                    className="w-full"
                    options={RELATION_TYPE_OPTIONS}
                    value={item.relationType}
                    onChange={(val) => handleChange(index, "relationType", val)}
                  ></Select>
                </Form.Item>
                <div>
                  <Popconfirm
                    okType="default"
                    title="确定删除该关系？"
                    okText="确定"
                    cancelText="取消"
                    onConfirm={() => deleteRelation(item.id)}
                  >
                    <Button danger className="m-y-10px w-full">
                      删除
                    </Button>
                  </Popconfirm>
                </div>
              </Form>
            </div>
          </div>
        );
      })}
      {list.length === 0 && (
        <div className="flex flex-col items-center justify-center h-[300px]">
          <img src={noData} alt="暂无数据" className="w-[200px] h-[200px]" />
          <div className="text-gray-400">拖拽字段形成关系！</div>
        </div>
      )}
    </div>
  );
}
