/**
 * @file Tabs
 * @description 选项卡
 * @author fex
 */

import React, { ChangeEvent, CompositionEvent, ReactNode } from 'react';
import { ResizeEvent, Schema } from '../types';
import Transition, { ENTERED, ENTERING } from 'react-transition-group/Transition';
import { themeable, ThemeProps } from '../theme';
import { uncontrollable } from 'uncontrollable';
import { generateIcon } from '../utils/icon';
import { SchemaClassName } from '../Schema';
import { autobind, domUtils, flatSuperData, isMobile } from '../utils/helper';
import debounce from 'lodash/debounce';
import LionCopyItem from '../renderers/Lion/components/LionCopyItem/index';
import { RendererEnv } from '../env';
import ActionSheet from './Lion/ActionSheet';
import { Icon } from './icons';
import { Input, Dropdown } from 'antd';
import type { MenuProps } from 'antd';
import { CaretLeftOutlined, CaretRightOutlined, DoubleLeftOutlined, DoubleRightOutlined, EllipsisOutlined } from '@ant-design/icons';
import { flatMap } from 'lodash';

const transitionStyles: {
  [propName: string]: string;
} = {
  [ENTERING]: 'in',
  [ENTERED]: 'in'
};

export type TabsMode = '' | 'line' | 'card' | 'radio' | 'vertical' | 'chrome' | 'content-tiled';

export interface TabProps extends ThemeProps {
  title?: string | React.ReactNode; // 标题
  icon?: string;
  iconPosition?: 'left' | 'right';
  disabled?: boolean | string;
  eventKey: string | number;
  tab?: Schema;
  className?: string;
  activeKey?: string | number;
  reload?: boolean;
  data?: any;
  mountOnEnter?: boolean;
  unmountOnExit?: boolean;
  toolbar?: React.ReactNode;
  totalTab?: any;
  children: React.ReactNode | Function | any;
  /**
  * 是否为tab添加数字展示
  **/
  isTotalMode?: boolean;
  env?: RendererEnv;
  setTotalNum?: any;
  mode?: TabsMode;
  tabName?: string
  notPrintFieldList?: string[]
}
interface TabsState {
  toolsOpened: boolean;
}

class TabComponent extends React.PureComponent<TabProps, TabsState> {

  contentDom: any;
  contentRef = (ref: any) => (this.contentDom = ref);
  state = {
    toolsOpened: false
  }

  render() {
    const {
      classnames: cx,
      mountOnEnter,
      reload,
      unmountOnExit,
      eventKey,
      activeKey,
      children,
      className,
      env,
      isTotalMode,
      title,
      mode,
      tabName,
      notPrintFieldList
    } = this.props;
    return (
      <Transition
        in={mode === 'content-tiled' ? true : activeKey === eventKey}
        mountOnEnter={mountOnEnter === false ? false : true}
        unmountOnExit={typeof reload === 'boolean' ? reload : unmountOnExit}
        timeout={500}
      >
        {(status: string) => {
          if (status === ENTERING) {
            this.contentDom.offsetWidth;
          }

          return (
            <div
              ref={this.contentRef}
              className={cx(
                transitionStyles[status],
                activeKey === eventKey ? 'is-active' : '',
                notPrintFieldList?.includes(tabName ?? '') ? 'dom-not-print' : '',
                'Tabs-pane',
                className
              )}
            >
              {mode === 'content-tiled' &&
                <div className={cx('Tabs-pane-title')}>
                  <LionCopyItem
                    showItems={[{
                      value: tabName ?? 'null',
                      label: "复制名称",
                      icon: "fa fa-sticky-note-o"
                    }]}
                    env={env!}  >
                    <span style={{ cursor: 'pointer' }}> {title} </span>
                  </LionCopyItem>
                </div>
              }
              {/* tab顶部数字显示 chencicsy */}
              {isTotalMode ? children(this.props.setTotalNum, this.props.totalTab) : children}
            </div>
          );
        }}
      </Transition>
    );
  }
}

export const Tab = themeable(TabComponent);

export interface TabsProps extends ThemeProps {
  mode: TabsMode;
  tabsMode?: TabsMode;
  data: any;
  additionBtns?: React.ReactNode;
  onSelect?: (key: string | number) => void;
  activeKey?: string | number;
  contentClassName: string;
  linksClassName?: SchemaClassName;
  className?: string;
  tabs?: Array<TabProps>;
  tabRender?: (tab: TabProps, props?: TabsProps) => JSX.Element;
  toolbar?: React.ReactNode;
  scrollable?: boolean // 是否支持溢出滚动
  /**
    * 是否为tab添加数字展示
  **/
  isTotalMode?: boolean;
  env?: RendererEnv;
  useMobileUI?: boolean; //Aug
  mountOnEnter?: boolean;//点击tab页时才加载，现在由内部tab控制，以前是tabs统一控制
  handleReload?: (children: ReactNode) => void;
  notPrintFieldList?: string[]
  getTabsActiveKeys?: () => string[];
}

export class Tabs extends React.Component<TabsProps, any> {
  static defaultProps: Pick<TabsProps, 'mode' | 'contentClassName' | 'isTotalMode'> = {
    mode: '',
    contentClassName: '',
    isTotalMode: false
  };

  static Tab = Tab;
  navMain = React.createRef<HTMLDivElement>();
  scroll: boolean = false;
  ulRef: React.RefObject<HTMLUListElement> = React.createRef();
  // collpaseRef: React.RefObject<HTMLDivElement> = React.createRef();
  tabsRef: React.RefObject<HTMLDivElement> = React.createRef();
  tabContentRef: React.RefObject<HTMLDivElement> = React.createRef();
  scrollRef: React.RefObject<HTMLSpanElement> = React.createRef();
  scrollRefChildren: React.RefObject<HTMLDivElement> = React.createRef();
  pageContentId: string;
  checkArrowStatus = debounce(
    () => {
      const { scrollLeft, scrollWidth, clientWidth } = this.navMain.current
        || {
        scrollLeft: 0,
        scrollWidth: 0,
        clientWidth: 0
      }
      const { arrowRightDisabled, arrowLeftDisabled } = this.state;
      if (scrollLeft === 0 && !arrowLeftDisabled) {
        this.setState({
          arrowRightDisabled: false,
          arrowLeftDisabled: true
        });
      } else if (scrollWidth === scrollLeft + clientWidth && !arrowRightDisabled) {
        this.setState({
          arrowRightDisabled: true,
          arrowLeftDisabled: false
        });
      } else if (scrollLeft !== 0 && arrowLeftDisabled) {
        this.setState({
          arrowLeftDisabled: false
        });
      } else if (scrollWidth !== scrollLeft + clientWidth && arrowRightDisabled) {
        this.setState({
          arrowRightDisabled: false
        });
      }
    },
    100,
    {
      trailing: true,
      leading: false
    }
  )
  menuItems: MenuProps['items'] = [];

  constructor(props: TabsProps) {
    super(props);
    const menuItems = (props?.children ?? []).filter(Boolean).map((item) => ({ label: item.props.title, key: `${item.props.eventKey}` }));
    this.state = {
      isHovered: false,
      isOverflow: false,
      tabsSearchQuery: '', // tabs名字搜索功能
      arrowLeftDisabled: false,
      arrowRightDisabled: false,
      /* tab顶部数字 chencicsy */
      tabsTotal: Array.isArray(this.props.children) ? ((that: any) => {
        let keysContainer: any = {};
        that.props?.children.filter(Boolean).forEach((tab: any, idx: number) => {
          keysContainer[idx] = {
            key: idx,
            totalNum: '0'
          }
        })
        return keysContainer
      })(this) : { 0: { key: 0, totalNum: '0' } },
      navVisible: true,
      menuItems,
      cacheMenuItems: menuItems
    };
    this.tempTabsTotal = this.state.tabsTotal
  }

  componentDidMount() {
    this.computedWidth();
    if (this.navMain) {
      this.navMain.current?.addEventListener('wheel', this.handleWheel, {
        passive: false
      });
      this.checkArrowStatus();

      // 用于解决AI助手固定右侧的时候显示异常
      const pageContentDom = domUtils.closest(this.navMain.current as HTMLElement, '.main-page-content');
      const pageContentIdMatch = pageContentDom?.className.split(' ').find((item) => item.includes('page-content-id_')) ?? '';
      this.pageContentId = pageContentIdMatch;
    }
  }

  componentDidUpdate() {
    // 判断是否是由滚动触发的数据更新，如果是则不需要再次判断容器与内容的关系
    if (!this.scroll) {
      this.computedWidth();
    }

    this.scroll = false;
  }

  componentWillUnmount() {
    this.checkArrowStatus.cancel();
  }

  tempTabsTotal = {};

  /* 修改tab顶部数字显示 chencicsy */
  handleChangeTotal(key: string | number, totalNum: number, tableName?: string, statiStics?: string) {
    const { tabsTotal } = this.state
    let currentTab: any = Object.entries(tabsTotal).find((tab: any[]) => {
      return String(key) === String(tab[0]) && String(key) === String(tab[1]?.key)
    })

    if (currentTab && totalNum !== currentTab[1]?.totalNum) {
      // Jay，设置当前tab页的第一个CRUD、主从表的总数，第一次的setState就认为tableName是第一个CRUD、主从表的name值，防止picker弹出的CRUD覆盖了总数
      let temp: any;
      if (!tabsTotal[key].tableName) {
        temp = {
          [key]: {
            key: key,
            totalNum: totalNum,
            tableName
          }
        }
      } else if (tabsTotal[key].key === key && (statiStics && tableName === statiStics)) {
        // if (statiStics && tableName === statiStics) {
        temp = {
          [key]: {
            key: key,
            totalNum: totalNum,
            tableName
          }
        }
        // }
      } else if (tabsTotal[key].tableName === tableName) {
        temp = {
          [key]: {
            key: key,
            totalNum: totalNum,
            tableName
          }
        }
      }
      //因为在上一个state还未更新完之前，另一个crud也调用了这个方法，导致覆盖了上一次的值，所以这里使用私有属性记录一下，实时更新
      if (temp) {
        this.tempTabsTotal[key] = temp[key]
        this.setState({
          tabsTotal: {
            ...this.tempTabsTotal,
            ...temp
          }
        })
      }
    }
  }

  /**
   * 处理内容与容器之间的位置关系
   */
  computedWidth() {
    const { mode: dMode, tabsMode, scrollable } = this.props;
    const mode = tabsMode || dMode;
    if (!scrollable || mode === 'vertical') {
      return;
    }
    const navMainRef = this.navMain.current;
    const clientWidth: number = navMainRef?.clientWidth || 0;
    const scrollWidth: number = navMainRef?.scrollWidth || 0;
    const isOverflow = scrollWidth > clientWidth;
    // 内容超出容器长度标记溢出
    if (isOverflow !== this.state.isOverflow) {
      this.setState({ isOverflow });
    }
    if (isOverflow) {
      this.showSelected();
    }
  }
  /**
   * 保证选中的tab始终显示在可视区域
   */
  showSelected(key?: string | number) {
    const { mode: dMode, tabsMode, scrollable } = this.props;
    const { isOverflow } = this.state;
    const mode = tabsMode || dMode;
    if (!scrollable || mode === 'vertical' || !isOverflow) {
      return;
    }
    const { activeKey, children } = this.props;
    const currentKey = key !== undefined ? key : activeKey;
    const currentIndex = (children as any[])?.filter(Boolean).findIndex(
      (item: any) => item.props.eventKey === currentKey
    );
    const li = this.navMain.current?.children[0]?.children || [];
    const currentLi = li[currentIndex] as HTMLElement;
    const liOffsetLeft = currentLi?.offsetLeft - 20;
    const liClientWidth = currentLi?.clientWidth;
    const scrollLeft = this.navMain.current?.scrollLeft || 0;
    const clientWidth = this.navMain.current?.clientWidth || 0;

    // 左边被遮住了
    if (scrollLeft > liOffsetLeft) {
      this.navMain.current?.scrollTo({
        left: liOffsetLeft,
        behavior: 'smooth'
      });
    }
    // 右边被遮住了
    if (liOffsetLeft + liClientWidth > scrollLeft + clientWidth) {
      this.navMain.current?.scrollTo({
        left: liOffsetLeft + liClientWidth - clientWidth,
        behavior: 'smooth'
      });
    }
  }

  handleSelect(key: string | number) {
    const { onSelect } = this.props;
    this.showSelected(key);
    setTimeout(() => {
      this.checkArrowStatus();
    }, 500);
    onSelect && onSelect(key);
  }

  handleArrow(type: 'left' | 'right') {
    const { scrollLeft, scrollWidth, clientWidth } = this.navMain.current
      || {
      scrollLeft: 0,
      scrollWidth: 0,
      clientWidth: 0
    }
    if (type === 'left' && scrollLeft > 0) {
      this.navMain.current?.scrollTo({
        left: 0,
        behavior: 'smooth'
      });
      this.setState({
        arrowRightDisabled: false,
        arrowLeftDisabled: true
      });
    } else if (type === 'right' && scrollWidth > scrollLeft + clientWidth) {
      this.navMain.current?.scrollTo({
        left: this.navMain.current?.scrollWidth,
        behavior: 'smooth'
      });
      this.setState({
        arrowRightDisabled: true,
        arrowLeftDisabled: false
      });
    }
    this.scroll = true;
  }

  /**
   * 监听导航上的滚动事件
   */
  @autobind
  handleWheel(e: WheelEvent) {
    const { deltaY, deltaX } = e;
    const absX = Math.abs(deltaX);
    const absY = Math.abs(deltaY);

    // 当鼠标上下滚动时转换为左右滚动
    if (absY > absX) {
      this.navMain.current?.scrollTo({
        left: this.navMain.current?.scrollLeft + deltaY
      });
      e.preventDefault();
    }
    this.checkArrowStatus();
    this.scroll = true;
  }
  openWin = (child: any) => {
    const appShell: any = window['AppShell'];
    const winSchemeData = child?.props.body[0]
    appShell?.openNewWin({ ...winSchemeData, title: child?.props.title }, sessionStorage, flatSuperData(this.props.data))
  }
  renderNav(child: any, index: number) {
    if (!child) {
      return;
    }

    const { classnames: cx, activeKey: activeKeyProp, mode, classPrefix: ns, env } = this.props;
    const { tabsTotal } = this.state;
    const {
      eventKey,
      disabled,
      icon,
      iconPosition,
      title,
      toolbar,
      tabClassName,
      isTotalMode
    } = child.props;
    const activeKey =
      activeKeyProp === undefined && index === 0 ? eventKey : activeKeyProp;

    const iconElement = generateIcon(cx, icon, 'Icon');
    let menuItems: any[] = [{
      value: child.props?.tabName ?? 'null',
      label: "复制名称",
      icon: "fa fa-sticky-note-o"
    }, {
      value: 'openNew',
      label: "在新标签页打开",
      icon: "fa fa-clone",
      click: () => {
        env?.onPageLink?.(child.props.body?.[0]?.name ?? '', child.props?.tabName ?? '', child.props.title, { schema: child.props.body?.[0], appId: sessionStorage.getItem('appId') ?? '' }, undefined)
      }
    }]
    const currentDom = this.tabsRef.current;
    const needCollect = currentDom && !(currentDom.closest(`.${ns}Modal`) || currentDom.closest(`.${ns}Drawer`) || currentDom.closest(`.ant-modal`) || currentDom.closest(`.ant-drawer`)) && child.props.tabName;
    if (needCollect) {
      const collectStr = sessionStorage.getItem('collectList') ?? ''
      if (collectStr) {
        const collectList = JSON.parse(collectStr)
        const collectedTabList: any[] = flatMap(collectList ?? [], (item: any) => item.secondList).filter((item: any) => item.content && item.content?.isTab);
        const menuStr = sessionStorage.getItem('currentSecondMenu')
        let targetItem: any = undefined;
        if (menuStr) {
          const currentSecondMenu = JSON.parse(menuStr)
          targetItem = collectedTabList?.find(node => node.content?.appId == sessionStorage.getItem('appId') &&
            (currentSecondMenu.secMenuId ? node.content?.secMenuId == currentSecondMenu?.secMenuId :
              node.content?.menuId == currentSecondMenu?.menuId) &&
            node.content?.tabName == child.props.tabName)
        }
        menuItems.push({
          value: targetItem ? 'cancel-collect' : 'collect',
          label: targetItem ? "取消收藏" : "加入收藏",
          icon: "fa fa-star-o",
          click: async (val: string) => {
            const keyList = this.props.getTabsActiveKeys?.();
            //更改这个，因为第一项永远是激活项
            keyList?.shift();
            keyList?.unshift(child.props.tabName);
            const menuStr = sessionStorage.getItem('currentSecondMenu')
            if (menuStr) {
              const currentSecondMenu = JSON.parse(menuStr)
              delete currentSecondMenu.favId
              await this.props?.env?.handleCollect?.({
                ...currentSecondMenu,
                collected: false,
                ...(targetItem ? { ...targetItem.content, favId: targetItem.favId, collected: true } : {}),
                isTab: true,
                tabName: child.props.tabName,
                keyList: keyList,
                title: child.props.title,
                tabKey: child.props.eventKey
              })
              this.forceUpdate()
            }
          }
        })
      }
    }
    return (
      // chencicsy 用于执行赋值name操作
      <LionCopyItem
        canOpenWin={true}
        openWin={() => this.openWin(child)}
        showItems={menuItems}
        env={this.props?.env!}
      >
        <li
          className={cx(
            'Tabs-link',
            activeKey === eventKey ? 'is-active' : '',
            disabled ? 'is-disabled' : '',
            tabClassName
          )}
          key={eventKey ?? index}
          onClick={() => (disabled ? '' : this.handleSelect(eventKey))}
        >
          <a>
            {icon ? (
              iconPosition === 'right' ? (
                <>
                  {title} {iconElement}
                </>
              ) : (
                <>
                  {iconElement} {title}
                </>
              )
            ) : (
              title
            )}
            {React.isValidElement(toolbar) ? toolbar : null}
            {isTotalMode ? (tabsTotal[index].totalNum === '0' ? null : <span>({tabsTotal[index].totalNum > 99 ? '99+' : tabsTotal[index]?.totalNum})</span>) : null}
          </a>
          {mode === 'chrome' ? (
            <div className="chrome-tab-background">
              <svg viewBox="0 0 124 124" className="chrome-tab-background--right">
                <path d="M0,0 C0,68.483309 55.516691,124 124,124 L0,124 L0,-1 C0.00132103964,-0.667821298 0,-0.334064922 0,0 Z"></path>
              </svg>
              <svg viewBox="0 0 124 124" className="chrome-tab-background--left">
                <path d="M124,0 L124,125 L0,125 L0,125 C68.483309,125 124,69.483309 124,1 L123.992,0 L124,0 Z"></path>
              </svg>
            </div>
          ) : null}
        </li>
      </LionCopyItem >
    );
  }

  renderTab(child: any, index: number) {
    if (!child) {
      return;
    }

    const { activeKey: activeKeyProp, classnames, mode, mountOnEnter, notPrintFieldList } = this.props;
    const eventKey = child.props.eventKey;
    const activeKey =
      activeKeyProp === undefined && index === 0 ? eventKey : activeKeyProp;

    return React.cloneElement(child, {
      ...child.props,
      env: this.props.env,
      key: eventKey,
      totalTab: this.state.tabsTotal[index],
      setTotalNum: (key: string | number, totalNum: number, tableName?: string, statiStics?: string) => { if (!child?.props?.isTotalMode) return; this.handleChangeTotal(key, totalNum, tableName, statiStics) },
      classnames: classnames,
      activeKey: activeKey,
      mountOnEnter: mode === 'content-tiled' ? false : child.props?.mountOnEnter,
      mode,
      notPrintFieldList
    });
  }

  renderArrow(type: 'left' | 'right') {
    const { mode: dMode, tabsMode, } = this.props;
    const mode = tabsMode || dMode;
    if (mode === 'vertical') {
      return;
    }
    const { classnames: cx } = this.props;
    const { isOverflow, arrowLeftDisabled, arrowRightDisabled } = this.state;
    const disabled = type === 'left' ? arrowLeftDisabled : arrowRightDisabled;
    return (isOverflow
      ? (<div onClick={() => this.handleArrow(type)}
        className={cx(
          'Tabs-linksContainer-arrow',
          'Tabs-linksContainer-arrow--' + type,
          disabled && 'Tabs-linksContainer-arrow--disabled'
        )}>
        {/* <i className={'iconfont icon-arrow-' + type} /> */}
        {/* Aug */}
        <i className={'fa fa-chevron-' + type} />
      </div>)
      : null
    )
  }
  /** 防抖过滤关键词 */
  handleFilterItem = debounce((e: ChangeEvent<HTMLInputElement>) => {
    const isComposing = e.nativeEvent.isComposing;
    if (isComposing) return;
    const matchItems = this.state.cacheMenuItems.filter((item) => item.label.includes(e.target.value));
    this.setState({ menuItems: matchItems });
  }, 300);
  handleComposition = (e: CompositionEvent<HTMLInputElement>) => {
    const isEnd = e.type === 'compositionend';
    if (isEnd) {
      this.handleFilterItem(e);
    }
  }

  /** 渲染下拉菜单 */
  renderMoreItems = () => {
    const { isOverflow } = this.state;
    return isOverflow ? (
      <div className="Tabs-allItems">
        <Dropdown
          overlayClassName='overlay-allItems'
          trigger={['hover']}
          placement='bottomRight'
          getPopupContainer={() => document.getElementById('amis-modal-container')}
          menu={{ items: this.state.menuItems, onClick: this.handleClickItem, selectable: true, selectedKeys: [].concat(`${this.props?.activeKey ?? 0}`) }}
          dropdownRender={menu => (
            <div className='dropdown-wrapper'>
              <div className='filter-wrapper'>
                <Input size='small' placeholder='请输入关键词' onChange={this.handleFilterItem} onCompositionStart={this.handleComposition} onCompositionEnd={this.handleComposition} allowClear />
              </div>
              {menu}
            </div>
          )}
        >
          <div className='emit-icon'>
            <EllipsisOutlined />
          </div>
        </Dropdown>
      </div>
    ) : null
  }
  renderReloadTools = () => {
    const { mode, env } = this.props;
    if (mode === 'content-tiled' && isMobile()) {
      return <ActionSheet
        round
        className='tabs-content-tiled-actions'
        isOpened={this.state.toolsOpened}
        container={env?.getModalContainer}
        onHide={(e: any) => {
          e.stopPropagation();
          this.setState({ toolsOpened: false })
        }}
        popupContent={
          <div className='tabs-reload-tool'>
            <div className='toolbar-title'>

            </div>
            <div className='toolbar-body'>
              <div className='toolbar-item-row'>
                <div className='toolbar-item' onClick={() => {
                  this.setState({ toolsOpened: false })
                  this.props.handleReload?.(this.props.children)
                }}>
                  <div className='icon-bar'>
                    <Icon icon='reload' className='icon' />
                  </div>
                  <div className='icon-title'>刷新</div>
                </div>
              </div>
              <div className='toolbar-item-row toolbar-cancel'>
                <div onClick={() => this.setState({ toolsOpened: false })}>
                  取消
                </div>
              </div>
            </div>
          </div>
        }
      >
        <div className={`tabs-reload-tools ${env?.shottcut ? 'tabs-reload-tools-shottcut' : ''}`} onClick={() => { this.setState({ toolsOpened: true }) }}>
          . . .
        </div>
      </ActionSheet>
    }
    return null
  }

  tabsSeachTimer: any = 0

  // 以下变量都是用于列宽度调整拖拽
  targetThWidth: number;
  lineStartX: number;
  isDragging = false;
  handleMouseDown = (e: React.MouseEvent<HTMLElement>) => {
    if (this.tabsRef.current && this.state.navVisible) {
      this.setState({ isHovered: true })
      this.lineStartX = e.clientX;
      this.isDragging = true;
      this.targetThWidth = this.ulRef.current!.getBoundingClientRect().width;
      this.tabsRef.current.addEventListener('mousemove', this.handleMouseMove);
      this.tabsRef.current.addEventListener('mouseup', this.handleMouseUp);
    }
  }
  handleMouseMove = (e: MouseEvent) => {
    const moveX = e.clientX - this.lineStartX;
    if (this.ulRef.current && this.isDragging) {
      if (this.targetThWidth + moveX <= 80 || this.targetThWidth + moveX >= this.tabsRef.current!.getBoundingClientRect().width - 200) {
        this.isDragging = false;
        this.tabsRef.current!.removeEventListener('mousemove', this.handleMouseMove);
        this.tabsRef.current!.removeEventListener('mouseup', this.handleMouseUp);
        return;
      }
      this.ulRef.current.style.width = this.targetThWidth + moveX + 'px';
    }
  }
  handleMouseUp = (e: MouseEvent) => {
    this.isDragging = false;
    this.setState({ isHovered: false })
    if (e.clientX == this.lineStartX) {
      this.handleClickCollpase()
    }
    if (this.tabsRef.current) {
      this.tabsRef.current.removeEventListener('mousemove', this.handleMouseMove);
      this.tabsRef.current.removeEventListener('mouseup', this.handleMouseUp);
    }
  }

  handleClickCollpase = () => {
    const contentHeight = this.tabContentRef.current?.clientHeight + 'px';
    this.setState({ navVisible: !this.state.navVisible }, () => {
      this.ulRef.current!.style.width = this.state.navVisible ? '160px' : '22px';
      this.ulRef.current!.style.height = contentHeight;
      const { classPrefix: ns } = this.props;
      (this.ulRef.current!.querySelector(`.${ns}Tabs-links-befote`) as HTMLDivElement).style.display = this.state.navVisible ? 'block' : 'none';
      this.scrollRef.current!.style.width = this.state.navVisible ? '8px' : '0px';
    })
  }
  handleClickItem = (item) => {
    const { key } = item;
    this.handleSelect(Number(key));
  }
  render() {
    const {
      classnames: cx,
      contentClassName,
      className,
      mode: dMode,
      tabsMode,
      children,
      additionBtns,
      toolbar,
      linksClassName,
      scrollable,
      useMobileUI
    } = this.props;
    const { isOverflow } = this.state;
    if (!Array.isArray(children)) {
      return null;
    }

    const mode = tabsMode || dMode;

    const mobileUI = isMobile() && useMobileUI;
    const filteredChildren = children.filter(Boolean);
    const showList = filteredChildren.filter(_ => {
      return _?.props?.title?.includes?.(this.state.tabsSearchQuery)
    })
    return (
      <div
        className={cx(
          `Tabs`,
          {
            [`Tabs--${mode}`]: mode
          },
          className
        )}
        ref={this.tabsRef}
      >
        {
          this.renderReloadTools()
        }
        {scrollable && !['vertical', 'chrome'].includes(mode) ? (
          <div
            className={cx(
              'Tabs-linksContainer',
              isOverflow && 'Tabs-linksContainer--overflow'
            )}
          >
            {!mobileUI && this.renderArrow('left')}
            <div className={cx('Tabs-linksContainer-main')} ref={this.navMain}>
              <ul className={cx('Tabs-links', linksClassName)} role="tablist">
                {filteredChildren.map((tab, index) => this.renderNav(tab, index))}
                {additionBtns}
                {toolbar}
              </ul>
            </div>
            {!mobileUI && (
              <>
                {this.renderMoreItems()}
                {this.renderArrow('right')}
              </>
            )}
          </div>
        ) : (
          //style={{ flex: this.state.showLinks ? 1 : undefined, display: this.state.showLinks == undefined ? undefined : this.state.showLinks ? 'flex' : 'none' }}
          <ul className={cx('Tabs-links', linksClassName)} role="tablist" ref={this.ulRef} >
            <div className={cx('Tabs-links-befote')}>
              {(mode === 'vertical' && filteredChildren.length > 5) ?
                <li className={cx('Tabs-links-input')}>
                  <Input
                    placeholder='请输入关键字'
                    type='search'
                    allowClear
                    bordered={false}
                    onChange={(e) => {
                      const value = e.target.value
                      clearTimeout(this.tabsSeachTimer)
                      this.tabsSeachTimer = setTimeout(() => {
                        this.setState({ tabsSearchQuery: value })
                      }, 500)
                    }} />
                </li> : null}
              {showList.map((tab, index) => this.renderNav(tab, index))}

              {!showList.length ? <li style={{
                textAlign: 'center',
                fontSize: '13px',
                padding: '20px'
              }}>该关键词暂无数据</li> : null}
              {additionBtns}
              {toolbar}
            </div>
            {!isMobile() && mode === 'vertical' && <div
              onClick={(e) => {
                e.stopPropagation()
                this.handleClickCollpase()
              }}
              className={`tablinks-collpase ${this.state.navVisible ? '' : 'closed'}`}>
              {
                this.state.navVisible ? <span>
                  <DoubleLeftOutlined style={{fontSize: '11px'}}/>收缩
                </span> : <span>
                  <DoubleRightOutlined style={{fontSize: '11px'}}/>展开
                </span>
              }
            </div>}
            {!isMobile() && mode === 'vertical' && <span className={cx('Tabs--slider',
              { 'slider-closed': !this.state.navVisible })} ref={this.scrollRef}
              onMouseDown={this.handleMouseDown}
            >
              <div className={cx('Tabs--sliders')} ref={this.scrollRefChildren} />
            </span>}
          </ul>
        )
        }
        {/* {!isMobile() && mode === 'vertical' && (
          <div className={cx('Tabs-line')} >
            <div className={'collpase'}
              ref={this.scrollRef}
              onMouseDown={this.handleMouseDown}
              onMouseEnter={() => this.setState({ isHovered: true })}
              onMouseLeave={() => {
                if (!this.isDragging) {
                  this.setState({ isHovered: false })
                }
              }}
            >
              {(this.state.showLinks === undefined || this.state.showLinks === true) && (
                <CaretLeftOutlined
                  className={`left ${this.state.isHovered ? 'left-hovered' : ''}`}
                  onClick={() => {
                    if (this.state.showLinks == undefined) {
                      this.setState({ showLinks: false })
                    } else {
                      this.setState({ showLinks: undefined })
                    }
                  }}
                />
              )}
              {(this.state.showLinks === undefined || this.state.showLinks === false) && (
                <CaretRightOutlined
                  className={`right ${this.state.isHovered ? 'right-hovered' : ''}`}
                  onClick={() => {
                    if (this.state.showLinks == undefined) {
                      this.setState({ showLinks: true })
                    } else {
                      this.setState({ showLinks: undefined })
                    }
                    // 如果容器下有固定到右侧的弹窗容器，才进行操作
                    const hasPinModal = domUtils.closest(this.navMain.current as HTMLElement, `.main-page-content.${this.pageContentId}`)?.querySelector('.dialog-pin-right.dialog-fix-right');
                    if (hasPinModal) {
                      const targetEvent = this.state.showLeft == undefined ? ResizeEvent.RESET_MAIN_PAGE_WIDTH + this.pageContentId : ResizeEvent.STOP_RESIZE_AFTER_PIN + this.pageContentId;
                      document.body.dispatchEvent(new Event(targetEvent));
                    }
                  }}
                />
              )}
            </div>
          </div>
        )} */}
        {/* style={{ display: this.state.showLinks == undefined ? undefined : this.state.showLinks ? 'none' : 'block' }} */}
        <div className={cx('Tabs-content', contentClassName)} ref={this.tabContentRef} >
          {filteredChildren.map((child, index) => {
            return this.renderTab(child, index);
          })}
        </div>
      </div >
    );
  }
}

const ThemedTabs = themeable(
  uncontrollable(Tabs, {
    activeKey: 'onSelect'
  })
);

export default ThemedTabs as typeof ThemedTabs & {
  Tab: typeof Tab;
};
