import { useDebounceFn } from 'ahooks';
import classNames from 'classnames';
import { useEffect, useRef, useState } from 'react';
import styles from './index.less';

interface TabsProps {
  onChange?: (type: string) => void;
  items?: TabItem[];
  defaultValue?: string;
  style?: React.CSSProperties; //父元素属性
  itemStyle?: React.CSSProperties; //每个item的属性
  itemkey?: string; //指定 key 值
}
/**
 * @description: tabs组件
 */
export interface TabItem {
  label: string | React.ReactNode;
  key?: string;
  icon?: string;
  [key: string]: any;
}
const Tabs = (props: TabsProps) => {
  const { onChange, items, defaultValue, style, itemStyle, itemkey } = props;
  const [active, setActive] = useState(defaultValue);
  const initStatus = useRef(true);

  useEffect(() => {
    if (initStatus.current) {
      if (items && items.length > 0) {
        let type = itemkey ? items[0][itemkey] : items[0].key;
        setActive(defaultValue || type);
        initStatus.current = false;
      }
    }
  }, [items]);

  const handleChange = async (type: string) => {
    if(onChange) {
      onChange(type)
    }
  };

  //函数防抖
  const { run } = useDebounceFn(
    (type: string) => {
      handleChange(type);
    },
    {
      wait: 500,
      leading: true,
    },
  );

  return (
    <div
      className={styles.tabWrap}
      style={{ ...style, borderRadius: itemStyle?.borderRadius || 20 }}
    >
      {items?.map((v, index) => (
        <div
          key={'tabs_' + index}
          style={itemStyle}
          className={classNames({
            [styles.active]: active === v[itemkey as any] || active === v.key,
          })}
          onClick={(e) => {
            e.stopPropagation();
            let type = itemkey ? v[itemkey] : v.key;
            setActive(type);
            run(type);
          }}
        >
          {v.icon && (
            <img
              src={v.icon}
              alt=""
              style={{ marginRight: 5, width: 24, height: 24 }}
            />
          )}
          <span>{v.label}</span>
        </div>
      ))}
    </div>
  );
};

export default Tabs;
