import React, { useEffect, useState } from 'react';

function Tab(props: ITab) {
  const { type, options = [], selected = [], clickFilter } = props;
  const [newCurrentList, setNewCurrentList] = useState([]); //处理选中的数据

  useEffect(() => {
    setNewCurrentList(selected);
  }, []);

  const _click = (value) => {
    let _newCurrentList = [];
    if (value === '全部') {
      _newCurrentList = ['全部'];
      setNewCurrentList(_newCurrentList);
    } else {
        //如果有全部的 当前选中数据 就只有当前的点击的
      if (newCurrentList.indexOf('全部') > -1) {
        _newCurrentList = [value];
        setNewCurrentList(_newCurrentList);
      } else {
        _newCurrentList = [...newCurrentList];
        if (_newCurrentList.indexOf(value) === -1) {
          _newCurrentList.push(value);
          setNewCurrentList(_newCurrentList);
        } else {
          let index = _newCurrentList.indexOf(value);
          _newCurrentList.splice(index, 1);
          setNewCurrentList(_newCurrentList);
        }
      }
    }
    clickFilter({ type: type, selected: _newCurrentList });
  };

  return (
    <div className="zl-large-screen-component-filtr-item-wrap">
      <span>{type} :</span>
      {options?.length > 0 &&
        options?.map((item,index) => {
          return (
            <span
              key={index}
              className={`zl-large-screen-component-filtr-item ${
                newCurrentList.includes(item)
                  ? 'zl-large-screen-component-filtr-item-active'
                  : ''
              }`}
              onClick={() => _click(item)}
            >
              {item}
            </span>
          );
        })}
    </div>
  );
}
export default Tab;

export interface ITab {
  type?: string;
  selected?: string[];
  options?: string[];
  clickFilter?: Function;
}
