import React, { useState, useEffect, useLayoutEffect, useRef, useMemo, useCallback } from 'react';
import Title from './Title';
import { Row, Col, Popover } from 'antd'
import { uuid, simpleGrid } from '../utils/index'
import IconFont from '../../../themeComponents/IconFont';
import './index.less';

function TwoRowLayout({ onTabChange, activeKey, className, defaultKey, tabList, isRightHead, titleGrid, extGrid, ...props }) {
  const [renderKeys, setRenderKey] = useState(activeKey || defaultKey ? [activeKey || defaultKey] : [tabList[0].name]);
  const { customCenterExtContent, rightExtContent, hasRightExt } = props;
  const headerLayoutLetfId = useMemo(() => `header-left-ext-layout-${uuid()}`, []);
  const headerLayoutRightId = useMemo(() => `header-right-ext-layout-${uuid()}`, []);
  const index = useMemo(() => tabList.findIndex((v) => v.name === activeKey), [activeKey, tabList]);
  // eslint-disable-next-line react-hooks/exhaustive-deps
  useEffect(() => setRenderKey((keys) => {
    if (!keys.includes(activeKey)) {
      keys.push(activeKey);
    }
    return [...keys]
  }), [activeKey]);



  /**
   * 切换当前key值
   * @param {*} item
   * @param {*} index
   */
  const onTabClick = useCallback((item, index) => {
    if (activeKey !== item.name) {
      setRenderKey((keys) => {
        if (!keys.includes(item.name)) {
          keys.push(item.name);
        }
        return [...keys]
      });
      onTabChange && onTabChange(item, index);
    }
  }, [onTabChange])
  return (
    <Row className={`lm-c-two-row-layout ${className} ${isRightHead ? 'lm-c-two-row-layout-right-header' : ''}`}>
      <HeaderLayout
        tabList={tabList}
        headerLayoutLetfId={headerLayoutLetfId}
        headerLayoutRightId={headerLayoutRightId}
        onTabClick={onTabClick}
        activeKey={activeKey}
        index={index}
        customCenterExtContent={customCenterExtContent}
        titleGrid={titleGrid}
        extGrid={extGrid}
        rightExtContent={rightExtContent}
        hasRightExt={hasRightExt}
      />

      <div className="lm-c-two-row-col-content">
        <div style={{ width: `${tabList.length * 100}%`, marginLeft: `-${index * 100}%` }} className="lm-c-two-row-content-box">
          {tabList.map((item, i) => (
            <div key={item.name} className="lm-c-two-row-content">
              {renderKeys.indexOf(item.name) > -1 &&
                React.cloneElement(item.content, {
                  ...props,
                  activeKey,
                  getHeaderLeftExtContent: () => document.querySelector(`.${headerLayoutLetfId}-${i}`),
                  getHeaderRightExtContent: () => document.querySelector(`.${headerLayoutRightId}-${i}`),
                  tabItem: item,
                })}
            </div>
          ))}
        </div>
      </div>
    </Row>
  );
}

function HeaderLayout({ title, titleGrid, extGrid, onTabClick, hasRightExt, ...props }) {
  const tabWidht = useMemo(() => 100, []);
  const [renderSize, setRenderSize] = useState(2);
  const { tabList, index, customCenterExtContent, activeKey, rightExtContent, headerLayoutLetfId, headerLayoutRightId } = props;
  const boxRef = useRef(null);
  useLayoutEffect(() => {
    const computeSize = () => {
      const { width } = boxRef.current.getBoundingClientRect();
      setRenderSize(Math.floor(width / tabWidht));
    };
    computeSize();
    window.addEventListener('resize', computeSize, false);
    return () => window.removeEventListener('resize', computeSize, false);
  }, [tabWidht]);

  const [tabList1, tabList2] = useMemo(() => [tabList.slice(0, renderSize), tabList.slice(renderSize)], [renderSize]);

  return (
    <div className="two-row-layout-header">
      <Row className="two-row-layout-header" type="flex" align="middle">
        <Col className={`two-row-layout-header-title `} {...titleGrid}>
          <div className="header-title-layout">
            {title && <Title title={title} />}
            {tabList.map((_, i) => (
              <div key={`${headerLayoutLetfId}-${i}`} className={`${headerLayoutLetfId}-${i}`} style={{ width: '100%', height: '100%', display: i === index ? 'block' : 'none' }} />
            ))}
          </div>
        </Col>

        <div className="two-row-layout-header-tab" style={{ overflow: customCenterExtContent ? 'unset' : 'hidden' }} ref={boxRef}>
          {customCenterExtContent ? (
            <Row className="two-row-layout-header two-row-layout-header-ext-center" type="flex" justify="center" align="middle">
              <div>{customCenterExtContent}</div>
            </Row>
          ) : (
              <Tabs
                activeKey={activeKey}
                tabList={tabList1}
                tabIndex={index}
                onTabClick={onTabClick}
                extContent={
                  tabList2.length > 0 && (
                    <Popover placement="bottom" overlayClassName="tab-ext-popover" content={<TabsRow tabList={tabList2} activeKey={activeKey} onTabClick={onTabClick} />}>
                      <IconFont type="icon-S_Edit_Menu" className={`tab-hidden-ext ${tabList2.findIndex((item) => item.name === activeKey) > -1 ? 'tab-hidden-ext-active' : ''}`} />
                    </Popover>
                  )
                }
              />
            )}
        </div>
        {hasRightExt && (
          <Col className={`two-row-layout-header-ext ${headerLayoutRightId}`} {...extGrid}>
            {rightExtContent}
            {tabList.map((_, i) => (
              <div
                key={`${headerLayoutRightId}-${i}`}
                className={`${headerLayoutRightId}-${i}`}
                style={{ width: '100%', height: '100%', display: i === index ? 'block' : 'none' }}
              />
            ))}
          </Col>
        )}
      </Row>
    </div>
  );
}

function Tabs({ tabList, activeKey, onTabClick, extContent }) {
  const [movex, setMovex] = useState(0);
  const tabRef = useRef(null);

  useLayoutEffect(() => {
    function computedX() {
      const layerRect = tabRef.current.getBoundingClientRect();
      const acticeDom = tabRef.current.querySelector('.lm-tab-item-active');
      if (!acticeDom) {
        return;
      }
      const activeRect = acticeDom.getBoundingClientRect();
      const activeX = activeRect.x - layerRect.x;
      const x = activeX + activeRect.width / 2 - 12;
      x !== movex && setMovex(x);
    }
    setTimeout(() => computedX(), 100);
    window.addEventListener('resize', computedX, false);
    return () => window.removeEventListener('resize', computedX, false);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [activeKey]);

  function onTabItemClick(e, item, index) {
    e && e.stopPropagation && e.stopPropagation()
    onTabClick(item, index);
  }
  return (
    <>
      <div className="lm-two-row-tab-layout" ref={tabRef}>
        {tabList.map((item, index) => (
          <div
            key={item.name}
            onClick={(e) => onTabItemClick(e, item, index)}
            title={item.title}
            className={`lm-two-row-tab-item ${activeKey === item.name ? 'lm-tab-item-active' : ''}`}
          >
            {item.icon && <IconFont type={item.icon} />}
            {item.title}
          </div>
        ))}
        {extContent}
      </div>
      <div className="lm-tab-select-border">
        <div style={{ transform: `translate3d(${movex}px,0,0)` }} className="lm-two-row-tab-border" />
      </div>
    </>
  );
}

function TabsRow({ tabList, activeKey, onTabClick }) {
  return (
    <div className="lm-tab-row-style-layout">
      {tabList.map((item, index) => (
        <div key={item.name} onClick={() => onTabClick(item, index)} title={item.title} className={`lm-two-row-tab-item ${activeKey === item.name ? 'lm-tab-item-active' : ''}`}>
          {item.icon && <IconFont type={item.icon} />}
          {item.title}
        </div>
      ))}
    </div>
  );
}

TwoRowLayout.defaultProps = {
  className: '',
  tabList: [],
  titleGrid: simpleGrid,
  extGrid: simpleGrid,
  hasRightExt: true,
  isRightHead: false,
};

export default React.memo(TwoRowLayout);
