import React, { useEffect } from 'react';
import {
  deleteDataMgmt,
  getDataMgmtList,
  uploadTableStatus
} from './api/datamanage';
import Menu from '@mui/material/Menu';
import MenuItem from '@mui/material/MenuItem';
import fileIcon from '../style/img/table.png';
import { message } from 'antd';
interface IProps {
  onOpenData: (tableInfo: any) => void;
}

const DataManage: React.FC<IProps> = props => {
  const [contextMenu, setContextMenu] = React.useState<{
    mouseX: number;
    mouseY: number;
  } | null>(null);

  const [currentTable, setCurrentTable] = React.useState<any | null>(null);
  const [tables, setTables] = React.useState<any>([]);
  const [loading, setLoading] = React.useState<boolean>(false);

  useEffect(() => {
    void fetchDataMgmtList();
  }, []);

  const fetchDataMgmtList = async () => {
    setLoading(true);
    const { data } = await getDataMgmtList();
    if (data.code === 200) {
      setTables(data.data);
    } else {
      void message.error(data.msg);
    }
    setLoading(false);
  };

  const tableClick = (table: any) => {
    void fetchTableStatus(table);
  };

  const handleContextMenu = (event: React.MouseEvent, table: any) => {
    event.preventDefault();
    setContextMenu(
      contextMenu === null
        ? {
            mouseX: event.clientX + 2,
            mouseY: event.clientY - 6
          }
        : // repeated contextmenu when it is already open closes it with Chrome 84 on Ubuntu
          // Other native context menus might behave different.
          // With this behavior we prevent contextmenu from the backdrop to re-locale existing context menus.
          null
    );
    setCurrentTable(table);
  };

  const handleClose = () => {
    setContextMenu(null);
  };

  const handleWatch = () => {
    setContextMenu(null);
    void fetchTableStatus(currentTable);
  };

  const handleDelete = async () => {
    setContextMenu(null);
    void fetchDeleteDataMgmt();
  };

  const fetchDeleteDataMgmt = async () => {
    const { data } = await deleteDataMgmt(currentTable.id);
    if (data.code === 200) {
      void message.success('删除成功');
      void fetchDataMgmtList();
    } else {
      void message.error(data.msg);
    }
  };

  const fetchTableStatus = async (table: any) => {
    if (table.status === 1) {
      const { data } = await uploadTableStatus(table.id);
      if (data.code === 200) {
        switch (data.data.status) {
          case 1:
            void message.info('数据表正在转存');
            break;
          case 2:
            props.onOpenData(table);
            break;
          case 3:
            void message.error('数据表转存失败');
            break;
          default:
            break;
        }
      } else {
        void message.error(data.msg);
      }
    } else if (table.status === 3) {
      void message.error('数据表转存失败');
    } else {
      props.onOpenData(table);
    }
  };

  const contextMenuView = (
    <Menu
      open={contextMenu !== null}
      onClose={handleClose}
      anchorReference="anchorPosition"
      anchorPosition={
        contextMenu !== null
          ? { top: contextMenu.mouseY, left: contextMenu.mouseX }
          : undefined
      }
    >
      <MenuItem onClick={handleWatch}>查看</MenuItem>
      <MenuItem onClick={handleDelete}>删除</MenuItem>
    </Menu>
  );

  let el: JSX.Element[] | JSX.Element;
  if (loading) {
    el = <div className="datamanage-label">Loading ...</div>;
  } else {
    el = tables.map((item: any) => {
      return (
        <div
          className="datamanage-label"
          onDoubleClick={() => tableClick(item)}
          onContextMenu={evt => handleContextMenu(evt, item)}
          key={item.id}
        >
          <img className="datamanage-img" src={fileIcon} alt="" />
          <span>{item.name}</span>
        </div>
      );
    });
  }

  return (
    <div className="datamanage">
      {el}
      {contextMenuView}
    </div>
  );
};

export default DataManage;
