import {useContextSection} from '@hooks';
import css from './index.module.css';
import {FC, ReactNode, useEffect, useReducer, useRef} from 'react';
import {context} from '../../context';
import classNames from 'classnames';
import {useStore} from 'zustand';
import {tabStore} from '@stores';

const TabPanel: FC = function () {
  const tabs = useContextSection(context, state => state[0]);
  const nodes = useRef<Map<string, ReactNode>>(new Map());
  const [, forceupdate] = useReducer(() => ({}), {});
  const {key: activeKey} = useStore(tabStore);

  useEffect(
    function () {
      // 如果长度相同 说明是修改顺序或者调整内容
      if (tabs.length === nodes.current.size) return;
      const map = nodes.current;
      const nextMap = new Map<string, ReactNode>();

      // 创建新的map 遍历查询内容 如果有复用 没有创建一个
      tabs.forEach(function ({key, url}) {
        if (map.has(key)) {
          nextMap.set(key, map.get(key));
        } else {
          nextMap.set(key, <iframe src={url} className={css.iframe} />);
        }
      });

      nodes.current = nextMap;

      forceupdate();
    },
    [nodes, tabs],
  );

  return (
    <div className={css.tabPanel}>
      {Array.from(nodes.current.entries()).map(function ([key, node]) {
        return (
          <div
            key={key}
            className={classNames(css.iframeWrapper, {
              [css.iframeTop]: key === activeKey,
            })}
          >
            {node}
          </div>
        );
      })}
    </div>
  );
};

export default TabPanel;
