import React, { useEffect, useState, useMemo } from 'react';
import { Form, Select, Checkbox, Input, Row, Col, Switch, Tooltip } from 'antd';
import { get, has } from 'lodash';
import {
  PlusCircleOutlined,
  MinusCircleOutlined,
  QuestionCircleOutlined,
} from '@ant-design/icons';
import FormModal, { FormModalProps } from '../form-modal';
import {
  CONDITIONS,
  RANGES,
  NOTICE_TYPES_ARRAY,
  getRangesByCategory,
} from '../../config';
import {
  NoticeTypes,
  Ranges,
  Conditions,
  NewNoticeRuleItem,
  NoticeRuleItem,
  MultiLevel,
} from '../../services/notice-rules/type';
import styles from './index.less';
import { telephoneRegexp } from '@/utils/regexp';
import { checkNickname } from '@/utils/utils';
import TransformTime from '../transform-time';
import { Category } from '../../types';
import useRoleList from './hooks/use-role-list';
import TransformField from '../transform-field';

const getOptimalValue = (min: number, max: number, value: number): number => {
  if (value >= min && value <= max) {
    if (value - min > max - value) {
      return max;
    } else {
      return min;
    }
  }
  if (value > max) {
    return max;
  }
  if (value < min) {
    return min;
  }
  return min;
};

const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 18 },
};
export interface LevelModalProps extends FormModalProps {
  category?: Category;
  timeList?: any;
  data: NewNoticeRuleItem | NoticeRuleItem;
  onChange?: (value: NewNoticeRuleItem | NoticeRuleItem) => void;
}
const { Item } = Form;
const LevelModal: React.FC<LevelModalProps> = props => {
  const {
    timeList,
    data = { multilevel: 1 },
    onCancel,
    visible,
    onChange,
    category = Category.GROUP_DEFENSE,
    ...rest
  } = props;
  const [rangesRequired, setRangesRequired] = useState(() => {
    return !get(data, 'contactsSwitch', false);
  });
  const [timeValue, setTimeValue] = useState(0);
  const [second, setSecond] = useState(0);
  const roleListResult = useRoleList();

  const [form] = Form.useForm();

  useEffect(() => {
    setRangesRequired(!get(data, 'contactsSwitch', false));
  }, [get(data, 'contactsSwitch', false)]);

  useEffect(() => {
    form.validateFields(['ranges']);
  }, [rangesRequired]);
  useEffect(() => {
    form.validateFields(['time']);
  }, [timeValue]);
  useEffect(() => {
    form.validateFields(['time']);
  }, [second]);

  useEffect(() => {
    form.resetFields();
    visible && form.setFieldsValue(data);
  }, [data, visible]);

  // 失去焦点填充数据
  const handleBlur = (multilevel: MultiLevel) => {
    if (multilevel > 1) {
      // 填充值
      timeValue && form.setFieldsValue({ time: timeValue });
      // 清除值
      setTimeValue(0);
    } else {
      // 填充值
      second && form.setFieldsValue({ time: second });
      // 清除值
      setSecond(0);
    }
  };
  //  渲染通知条件
  const renderConditions = useMemo(() => {
    if (
      [
        Category.CAMERA_CAPTURE_GB_THERMAL_CAMERA,
        Category.ILLEGAL_CONSTRUCTION,
        Category.WEATHER_DISASTER,
        Category.ILLEGAL_WORK_ON_RIVER,
        Category.JIN_SHU_JU,
      ].includes(category)
    ) {
      return (
        <Item label="通知条件" style={{ marginBottom: 0 }} required={false}>
          <Item
            name="conditions"
            // rules={[
            //   {
            //     required: true,
            //     message: '必选一个通知条件',
            //   },
            // ]}
          >
            <Checkbox.Group
              options={CONDITIONS.filter(
                item => item.value === Conditions.EVENT_NOT_ON_PROCESS,
              )}
            ></Checkbox.Group>
          </Item>
        </Item>
      );
    } else {
      if (data.multilevel === 1) {
        return (
          <Item
            label="通知条件"
            style={{ marginBottom: 0 }}
            required={data.multilevel === 1 ? false : true}
          >
            <Item name="conditions">
              <Checkbox.Group
                options={CONDITIONS.filter(
                  item => item.value == Conditions.DEVICE_NOT_RECOVERY,
                )}
              ></Checkbox.Group>
            </Item>
          </Item>
        );
      } else {
        return (
          <Item
            label="通知条件"
            style={{ marginBottom: 0 }}
            required={data.multilevel === 1 ? false : true}
          >
            <Item
              name="conditions"
              rules={[
                {
                  required: true,
                  message: '必选一个通知条件',
                },
              ]}
            >
              <Checkbox.Group
                options={CONDITIONS.filter(
                  item => item.value !== Conditions.DEVICE_ALARM_CREATE,
                )}
              ></Checkbox.Group>
            </Item>
          </Item>
        );
      }
    }
  }, [data, category, Conditions, CONDITIONS]);

  return (
    <div>
      <FormModal
        width={588}
        visible={visible}
        bodyStyle={{ paddingBottom: '0px' }}
        okText="确认"
        cancelText="取消"
        destroyOnClose={true}
        maskClosable={false}
        onCancel={onCancel}
        forceRender
        form={form}
        {...rest}
        title="编辑通知规则"
        formProps={{
          colon: false,
          // size: 'small',
          onValuesChange: changeValue => {
            if (has(changeValue, 'contactsSwitch')) {
              setRangesRequired(!changeValue?.contactsSwitch);
            }
          },
          ...layout,
        }}
        onSubmit={form => {
          form.validateFields().then((values: NewNoticeRuleItem) => {
            // 自定义联系人 加入
            if (values.contactsSwitch) {
              values?.ranges?.push(Ranges.CUSTOM_CONTACTS);
            } else {
              // 空数组
              values.contacts = [];
            }
            values.noticeTypes = values.noticeTypes?.sort();

            delete values.contactsSwitch;

            onChange && onChange({ ...data, ...values });
          });
        }}
      >
        <div className={styles.formWrapper} id="form-wrapper">
          <Item
            label="通知时间"
            style={{ marginBottom: data.multilevel === 1 ? 24 : 0 }}
            required={data.multilevel === 1 ? false : true}
          >
            {data.multilevel === 1 ? (
              <div className={styles.timeWrapper}>
                <span className={styles.timeDesc}>预警发生后</span>
                <Item
                  name="time"
                  rules={[
                    ({ getFieldValue }) => ({
                      validator(rule, value) {
                        if (value <= 15 && value >= 0) {
                          setSecond(0);
                          return Promise.resolve();
                        }
                        setSecond(getOptimalValue(1, 15, value));
                        return Promise.reject('输入范围 0 - 15 秒');
                      },
                    }),
                  ]}
                  noStyle
                >
                  <Input
                    addonAfter="秒"
                    style={{ width: 86 }}
                    onBlur={() => handleBlur(data?.multilevel || 1)}
                  />
                </Item>
              </div>
            ) : (
              <div className={styles.timeWrapper}>
                <span className={styles.timeDesc}>预警发生后</span>
                <Item
                  name="time"
                  noStyle
                  rules={[
                    {
                      required: true,
                      message: '输入通知时间',
                    },
                    ({ getFieldValue }) => ({
                      validator(rule, value) {
                        const multilevel = data.multilevel;
                        const nextTime = get(
                          timeList,
                          `${String(Number(multilevel) + 1)}.time`,
                        );
                        const prevTime =
                          Number(multilevel) - 1 === 1
                            ? 0
                            : get(
                                timeList,
                                `${String(Number(multilevel) - 1)}.time`,
                              );
                        const max = nextTime ? Number(nextTime) - 60 : 6000;
                        const min = prevTime ? Number(prevTime) + 60 : 60;
                        let maxTime = max;
                        let minTime = min;
                        // 最小值 大于 100分钟 说明没有值可以用
                        if (min > 6000) {
                          setTimeValue(6000);
                          return Promise.reject(
                            `没有可用值，请调整上一级通知时间`,
                          );
                        }

                        if (value) {
                          if (!Number.isInteger(Number(value))) {
                            return Promise.reject('输入整数数值');
                          }

                          if (value >= minTime && value <= maxTime) {
                            // 清理 推荐优化的值， 使用用户填写的值
                            setTimeValue(0);
                            return Promise.resolve();
                          } else {
                            // 设置最优值
                            setTimeValue(
                              getOptimalValue(minTime, maxTime, value),
                            );
                            return Promise.reject(
                              `输入 ${minTime / 60} ~ ${maxTime / 60} 之间的值`,
                            );
                          }
                        } else {
                          // 设置最优值
                          setTimeValue(
                            getOptimalValue(minTime, maxTime, value),
                          );
                          return Promise.reject(
                            `输入 ${minTime / 60} ~ ${maxTime / 60} 之间的值`,
                          );
                        }
                      },
                    }),
                  ]}
                >
                  <TransformTime>
                    <Input
                      addonAfter="分钟"
                      style={{ width: 102 }}
                      onBlur={() => handleBlur(data?.multilevel || 1)}
                    />
                  </TransformTime>
                </Item>
              </div>
            )}
          </Item>
          {data.multilevel !== 1 && (
            <Item
              label=" "
              name="cascade"
              valuePropName="checked"
              style={{ marginBottom: 16 }}
            >
              <Checkbox>上一级电话拨打失败时立刻通知</Checkbox>
            </Item>
          )}

          {renderConditions}

          <Item
            label="通知范围"
            name="ranges"
            style={{ marginBottom: 0 }}
            rules={[{ required: rangesRequired, message: '必选一个通知范围' }]}
          >
            <Select
              options={getRangesByCategory(category)}
              style={{ width: 288 }}
              mode="multiple"
              getPopupContainer={() =>
                document.getElementById('form-wrapper') as HTMLElement
              }
            ></Select>
          </Item>
          <Item noStyle shouldUpdate>
            {({ getFieldValue }) => {
              return getFieldValue('ranges')?.includes(
                Ranges?.MERCHANT_ROLE_CONTACTS,
              ) ? (
                <Item
                  label="项目角色"
                  name="merchantRoleMetadata"
                  style={{ marginBottom: 0, marginTop: 24 }}
                  rules={[{ required: true, message: '必选一个项目角色' }]}
                >
                  <TransformField>
                    <Select
                      placeholder="请选择角色"
                      options={roleListResult?.list}
                      loading={roleListResult?.loading}
                      labelInValue
                      style={{ width: 288 }}
                      mode="multiple"
                      getPopupContainer={() =>
                        document.getElementById('form-wrapper') as HTMLElement
                      }
                    ></Select>
                  </TransformField>
                </Item>
              ) : null;
            }}
          </Item>

          <Item
            label=" "
            name="contactsSwitch"
            valuePropName="checked"
            style={{ marginBottom: rangesRequired ? 16 : 0 }}
          >
            <Checkbox>自定义联系人</Checkbox>
          </Item>

          <Form.Item
            noStyle
            shouldUpdate={(prevValues, curValues) =>
              prevValues.contactsSwitch !== curValues.contactsSwitch
            }
          >
            {({ getFieldValue }) => {
              return getFieldValue('contactsSwitch') ? (
                <Form.List name="contacts">
                  {(fields, { add, remove }) => {
                    return (
                      <div>
                        <Row>
                          <Col
                            offset={4}
                            span={18}
                            className={styles.contactsWrapper}
                          >
                            <span className={styles.labelWrapper}>
                              <span className={styles.requiredStyle}>*</span>
                              &nbsp;姓名
                            </span>
                            <span
                              className={styles.labelWrapper}
                              style={{ marginLeft: -6 }}
                            >
                              职位
                            </span>
                            <span className={styles.labelWrapper}>
                              <span className={styles.requiredStyle}>*</span>
                              &nbsp;电话
                            </span>
                          </Col>
                        </Row>

                        {fields.map((field, index) => (
                          <Item
                            labelCol={{ span: 4 }}
                            label={' '}
                            style={{ marginBottom: 0 }}
                            key={index}
                            initialValue={[{ name: '' }]}
                          >
                            <Item
                              name={[field.name, 'name']}
                              rules={[
                                { required: true, message: '姓名不能为空' },
                                { validator: checkNickname },
                                { max: 20, message: '不能超过20个字符' },
                              ]}
                              style={{
                                display: 'inline-block',
                                width: '112px',
                                paddingRight: '8px',
                              }}
                            >
                              <Input placeholder="请输入" />
                            </Item>

                            <Item
                              name={[field.name, 'position']}
                              rules={[{ max: 20, message: '不能超过20个字符' }]}
                              style={{
                                display: 'inline-block',
                                width: '112px',
                                paddingRight: '8px',
                              }}
                            >
                              <Input placeholder="请输入" />
                            </Item>
                            <Item
                              name={[field.name, 'contacts']}
                              rules={[
                                { required: true, message: '联系电话不能为空' },
                                {
                                  pattern: telephoneRegexp,
                                  message: '手机号格式不正确',
                                },
                              ]}
                              style={{
                                display: 'inline-block',
                                width: '128px',
                                marginRight: '8px',
                              }}
                            >
                              <Input placeholder="请输入" />
                            </Item>

                            <PlusCircleOutlined
                              className={
                                fields.length < 10
                                  ? styles.contactUsable
                                  : styles.contactDisabled
                              }
                              onClick={() => fields.length < 10 && add()}
                            />
                            <MinusCircleOutlined
                              className={
                                fields.length > 1
                                  ? styles.contactUsable
                                  : styles.contactDisabled
                              }
                              onClick={() =>
                                fields.length > 1 && remove(field.name)
                              }
                            />
                          </Item>
                        ))}
                      </div>
                    );
                  }}
                </Form.List>
              ) : null;
            }}
          </Form.Item>
          <Item label="通知方式" style={{ marginBottom: 0 }}>
            <Item
              name="noticeTypes"
              style={{ marginBottom: 0, display: 'inline-block' }}
              rules={[
                {
                  required: true,
                  message: '必选一个通知方式',
                },
              ]}
            >
              <Checkbox.Group options={NOTICE_TYPES_ARRAY}></Checkbox.Group>
            </Item>
            <Item style={{ display: 'inline-block', marginBottom: 0 }}>
              <Item
                name="isForceNotice"
                valuePropName="checked"
                style={{ marginLeft: 22, display: 'inline-block' }}
              >
                <Switch size="small"></Switch>
              </Item>
              <span className={styles.forceWrapper}>
                <span className={styles.forceTitle}>强制通知</span>
                <Tooltip title="开通强制通知时，将覆盖感知事件的通知方式配置">
                  <QuestionCircleOutlined className={styles.iconStyle} />
                </Tooltip>
              </span>
            </Item>
          </Item>
        </div>
      </FormModal>
    </div>
  );
};

export default LevelModal;
