import React, { useMemo, useState, useEffect, useCallback } from 'react';
import { Button } from 'antd';
import { useModal } from '@pansy/hooks';
import { get, concat, keyBy } from 'lodash';
import IconFont from '@sensoro/library/lib/components/icon-font';
import {
  MULTI_LEVEL_ARRAY,
  MULTI_LEVEL_MAP,
  CONDITIONS_MAP,
  RANGES_MAP,
  NOTICE_TYPES_MAP,
  getInitialValueRangesByCategory,
  getInitialValueConditionsByCategory,
} from '../../config';
import { Timeline, NoField } from '@sensoro/sensoro-design';
import styles from './index.less';
import {
  NoticeRuleItem,
  MultiLevel,
  Ranges,
  NewNoticeRuleItem,
  Contact,
  Conditions,
  NoticeTypes,
} from '../../services/notice-rules/type';
import LevelModal from '../level-modal';
import { confirm } from '../../utils/confirm';
import { Category } from '../../types';

const defaultValue: NewNoticeRuleItem = {
  cascade: true,
  conditions: [Conditions.DEVICE_NOT_RECOVERY, Conditions.EVENT_NOT_ON_PROCESS],
  ranges: [Ranges.MERCHANT_CONTACTS],
  noticeTypes: [NoticeTypes.APP, NoticeTypes.SMS, NoticeTypes.VOICE],
};
const isShow = (data: NoticeRuleItem) => {
  if (get(data, 'conditions', []).length === 0) {
    return false;
  }
  return true;
};
export interface NoticeTypeViewProps {
  type: NoticeTypes;
}
const NoticeTypeView: React.FC<NoticeTypeViewProps> = props => {
  const { type } = props;
  const { icon, label } = NOTICE_TYPES_MAP[type];
  return (
    <span className={styles.noticeTypeWrapper}>
      <IconFont type={icon} style={{ color: '#8c8c8c' }} />
      <span className={styles.noticeTypeLabel}>{label}</span>
    </span>
  );
};

const formatContacts = (data: Contact[]) => {
  return data
    ?.map(item => {
      const { name, position, contacts } = item;
      const positionText = position ? `-${position}` : '';
      const contactText = contacts ? `(${contacts})` : '';
      return `${name}${positionText} ${contactText}`;
    })
    .join('，');
};

export interface ListItem {
  title?: string;
  multilevel?: MultiLevel;
  content?: NoticeRuleItem;
  edit?: boolean;
  remove?: boolean;
  create?: boolean;
  disabledCreate?: boolean;
}
const formatList = (data: NoticeRuleItem[]): ListItem[] => {
  let list: ListItem[] = [];
  const length = data.length;
  list = MULTI_LEVEL_ARRAY.map((item, index) => {
    // 有数据 存在 就可以编辑
    const edit = data[index] ? true : false;
    //  data 长度  倒数第一条展示删除
    const remove = index > 0 && index + 1 === length ? true : false;
    // data 长度 + 1 条可以 启用
    const create = index > 0 && index === length ? true : false;
    const disabledCreate = index > 0 && index > length ? true : false;
    return {
      title: item.label,
      multilevel: item.value as MultiLevel,
      content: data[index],
      edit,
      remove,
      create,
      disabledCreate,
    };
  });
  return list;
};

const handleTimeText = (
  time: number,
  cascade: boolean,
  multilevel: MultiLevel,
) => {
  let text: string = '';

  if (multilevel === 1) {
    text = `预警发生后 ${Number(time)} 秒`;
  } else {
    if (cascade) {
      text = `预警发生后 ${Number(time) /
        60} 分钟或上一级电话拨打失败时立刻通知`;
    } else {
      text = `预警发生后 ${Number(time) / 60} 分钟`;
    }
  }

  return text;
};
export interface LevelNotificationProps {
  category: Category;
  data?: NoticeRuleItem[];
  editable?: boolean;
  onChange?: (value: NewNoticeRuleItem[]) => void;
}
const LevelNotification: React.FC<LevelNotificationProps> = props => {
  const { data, onChange, editable = false, category } = props;
  const {
    visible,
    initValue,
    openModal,
    closeModal,
  } = useModal<NewNoticeRuleItem | null>();

  const [list, setList] = useState(() => {
    return formatList(data);
  });

  useEffect(() => {
    data && setList(formatList(data));
  }, [data]);

  const timeList = useMemo(() => {
    return keyBy(data, 'multilevel');
  }, [data]);

  const handleRemove = useCallback(
    (multilevel: MultiLevel) => {
      const title = MULTI_LEVEL_MAP[multilevel]['label'];
      confirm({
        title: `删除${title}`,
        content: '确认删除该预警',
        onOk: () => {
          const newData = data?.filter(item => item.multilevel !== multilevel);
          onChange && onChange(newData || []);
        },
      });
    },
    [data],
  );

  const renderContent = (item: NoticeRuleItem) => {
    return (
      <>
        {item ? (
          <div className={styles.contentWrapper}>
            <div className={styles.margin}>
              通知时间：
              {Number(item.time) === 0
                ? '立即'
                : handleTimeText(
                    item?.time || 0,
                    item?.cascade || false,
                    item?.multilevel || 1,
                  )}
            </div>
            {isShow(item) && (
              <div className={styles.margin}>
                通知条件：
                <NoField>
                  {item.conditions
                    ?.map(i => get(CONDITIONS_MAP, `${i}.label`))
                    .join('，')}
                </NoField>
              </div>
            )}

            <div className={styles.rangesWrapper}>
              <div style={{ whiteSpace: 'nowrap' }}>通知范围：</div>
              <div>
                <div>
                  {item.ranges
                    ?.filter((item: Ranges) => item !== Ranges.CUSTOM_CONTACTS)
                    .map(i => get(RANGES_MAP, `${i}.label`))
                    .join(' ，')}
                </div>
                <div className={styles.contactsWrapper}>
                  {item?.ranges?.includes(Ranges.CUSTOM_CONTACTS) &&
                    formatContacts(item?.contacts || [])}
                </div>
              </div>
            </div>
            <div>
              通知方式：
              {item.noticeTypes?.sort()?.map(i => (
                <NoticeTypeView key={i} type={i} />
              ))}
            </div>
          </div>
        ) : null}
      </>
    );
  };
  const handleEditOrCreate = (
    item: NoticeRuleItem,
    isCreate: boolean = false,
  ) => {
    // @ts-ignore
    const contactsSwitch = get(item, 'ranges', []).includes(
      Ranges.CUSTOM_CONTACTS,
    );
    // 如果是启用 规则填充通知时间默认值
    if (isCreate) {
      let time = 0;
      if (
        Number(item.multilevel) - 1 !== 1 &&
        get(timeList, `${String(Number(item.multilevel) - 1)}.time`, 0) >= 6000
      ) {
        time = Number(
          get(timeList, `${String(Number(item.multilevel) - 1)}.time`, 0),
        );
      } else if (Number(item.multilevel) - 1 !== 1) {
        time =
          Number(
            get(timeList, `${String(Number(item.multilevel) - 1)}.time`, 0),
          ) + 300;
      } else {
        time = 300;
      }

      // 不同分类默认值不同
      item = {
        ...defaultValue,
        ...item,
        time,
        ranges: getInitialValueRangesByCategory(category),
        conditions: getInitialValueConditionsByCategory(category),
      };
    }
    openModal({
      ...item,
      contactsSwitch,
      ranges: get(item, 'ranges', []).filter(
        (item: Ranges) => item !== Ranges.CUSTOM_CONTACTS,
      ),
      contacts:
        get(item, 'contacts', []).length > 0
          ? get(item, 'contacts', [])
          : [{ name: '', contacts: '', position: '' }],
    });
  };
  const handleOk = (item: NewNoticeRuleItem) => {
    let newData: NoticeRuleItem[] = [];

    if (data?.map(i => i.multilevel).includes(item.multilevel)) {
      newData = data?.map(i => {
        if (i.multilevel === item.multilevel) {
          return { ...i, ...item };
        } else {
          return i;
        }
      });
    } else {
      newData = concat(data, [item]);
    }

    onChange && onChange(newData);
    closeModal();
  };
  const renderTitle = (item: ListItem) => {
    const {
      title,
      content,
      multilevel,
      edit,
      remove,
      create,
      disabledCreate,
    } = item;
    return (
      <>
        <div className={styles.titleWrapper}>
          <div className={styles.title}>{title}</div>
          <div className={styles.extra}>
            {editable && edit && (
              <Button
                type="link"
                onClick={() => handleEditOrCreate(content, false)}
              >
                编辑
              </Button>
            )}
            {editable && remove && (
              <Button type="link" onClick={() => handleRemove(multilevel || 1)}>
                删除
              </Button>
            )}
            {editable && create && (
              <Button
                type="link"
                onClick={() => handleEditOrCreate({ multilevel }, true)}
              >
                启用
              </Button>
            )}
            {disabledCreate && (
              <Button type="link" disabled={true}>
                启用
              </Button>
            )}
          </div>
        </div>
        {content && renderContent(content)}
      </>
    );
  };
  return (
    <div className={styles.wrapper}>
      <Timeline>
        {list.map((item: ListItem) => (
          <Timeline.Item
            color="rgba(242,165,22)"
            fill="rgba(242,165,22,.15)"
            key={item.multilevel}
            title={renderTitle(item)}
          ></Timeline.Item>
        ))}
      </Timeline>
      <LevelModal
        category={category}
        data={initValue}
        timeList={timeList}
        visible={visible}
        onCancel={closeModal}
        onChange={handleOk}
      />
    </div>
  );
};

LevelNotification.defaultProps = {
  data: [],
};

export default LevelNotification;
