import { useCallback, useMemo, useState } from 'react';

/**
 * 选择、全选操作
 * @param list - 需要进行选择的列表
 * @return  [选中的项, 设置选中的方法, 是否全选, 是否部分选中, 全选方法，是否单个选中，选中单个方法]
 */
export const useCheck = <T>(list: T[]) => {
  const [selected, setSelected] = useState<T[]>([]);

  const checked = useMemo(() => {
    return selected.length === list.length && selected.length > 0;
  }, [selected, list]);

  const indeterminate = useMemo(() => {
    return selected.length > 0 && selected.length < list.length;
  }, [selected, list]);

  const checkAll = useCallback(() => {
    setSelected(checked ? [] : list);
  }, [list, checked]);

  const isSingleChecked = useCallback((item: T) => selected.includes(item), [selected]);

  const checkSingle = useCallback(
    (item: T) => {
      setSelected((prev) => {
        if (isSingleChecked(item)) {
          return prev.filter((i) => i !== item);
        } else {
          return [...prev, item];
        }
      });
    },
    [isSingleChecked],
  );

  return [
    selected,
    setSelected,
    checked,
    indeterminate,
    checkAll,
    isSingleChecked,
    checkSingle,
  ] as const;
};
