import { Checkbox, CheckboxOptionType } from "antd";
import { CheckboxGroupProps } from "antd/lib/checkbox";
import { isNumber, isObject, merge } from "lodash";
import { FC, useEffect, useState } from "react";

export interface DageCheckboxGroupProps extends CheckboxGroupProps {
  /** 最大选择个数 */
  max?: number;
}

export const DageCheckboxGroup: FC<DageCheckboxGroupProps> = ({
  options,
  max,
  ...rest
}) => {
  const [_options, _setOptions] = useState<CheckboxOptionType[]>([]);

  useEffect(() => {
    _setOptions(
      merge(
        [],
        options?.map((i) => {
          if (isObject(i)) return i;
          return {
            label: i,
            value: i,
          };
        }),
        _options
      )
    );
  }, [options]);

  useEffect(() => {
    const { value } = rest;

    if (!value || !isNumber(max)) return;

    _setOptions((val) => {
      return val.map((i) => ({
        ...i,
        disabled: value.length >= max ? !value.includes(i.value) : false,
      }));
    });
  }, [rest.value, max]);

  return <Checkbox.Group options={_options} {...rest} />;
};
