//TabSwitch组件
import classNames from 'classnames';
import React, { CSSProperties, useMemo } from 'react';
import styles from './index.less';
export interface OptionsDto {
  icon?: string; //配置图标
  label: string;
  value: string | number;
  count?: string | number | undefined;
}
interface selectProps {
  options: OptionsDto[] | any; //数据源
  defaultId?: string | number; //默认选中项
  style?: CSSProperties;
  onSelect?: (selectId: string | number) => void; //选择项
  isCount?: boolean; //是否计数
  labelWidth?: string; //支持自定义宽度
  activeBg?: string; //激活颜色
  fieldNames?: OptionsDto; //自定义字段
}

const TabSwitch: React.FC<selectProps> = (props) => {
  const {
    options,
    style,
    defaultId = 1,
    isCount,
    labelWidth,
    activeBg = '#2B85FF',
    onSelect,
    fieldNames = {
      icon: 'icon',
      label: 'label',
      value: 'value',
      count: 'count',
    },
  } = props;

  const [selectedId, setSelectedId] = React.useState<
    number | string | undefined
  >(defaultId);

  //点击Tab
  const handleTab = (row: any) => {
    setSelectedId(row.value);
    onSelect && onSelect(row.value);
  };

  //数据源
  let data = useMemo(() => {
    return options?.map((it: any) => ({
      icon: it[fieldNames.icon as string],
      label: it[fieldNames.label],
      value: it[fieldNames.value],
      count: it[fieldNames.count as string],
    }));
  }, [options]);
  return (
    <div
      className={classNames(styles.tab_switch, data?.length < 2 && styles.one)}
      style={style}
    >
      {data?.map((item: any) => (
        <span
          style={{ width: labelWidth, '--color': activeBg } as CSSProperties}
          className={item.value == selectedId ? styles.active : ''}
          onClick={() => handleTab(item)}
          key={item.value}
        >
          {item.icon && (
            <img src={require(`@/assets/images/${item.icon}.png`)} />
          )}
          {item.label} {isCount && '· ' + item.count}
        </span>
      ))}
    </div>
  );
};

export default TabSwitch;
