/*
 * @Author: your name
 * @Date: 2021-11-16 09:12:37
 * @LastEditTime: 2022-02-14 11:39:52
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: /KC-MiddlePlatform/src/pages/index/components/topBar/index.tsx
 */

import React, { useEffect, useState } from 'react';

import styles from './style.less';

import { Tooltip } from 'antd';
import { LogoutOutlined, SettingOutlined } from '@ant-design/icons';

import logo from '../../../public/images/kc-logo.png';
import platFormMenuIcon from '../../../public/images/platformMenu.png';
import tabCloseIcon from '../../../public/images/tabCloseIcon.png';

import { history } from 'umi';

interface TopBarType {
  onTabChange?: (data: TopBar.Tab[]) => void; //当tab切换时回调
  sysList: TopBar.Tab[]; //可选系统列表
  openedTabs: TopBar.Tab[]; //已打开的列表
  currentTab?: TopBar.Tab | undefined; //当前tab
  userPannelTabClick?: (tag: 'SETTING' | 'LOGOUT' | 'SETUSERINFO') => void;
  onCloseTab?: (data: TopBar.Tab) => void;
  onTabClick?: (data: TopBar.Tab) => void;
  userData?: { name: string; [key: string]: any };
}

const TopBar: React.FC<TopBarType> = (props) => {
  const {
    onTabChange,
    sysList = [],
    openedTabs = [],
    currentTab,
    userPannelTabClick,
    onCloseTab,
    onTabClick,
    userData,
  } = props;
  const [systemTabs, setSystemTabs] = useState<TopBar.Tab[]>([]); //已打开的tab
  const [currentSelectedTab, setCurrentSelectedTab] = useState<TopBar.Tab>();
  const [ifOpenPannel, setIfOpenPannel] = useState(false);
  const [arrowRotate, setArrowRotate] = useState(false);
  // const [opendedTabs,setOpendedTabs] = useState<SystemListItem[]>([]);

  const _systemTabClickHandle = (item: TopBar.Tab) => {
    //导航栏tab点击
    // console.log('tab click');
    setCurrentSelectedTab(item);
    onTabClick && onTabClick(item);
  };

  const _systemListClickHandle = (data: TopBar.Tab) => {
    //导航栏系统菜单列表点击回调
    const findIndex = systemTabs.findIndex((t) => t.id == data.id);
    if (findIndex != -1) return;
    _systemTabClickHandle(data); //触发一次tab点击
    setSystemTabs([...systemTabs, data]);
    onTabChange && onTabChange([...systemTabs, data]);
  };

  const _userPannelTabClick = (tag: 'SETTING' | 'LOGOUT') => {
    //用户菜单tab点击回调
    userPannelTabClick && userPannelTabClick(tag);
  };

  const closeTabHandle = (item: TopBar.Tab, e: React.MouseEvent) => {
    e.stopPropagation();
    let _systemTabs = [...systemTabs];
    let delIndex = -1;

    const filtered = _systemTabs.filter((t, index) => {
      if (t.id == item.id) {
        delIndex = index;
      }
      return t.id != item.id;
    });

    setSystemTabs([...filtered]);
    if (delIndex != 0) {
      _systemTabClickHandle(_systemTabs[delIndex - 1]); //自动切换为前一个tab
    }

    onTabChange && onTabChange(filtered);
    onCloseTab && onCloseTab(item);
  };

  const UserPannel = () => {
    return (
      <div className={styles.userPannel}>
        <div className={styles.userPannelTab} onClick={() => _userPannelTabClick('SETTING')}>
          <SettingOutlined />
          设置
        </div>
        <div className={styles.userPannelTab} onClick={() => _userPannelTabClick('LOGOUT')}>
          <LogoutOutlined />
          退出
        </div>
      </div>
    );
  };

  useEffect(() => {
    if (openedTabs.length == 1) {
      //当有且仅当只有一个的时候，默认激活
      setCurrentSelectedTab(openedTabs[0]);
      history.push(openedTabs[0].url);
    }
    if (openedTabs.length == 0) {
      //当所有tab都关闭时
      setCurrentSelectedTab(undefined);
      history.push('/index');
    }
  }, [openedTabs]);

  useEffect(() => {
    // console.log('Topbar props',props);
    setSystemTabs(openedTabs);
    currentTab && setCurrentSelectedTab(currentTab);
  }, [props]);

  return (
    <div className={styles.topBar}>
      <div className={styles.logoWrap}>
        <img className={styles.logo} src={logo} />
      </div>
      <div
        className={ifOpenPannel ? `${styles.platformMenu} ${styles.on}` : `${styles.platformMenu}`}
        onClick={() => setIfOpenPannel(!ifOpenPannel)}
      >
        <img src={platFormMenuIcon} />
        <div className={styles.systemPannel}>
          {sysList.map((item) => (
            <div
              key={item.id}
              className={styles.systemList}
              onClick={() => _systemListClickHandle(item)}
            >
              <img src={item.icon} alt="" />
              <div className={styles.systemListName}>{item.name}</div>
            </div>
          ))}
        </div>
      </div>
      {/**
       * 已打开的tab
       */}
      <div className={styles.tabWrap}>
        {systemTabs.map((item) => (
          <div
            key={item.id}
            className={
              currentSelectedTab?.id == item.id ? `${styles.tab} ${styles.on}` : `${styles.tab}`
            }
            onClick={() => _systemTabClickHandle(item)}
          >
            <div className={styles.tabText}>{item.name} </div>
            <div className={styles.closeIconWrap}>
              <img src={tabCloseIcon} onClick={(e) => closeTabHandle(item, e)} alt="close" />
            </div>
          </div>
        ))}
      </div>
      <div className={styles.userRelaInfoWrap}>
        <div className={styles.notification}>
          <img
            className={styles.notificationIcon}
            src={require('../../../public/images/notificationIcon.png')}
          />
        </div>
        <Tooltip
          title={<UserPannel />}
          color="#fff"
          onVisibleChange={(visible) => setArrowRotate(visible)}
        >
          <div className={styles.user}>
            <img className={styles.avator} src={require('../../../public/images/Mask.png')} />
            <span className={styles.name}>{userData?.name}</span>
            <img
              className={arrowRotate ? `${styles.arrow} ${styles.on}` : `${styles.arrow}`}
              src={require('../../../public/images/arrow_white.png')}
            />
          </div>
        </Tooltip>
      </div>
    </div>
  );
};

export default TopBar;
