import { Checkbox, Divider, Space } from 'antd';
import _ from 'lodash';
import moment from 'moment';
import { useContext, useEffect, useState } from 'react';
import CustomBatchDatePicker from '../CustomDatePicker/CustomBatchDatePicker';
import CustomBatchDay from '../CustomDatePicker/CustomBatchDay';
import CustomLabel from '../CustomDatePicker/CustomLabel';
import PermissionParentShow from '../PermissionParentShow';
import { validate, validateDay } from '../utils';
import { AppDetailContext, useBatchSetExpires } from '../utils/hooks';
import './index.less';

export interface CustomCheckboxGroupProps {
  value?: any;
  isHaveDate?: boolean;
  isHaveDay?: boolean;
  isHaveCheckBox?: boolean;
  isAllowApply?: boolean;
  disabled?: boolean;
  onChange?: (val: any) => void;
  customRender?: (data: any) => React.ReactNode;
  oldData?: any[];
  options?: any[];
  max?: number;
  checkInterceptor?: (id: string, checked: boolean) => Promise<boolean>;
  isOtherUser?: boolean;
}

const CustomCheckboxGroup = (props: CustomCheckboxGroupProps) => {
  const {
    value,
    onChange,
    isHaveDate,
    isHaveDay,
    isHaveCheckBox,
    customRender,
    disabled = false,
    isAllowApply = false,
    oldData,
    options,
    max,
    checkInterceptor,
    isOtherUser,
  } = props;

  const [selectIdMap, setSelectIdMap] = useState<Record<string, any>>({});
  const { defaultExpirationTime } = useContext(AppDetailContext);

  const { applyAll, applyNew } = useBatchSetExpires({
    selectIdMap,
    onChange,
    value,
    oldData,
  });

  const onFinished = async (id: string, val: boolean) => {
    if (_.isFunction(checkInterceptor)) {
      const intercept = await checkInterceptor(id, val);
      if (intercept) return;
    }
    const tempSelectIdMap = { ...selectIdMap };
    if (val) {
      tempSelectIdMap[id] = {
        id: id,
        expiredAt: isHaveDate
          ? defaultExpirationTime
            ? defaultExpirationTime * 1000 + moment().valueOf()
            : defaultExpirationTime
          : isHaveDay
          ? defaultExpirationTime
            ? defaultExpirationTime / 60 / 60 / 24
            : defaultExpirationTime
          : undefined,
      };
    } else {
      delete tempSelectIdMap[id];
    }
    if (isHaveDay) {
      validateDay(isHaveDay, tempSelectIdMap, onChange);
    } else {
      validate(isHaveDate, tempSelectIdMap, onChange);
    }
  };

  const renderCheckbox = (d: any) => {
    const {
      id: nodeId,
      uniqueKey,
      key,
      name,
      isAllowApply: allowApply,
      disabled: nodeDisabled,
    } = d;
    const id = String(nodeId);
    const keyText = uniqueKey || key;
    const title = `${name}${keyText ? `（${keyText}）` : ''}`;
    const currDisabled = max
      ? _.find(value?.data, { id })
        ? false
        : value?.data?.length >= max
      : false;
    return (
      <Checkbox
        key={id}
        style={{ marginLeft: 0, marginRight: 8, paddingBottom: 4 }}
        disabled={disabled || nodeDisabled || currDisabled}
        value={id}
        checked={!!selectIdMap[id]}
        onChange={(e) => onFinished(id, e.target.checked)}
      >
        <CustomLabel
          onChange={onChange}
          setSelectIdMap={setSelectIdMap}
          label={
            disabled ? <>{title}</> : <PermissionParentShow data={d}>{title}</PermissionParentShow>
          }
          disabled={(isAllowApply && allowApply === 0) || nodeDisabled || currDisabled}
          isHaveDate={isHaveDate}
          isHaveDay={isHaveDay}
          data={value?.data}
          selectId={nodeId}
          isHaveCheckBox={isHaveCheckBox}
          isBind={oldData?.some((item) => item.id === nodeId) && !isOtherUser}
        />

        {_.isFunction(customRender) && (
          <div
            style={{ display: 'contents' }}
            onClick={(e) => {
              e.stopPropagation();
              e.preventDefault();
            }}
          >
            &nbsp;&nbsp;
            {customRender(d)}
          </div>
        )}
      </Checkbox>
    );
  };

  useEffect(() => {
    if (value?.data?.length > 0) {
      setSelectIdMap(
        _.keyBy(
          value?.data?.map((item) => ({
            ...item,
            expiredAt: isHaveDate || isHaveDay ? item.expiredAt : undefined,
          })) || [],
          'id',
        ),
      );
    } else {
      setSelectIdMap([]);
    }
  }, [value, isHaveDate, isHaveDay]);

  return (
    <Space direction={'vertical'} style={{ width: '100%' }}>
      {Boolean(isHaveDate) && (
        <div style={{ paddingBottom: 4 }}>
          <CustomBatchDatePicker applyAll={applyAll} applyNew={applyNew} />
        </div>
      )}
      {Boolean(isHaveDay) && (
        <div style={{ paddingBottom: 4 }}>
          <CustomBatchDay applyAll={applyNew} />
        </div>
      )}

      {Boolean(isHaveDate || isHaveDay) && <Divider style={{ marginTop: 0, marginBottom: 0 }} />}

      {options?.map((d) => renderCheckbox(d))}
    </Space>
  );
};

export default CustomCheckboxGroup;
