import React, { useEffect, useState, useRef } from "react";
import {
  Button,
  Dropdown,
  Input,
  Modal,
  Switch,
  InputNumber,
  Drawer,
} from "antd";
import type { MenuProps } from "antd";
import { useModel } from "umi";
import { useFullscreen, useLocalStorageState } from "ahooks";
import AddModel from "@/components/AddModel";
import { TableType } from "@/enum";
import { getClassRules } from "@repo/utils";
export default function Menu() {
  const {
    project,
    canRedo,
    canUndo,
    onRedo,
    onUndo,
    graph,
    setProject,
    onClean,
    onCut,
    onCopy,
    onPaste,
    onDelete,
    enterPlayMode,
    saveTime,
    onSave,
  } = useModel("erModel");
  const [modal, contextHolder] = Modal.useModal();
  const [isFullscreen, { toggleFullscreen }] = useFullscreen(document.body);
  const [openKey, setOpenKey] = useState("");
  const [open, setOpen] = useState(false);
  const [openFastKey, setOpenFastKey] = useState(false);
  const [name, setName] = useState(project?.name);
  const addModelRef = useRef<{
    open: (type: TableType, folder: string) => void;
  }>();
  // 隐藏默认字段
  const [hideDefaultColumn, setHideDefaultColumn] = useLocalStorageState(
    "er-hideDefaultColumn",
    {
      defaultValue: false,
      listenStorageChange: true
    }
  );

  useEffect(() => {
    setName(project.name);
  }, [project.name]);
  const handleClean = () => {
    modal.confirm({
      title: "确认清除画布全部内容？",
      content: "清空后将无法恢复",
      cancelText: "取消",
      okText: "确定",
      onOk() {
        onClean();
      },
    });
  };

  const handleChangeSetting = (key: string, value: boolean | number | null) => {
    setProject({ ...project, setting: { ...project.setting, [key]: value } });
  };

  const handleChangeName = () => {
    name.trim() && setProject({ ...project, name });
  };

  const handleZoom = (value: number) => {
    if (value < 0.2) {
      graph?.zoomTo(0.2);
      return;
    } else if (value > 2) {
      graph?.zoomTo(2);
      return;
    }
    graph?.zoomTo(value);
  };

  const handleExportImage = () => {
    if (!graph) return;

    graph.exportPNG(project.name, {
      quality: 1,
      padding: 20,
      copyStyles: false,
      serializeImages: true,
      stylesheet: getClassRules()
    });
  };

  const menuData: {
    key: string;
    label: string;
    type: "group";
    children: MenuProps["items"];
  }[] = [
    {
      key: "1",
      label: "文件",
      type: "group",
      children: [
        {
          key: "1-1",
          label: (
            <span className="flex items-center justify-between">
              <span>新建</span>
              <span className="color-#666">ctrl+n</span>
            </span>
          ),
          onClick: () => {
            addModelRef.current?.open(project.type, project.directory);
          },
        },
        // { key: "1-2", label: "新标签页打开" },
        {
          key: "1-3",
          label: (
            <span className="flex items-center justify-between">
              <span>保存</span>
              <span className="color-#666">ctrl+s</span>
            </span>
          ),
          onClick: onSave,
        },
        { key: "1-4", label: "保存为模版" },
        { key: "1-5", label: "发布模版" },
        { key: "1-6", label: "同步数据表" },
        {
          key: "1-7",
          label: "导出为图片",
          onClick: () => handleExportImage(),
        },
      ],
    },
    {
      key: "2",
      label: "编辑",
      type: "group",
      children: [
        {
          key: "1-1",
          label: (
            <span className="flex items-center justify-between">
              <span>撤销</span>
              <span className="color-#666">ctrl+z</span>
            </span>
          ),
          onClick: () => canUndo && onUndo(),
        },
        {
          key: "1-2",
          label: (
            <span className="flex items-center justify-between">
              <span>恢复</span>
              <span className="color-#666">ctrl+y</span>
            </span>
          ),
          onClick: () => canRedo && onRedo(),
        },
        { key: "1-3", label: "清除", onClick: handleClean },
        {
          key: "1-4",
          label: (
            <span className="flex items-center justify-between">
              <span>剪切</span>
              <span className="color-#666">ctrl+x</span>
            </span>
          ),
          onClick: onCut,
        },
        {
          key: "1-5",
          label: (
            <span className="flex items-center justify-between">
              <span>复制</span>
              <span className="color-#666">ctrl+c</span>
            </span>
          ),
          onClick: onCopy,
        },
        {
          key: "1-6",
          label: (
            <span className="flex items-center justify-between">
              <span>粘贴</span>
              <span className="color-#666">ctrl+v</span>
            </span>
          ),
          onClick: onPaste,
        },
        {
          key: "1-7",
          label: (
            <span className="flex items-center justify-between">
              <span>删除</span>
              <span className="color-#666">delete</span>
            </span>
          ),
          onClick: onDelete,
        },
      ],
    },
    {
      key: "3",
      label: "视图",
      type: "group",
      children: [
        {
          key: "1-1",
          label: (
            <span className="flex items-center justify-between">
              <span>菜单栏隐藏</span>
              <Switch
                size="small"
                checked={project.setting.showMenu}
                onChange={(checked) => handleChangeSetting("showMenu", checked)}
              />
            </span>
          ),
        },
        {
          key: "1-2",
          label: (
            <span className="flex items-center justify-between">
              <span>侧边栏隐藏</span>
              <Switch
                size="small"
                checked={project.setting.showSidebar}
                onChange={(checked) =>
                  handleChangeSetting("showSidebar", checked)
                }
              />
            </span>
          ),
        },
        { key: "1-3", label: "演示模式", onClick: () => enterPlayMode() },
        {
          key: "1-4",
          label: (
            <span className="flex items-center justify-between">
              <span>字段详情</span>
              <Switch
                size="small"
                checked={project.setting.showColumnDetail}
                onChange={(checked) =>
                  handleChangeSetting("showColumnDetail", checked)
                }
              />
            </span>
          ),
        },
        {
          key: "1-11",
          label: (
            <span className="flex items-center justify-between">
              <span>隐藏默认字段</span>
              <Switch
                size="small"
                checked={hideDefaultColumn}
                onChange={(checked) =>
                  setHideDefaultColumn(checked)
                }
              />
            </span>
          ),
        },
        {
          key: "1-5",
          label: (
            <span className="flex items-center justify-between">
              <span>显示网格</span>
              <Switch
                size="small"
                checked={project.setting.showGrid}
                onChange={(checked) => handleChangeSetting("showGrid", checked)}
              />
            </span>
          ),
        },
        {
          key: "1-6",
          label: (
            <span className="flex items-center justify-between">
              <span>显示关系</span>
              <Switch
                size="small"
                checked={project.setting.showRelation}
                onChange={(checked) =>
                  handleChangeSetting("showRelation", checked)
                }
              />
            </span>
          ),
        },
        { key: "1-7", label: "重置视图", onClick: () => graph?.zoomTo(1) },
        {
          key: "1-8",
          label: (
            <span className="flex items-center justify-between">
              <span>放大</span>
              <span className="color-#666">ctrl+up</span>
            </span>
          ),
          onClick: () => handleZoom((graph?.zoom() || 1) + 0.2),
        },
        {
          key: "1-9",
          label: (
            <span className="flex items-center justify-between">
              <span>缩小</span>
              <span className="color-#666">ctrl+down</span>
            </span>
          ),
          onClick: () => handleZoom((graph?.zoom() || 1) - 0.2),
        },
        {
          key: "1-10",
          label: isFullscreen ? "退出全屏" : "全屏",
          onClick: () => toggleFullscreen(),
        },
      ],
    },
    {
      key: "4",
      label: "设置",
      type: "group",
      children: [
        { key: "1-1", label: "修改记录" },
        // {
        //   key: "1-2",
        //   label: (
        //     <span className="flex items-center justify-between">
        //       <span>自动保存</span>
        //       <Switch
        //         size="small"
        //         checked={project.setting.autoUpdate}
        //         onChange={(checked) =>
        //           handleChangeSetting("autoUpdate", checked)
        //         }
        //       />
        //     </span>
        //   ),
        // },
        // {
        //   key: "1-3",
        //   label: (
        //     <span className="flex items-center justify-between">
        //       <span>自动同步</span>
        //       <Switch size="small" />
        //     </span>
        //   ),
        // },
        {
          key: "1-4",
          label: "表格宽度",
          onClick: () => setOpen(true),
        },
      ],
    },
    {
      key: "5",
      label: "帮助",
      type: "group",
      children: [
        { key: "1-1", label: "快捷键", onClick: () => setOpenFastKey(true) },
        { key: "1-2", label: "操作说明" },
      ],
    },
  ];

  const fastKeyList = [
    { key: "CTRL+Z", label: "撤销" },
    { key: "CTRL+Y", label: "重做" },
    { key: "CTRL+C", label: "复制" },
    { key: "CTRL+V", label: "粘贴" },
    { key: "CTRL+X", label: "剪切" },
    { key: "DELETE", label: "删除" },
    { key: "CTRL+UP", label: "放大" },
    { key: "CTRL+DOWN", label: "缩小" },
    { key: "CTRL+S", label: "保存" },
  ];

  const handleOpenChange = (
    nextOpen: boolean,
    info: { source: "trigger" | "menu" },
    key: string
  ) => {
    if (info.source === "trigger" || nextOpen) {
      setOpenKey(nextOpen ? key : "");
    }
  };

  const handleAddAfter = (id: any) => {
    const { origin, pathname } = window.location;
    const enterpriseCode = sessionStorage.getItem("enterpriseCode");
    window.open(
      `${origin}${pathname}#/detail/${id}?enterpriseCode=${enterpriseCode}`
    );
  };

  return (
    <>
      <div className="flex-1 flex items-center">
        {contextHolder}
        <Drawer
          placement="right"
          title="快捷键"
          open={openFastKey}
          onClose={() => setOpenFastKey(false)}
        >
          {fastKeyList.map((item, index) => {
            return (
              <div
                key={index}
                className="flex items-center leading-48px odd:bg-gray-100 p-x-8px"
              >
                <div className="flex-1 font-bold text-16px">{item.key}</div>
                <div className="flex-1 text-right color-#666">{item.label}</div>
              </div>
            );
          })}
        </Drawer>
        <div className="logo h-48px m-l-12px">
          <svg className="icon h-48px w-48px" aria-hidden="true">
            <use xlinkHref="#icon-shujujianmo"></use>
          </svg>
        </div>
        <div className="h-full">
          <div className="leading-32px flex items-center">
            <Input
              className="text-24px max-w-200px"
              variant="borderless"
              value={name}
              onChange={(e) => setName(e.target.value)}
              onBlur={handleChangeName}
              onPressEnter={handleChangeName}
            />
            {saveTime && (
              <div className="bg-#eee text-12px leading-20px color-#666 rounded-4px p-x-4px p-y-2px">
                上次保存时间：{saveTime}
              </div>
            )}
          </div>
          <div className="flex">
            {menuData.map((item) => {
              return (
                <Dropdown
                  key={item.key}
                  menu={{ items: item.children, style: { width: 200 } }}
                  placement="bottomLeft"
                  open={openKey === item.key}
                  onOpenChange={(nextOpen, info) =>
                    handleOpenChange(nextOpen, info, item.key)
                  }
                >
                  <Button type="text" size="small">
                    {item.label}
                  </Button>
                </Dropdown>
              );
            })}
          </div>
        </div>
      </div>
      <Modal
        title="设置表格宽度"
        centered
        width={440}
        open={open}
        okText="确定"
        onOk={() => setOpen(false)}
        onCancel={() => setOpen(false)}
        footer={(_, { OkBtn }) => {
          return <OkBtn />;
        }}
      >
        <InputNumber
          className="w-full"
          min={150}
          max={1000}
          value={project.setting.tableWidth}
          onChange={(value) => handleChangeSetting("tableWidth", value)}
        />
      </Modal>
      <AddModel ref={addModelRef} onChange={handleAddAfter} />
    </>
  );
}
