import { FC, useEffect, useRef, useState } from 'react';
import styles from './index.less';
import { history, useLocation, useParams } from 'umi';
import { Menu, Tree } from 'antd';
import { unitAddressList } from '@/services/register';
import eventBus from '@/utils/eventBus';

interface PageProps {
  data: Array<{
    // 菜单名称
    name: string;
    // 是否展开
    check: boolean;
    // 内容是否有目录结构
    isTree?: boolean;
    // 菜单列表 ： name: 名称; url: 路由; img: 图标;
    data: Array<{ name: string; url: string; img: any; }>
  }>;
}

const LeftMenuCom: FC<PageProps> = ({ data }) => {
  const [list, setList] = useState<any>([]);
  const urlParams = useParams();
  const location = useLocation();

  const [selectedKeys, setSelectedKeys] = useState<any>([]);
  const [contextMenuPosition, setContextMenuPosition] = useState({ x: 0, y: 0 });
  const [showContextMenu, setShowContextMenu] = useState(false);
  const treeRef = useRef(null);

  const [menuItems, setMenuItems] = useState<any>([]);
  const [treeKey, setTreeKey] = useState<any>(0);

  const [treeData, setTreeData] = useState([
    {
      title: 'xxx管理系统',
      key: 'root',
      selectable: true,
      isFolder: true,
      children: [],
    }
  ]);

  const [treeData1, setTreeData1] = useState([
    {
      title: '所有单位位置',
      key: 'root',
      selectable: true,
      isFolder: true,
      children: [],
    }
  ]);

  let urlStr = `${urlParams?.fileType}${location?.search}`;

  useEffect(() => {
    menuItemsConfig();
  }, [location?.pathname])

  useEffect(() => {
    data.forEach((item, index) => {
      // 默认展开第一个
      // item.check = (index == 0 ? true : false);
      // 默认全部展开
      item.check = true;

      if (item?.isTree) setSelectedKeys([urlParams?.id])
    })
    setList([...data])

    const handleClickOutside = (e: any) => {
      if (treeRef.current && !treeRef.current.contains(e.target)) {
        // 点击了 MyTree 组件以外的地方，隐藏菜单
        setShowContextMenu(false);
      }
    };
    document.addEventListener('click', handleClickOutside);
    return () => {
      document.removeEventListener('click', handleClickOutside);
    };
  }, [])


  useEffect(() => {
    eventBus.on('getUnitList', getUnitList);
    return () => {
      eventBus.off('getUnitList', getUnitList);
    };
  }, [])

  const menuItemsConfig = () => {
    if (`/registerManage/deviceRegister/${urlStr}` == `${location.pathname}${location.search}`) {
      setMenuItems([
        { key: '1', label: '删除' },
        { key: '2', label: '刷新' },
      ])
    } else if (`/registerManage/unitLocation/${urlStr}` == `${location.pathname}${location.search}`) {
      setMenuItems([
        { key: '3', label: '修改' },
        { key: '4', label: '刷新' },
        { key: '5', label: '新建' },
        { key: '6', label: '删除' }
      ])
      getUnitList();
    }
  }

  // 更新单位位置管理树结构数据
  const getUnitList = (type?: string) => {
    unitAddressList({ pageNum: 1, pageSize: 50}).then((res: any) => {
      if (res.result == 'success') {
        res.data[0].list.forEach((val: any) => { val.title = val.unitName; val.key = val.id; })
        setTreeData1((e) => { e[0].children = res.data[0].list; return e })
        setTreeKey((e: any) => { return e + 1 })
        if (type == '添加成功') {
          setSelectedKeys([Number(res.data[0].list.length)])
        }else if (type == '删除成功') {
          setSelectedKeys(['root'])
        }
      }
    })
  }

  const handleRightClick = (e: any, node: any) => {
    if (node?.isFolder) return
    e[0] == 'root' ?  eventBus.emit('hideFlag', false) : eventBus.emit('hideFlag', true);
    e.preventDefault();
    setContextMenuPosition({ x: e.clientX, y: e.clientY }); // 记录右键菜单位置
    setSelectedKeys([node.key]); // 根据节点设置选中的 keys
    setShowContextMenu(true); // 显示右键菜单
  };

  const handleSelect = (selectedKeys: any, name: any) => {    
    selectedKeys[0] == 'root' ?  eventBus.emit('hideFlag', false) : eventBus.emit('hideFlag', true);
    setSelectedKeys(selectedKeys);
  };

  const handleContextMenuClick = (e: any) => {
    let index = selectedKeys[0] - 1;
    if(e.key == '3') {
      eventBus.emit('updateUnitInfo', ['修改', treeData1[0].children[index]]);
    } else if(e.key == '6') {
      eventBus.emit('updateUnitInfo', ['删除', treeData1[0].children[index]]);
    }
    
    setShowContextMenu(false); // 隐藏右键菜单    
  };

  const nameType = {
    "设备注册": treeData,
    '单位位置管理': treeData1
  }

  const urlType = {
    "设备注册": '/registerManage/deviceRegister',
    '单位位置管理': '/registerManage/unitLocation'
  }

  return (
    <div>
      {list.map((item: any, index: number) => {
        return (
          <div key={index}>
            {/* 类型 */}
            <div className={styles.menu_item} onClick={() => {
              list[index].check = !list[index].check;
              setList([...list])
            }}>
              <div>{item.name}</div>
              <div className={styles.triangle} style={{ transform: list[index].check ? 'rotate(90deg)' : '' }}></div>
            </div>

            {/* 列表 */}
            <div className={styles.item_warp} style={{ display: list[index].check ? 'block' : 'none' }}>
              {
                item?.isTree ?
                  // 树结构
                  <div>
                    <Tree
                      key={treeKey}
                      style={{ padding: 20 }}
                      onContextMenu={(e) => e.preventDefault()}
                      onRightClick={({ event, node }) => handleRightClick(event, node)}
                      onSelect={(e, { node }) => {
                        if (node.key === 'root') {
                          history.push(`${urlType[item.name]}/${urlStr}`)
                        }

                        handleSelect(e, item.name)
                      }}
                      selectedKeys={selectedKeys}
                      treeData={nameType[item.name]}
                      blockNode={true}
                      defaultExpandAll={true}
                    />
                    {showContextMenu && (
                      <div ref={treeRef}>
                        <Menu
                          style={{
                            zIndex: 99,
                            width: 111,
                            position: 'absolute',
                            left: contextMenuPosition.x,
                            top: contextMenuPosition.y,
                            boxShadow: '0px 4px 8px 0px rgba(156, 172, 180, 0.5)'
                          }}
                          mode="vertical"
                          onClick={handleContextMenuClick}
                          items={menuItems}
                        />
                      </div>
                    )}
                  </div> :
                  // 列表item
                  item.data.map((item1: any, index1: number) => {
                    return (
                      <div className={styles.item1} key={index1} onClick={() => {
                        setSelectedKeys([])
                        history.push(`${item1.url}/${urlStr}`)
                      }}>
                        <div className={styles.item1_img}></div>
                        <div className={styles.item1_name} style={{ color: (`${location.pathname}${location.search}` == `${item1.url}/${urlStr}` ? 'red' : '') }}>
                          {item1.name}
                        </div>
                      </div>
                    )
                  })
              }
            </div>
          </div>
        )
      })}
    </div >
  )
}

export default LeftMenuCom

