import React, { useMemo, useEffect } from 'react';
import { Switch, Form, Checkbox } from 'antd';
import DashedCard from '@/components/dashed-card';
import { EventRuleItem, NoticeTypes } from '../../services/notice-rules/type';
import { NOTICE_TYPES_ARRAY1 } from '../../config';
import styles from './index.less';

const { Item } = Form;
const { Group } = Checkbox;
export interface NoticeCardProps {
  disabled?: boolean;
  list?: EventRuleItem[];
  data?: EventRuleItem;
  height?: number;
  width?: number;
  onChange?: (value: EventRuleItem) => void;
  handleUnavailable?: (value: boolean) => void;
}
const NoticeCard: React.FC<NoticeCardProps> = (props) => {
  const { list, data, disabled = false, onChange, handleUnavailable, ...rest } = props;

  const [form] = Form.useForm();

  useEffect(() => {
    form.setFieldsValue({ noticeTypes: data?.noticeTypes });
  }, [data]);

  const triggerChange = (value: EventRuleItem) => {
    onChange && onChange(value);
  };

  const checkBoxDisabled = useMemo(() => {
    return disabled || data?.pause;
  }, [disabled, data?.pause]);

  const handleChange = (pause: boolean) => {
    triggerChange({ ...data, pause: !pause });
  };

  const handleValuesChange = ({ noticeTypes }: { noticeTypes: NoticeTypes[] }) => {
    if (noticeTypes && noticeTypes?.length) {
      handleUnavailable && handleUnavailable(false);
      triggerChange({ ...data, noticeTypes });
    } else {
      handleUnavailable && handleUnavailable(true);
    }
  };

  const newNoticeTypesArray = useMemo(() => {
    if (Array.isArray(data?.disableNoticeTypes) && data?.disableNoticeTypes?.length) {
      return NOTICE_TYPES_ARRAY1?.map((item) => ({
        ...item,
        disabled: data?.disableNoticeTypes?.includes(item.value)
      }));
    } else {
      return NOTICE_TYPES_ARRAY1;
    }
  }, [data?.disableNoticeTypes]);

  return (
    <DashedCard
      leftHeader={data?.eventName || '标题'}
      rightHeader={
        <Switch
          size="small"
          disabled={disabled || data?.disablePause}
          checked={!data?.pause}
          onChange={handleChange}
        />
      }
      {...rest}
    >
      <Form
        form={form}
        size="small"
        onValuesChange={handleValuesChange}
        className={styles.formWrapper}
      >
        <Item
          name="noticeTypes"
          rules={[
            {
              validator: (rule, value) => {
                if (!data?.pause && value.length === 0) {
                  return Promise.reject('至少勾选一个通知方式');
                }
                return Promise.resolve();
              }
            }
          ]}
        >
          <Group disabled={checkBoxDisabled} options={newNoticeTypesArray} />
        </Item>
      </Form>
    </DashedCard>
  );
};
NoticeCard.defaultProps = {
  width: 260,
  height: 114
};
export default NoticeCard;
