import React, { useState, useRef, useCallback, useEffect } from 'react';
import { useHistory, useLocation } from 'react-router-dom';
import { getKeyName } from '../../utils/utils';
const TabPanes = props => {
  const [activeKey, setActiveKey] = useState('');
  const [panes, setPanes] = useState([
    {
      title: '首页',
      key: 'home',
      closable: false,
      path: '/',
    },
  ]);

  const [isReload, setIsReload] = useState(false);
  const [selectedPanel, setSelectedPanel] = useState({});
  const pathRef = useRef(null);

  const {
    storeData: { curTab, reloadPath },
    setStoreData,
    defaultActiveKey,
    panesItem,
    tabActiveKey,
  } = props;

  const history = useHistory();
  const { pathname, search } = useLocation();

  const fullPath = pathname + search;

  const storeTabs = useCallback(
    ps => {
      const pathArr = ps.reduce((prev, next) => [...prev, next.path], []);
      // setStoreData('SET_CURTAB', pathArr)
    },
    [setStoreData],
  );

  const resetTabs = useCallback(() => {
    const initPanes = curTab.reduce((prev, next) => {
      const { title, tabKey, Content } = getKeyName(next);
      return [
        ...prev,
        {
          title,
          key: tabKey,
          content: Content,
          closable: tabKey !== 'home',
          path: next,
        },
      ];
    }, []);
    const { tabKey } = getKeyName(pathname);
    setPanes(initPanes);
    setActiveKey(tabKey);
  }, [curTab, pathname]);

  useEffect(() => {
    resetTabs();
  }, [resetTabs]);

  const onChange = tabKey => {
    setActiveKey(tabKey);
  };

  const remove = targetKey => {
    const delIndex = panes.findIndex(item => item.key === targetKey);
    panes.splice(delIndex, 1);

    if (targetKey !== activeKey) {
      const nextKey = activeKey;
      setPanes(panes);
      setActiveKey(nextKey);
      storeTabs(panes);
      return;
    }

    const nextPath = curTab[delIndex - 1];
    const { tabKey } = getKeyName(nextPath);
    if (nextPath !== '/') {
      remove(tabKey);
      history.push(curTab[delIndex - 2]);
    } else {
      history.push(nextPath);
    }
    setPanes(panes);
    storeTabs(panes);
  };

  const onEdit = (targetKey, action) =>
    action === 'remove' && remove(targetKey);

  const onTabClick = targetKey => {
    const { path } = panes.filter(item => item.key === targetKey)[0];
    history.push({ pathname: path });
  };

  const refreshTab = () => {
    setIsReload(true);
    setTimeout(() => {
      setIsReload(false);
    }, 1000);
    setStoreData('SET_RELOADPATH', pathname + search);
    setTimeout(() => {
      setStoreData('SET_RELOADPATH', 'null');
    }, 500);
  };
};
