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

export default function RelationPanel() {
  const { project, addRelation, 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] = React.useState("");

  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)
    }
  };

  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">{item.name}</div>
              <div>
                <i className="iconfont icon-open m-r-10px" />
              </div>
            </div>
            <div
              className="content overflow-hidden"
              style={{ height: active === item.id ? "auto" : 0 }}
            >
              <Form layout="vertical">
                <div className="flex justify-between">
                  <Form.Item label="主键">
                    {getPrimaryColumn(item)?.table?.schemaName}
                  </Form.Item>
                  <Form.Item label="外键">
                    {getForeignColumn(item)?.table?.schemaName}
                  </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>
                <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 color="danger" 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>
  );
}
