import React, { useState, useMemo, useEffect } from 'react';
import { Prompt } from 'umi';
import classNames from '@pansy/classnames';
import { groupBy } from 'lodash';
import { appTypeToCategory } from '../../config';
import { APP_TYPE, Category } from '../../types';
import { Button, Row, Col, Spin, message, Affix } from 'antd';
import { usePermission } from '@sensoro/core';
import useNoticeRules from '../../hooks/notice-rules/use-notice-rules';
import {
  EventRuleItem,
  NoticeRuleItem,
  TemplatePackageType,
} from '../../services/notice-rules/type';
import NoticeRulesList from '../notice-rules-list';
import IconFont from '@sensoro/library/lib/components/icon-font';
import styles from './index.less';

const formatEventRules = (eventRules: EventRuleItem[]) => {
  const data = eventRules?.map((item: EventRuleItem) => {
    return { ...item, label: item.eventName, value: item.eventType };
  });
  return groupBy(data, 'groupName');
};

const formatNoticeRule = (
  noticeRules: NoticeRuleItem[],
  category: Category,
) => {
  if (category === Category.MAINTENANCE) {
    // 维保 要增加
    return noticeRules?.map(item => {
      return { ...item, templatePackageType: TemplatePackageType.MAINTENANCE };
    });
  } else if (
    category === Category.CAMERA_CAPTURE_GB_THERMAL_CAMERA ||
    category === Category.JIN_SHU_JU
  ) {
    return noticeRules?.map(item => {
      return { ...item, templatePackageType: TemplatePackageType.TASK_ALARM };
    });
  } else {
    return noticeRules;
  }
};

export interface NoticeRulesProps {
  appType: APP_TYPE;
  className?: string;
  editable?: boolean;
  onChange?: (value: boolean) => void;
}

const NoticeRules: React.FC<NoticeRulesProps> = props => {
  const { appType, className, editable = true, onChange } = props;
  const [unavailable, setUnavailable] = useState(false);
  const [noticeData, setNoticeData] = useState<NoticeRuleItem[]>([]);
  const [eventData, setEventData] = useState<EventRuleItem[]>([]);
  const [change, setChange] = useState(false);
  const {
    loading,
    noticeRules,
    eventRules,
    updateLoading,
    updateRequest,
  } = useNoticeRules(appType);

  const category = appTypeToCategory[appType];

  // 动态更新
  useEffect(() => {
    // 数据预处理 formatNoticeRule
    noticeRules && setNoticeData(formatNoticeRule(noticeRules || [], category));
  }, [noticeRules]);

  // 动态更新
  useEffect(() => {
    setEventData(eventRules || []);
  }, [eventRules]);

  const handleSubmit = () => {
    updateRequest?.run({
      noticeRules: noticeData,
      eventRules: eventData,
    });
    setChange(false);
    message.success('提交成功');
  };
  const handleEventRule = (value: EventRuleItem) => {
    const newValues = eventData?.map(item => {
      if (item.eventType === value.eventType) {
        return { ...value };
      } else {
        return item;
      }
    });
    // 数据修改
    setChange(true);
    onChange?.(true);
    setEventData(newValues || []);
  };
  const handleNoticeRule = (value: NoticeRuleItem[]) => {
    setNoticeData(value);
    // 数据修改
    setChange(true);
  };

  return (
    <div className={classNames(styles.wrapper, className)}>
      <NoticeRulesList
        className={styles.paddingWrapper}
        category={category}
        eventData={eventData}
        noticeData={noticeData}
        editable={editable}
        onEventRule={handleEventRule}
        onNoticeRule={handleNoticeRule}
        onUnavailable={(value: boolean) => setUnavailable(value)}
        loading={loading}
      />
      <Affix offsetBottom={0}>
        <div className={styles.footerWrapper}>
          <div className={styles.footerTitle}></div>
          <div className={styles.footerExtra}>
            {change && (
              <span className={styles.tips}>
                <IconFont
                  type="icon-attention"
                  style={{ color: '#E57022', marginRight: 8 }}
                />
                预警通知规则已经修改，请注意提交
              </span>
            )}
            <Button
              disabled={!editable || !change || unavailable || updateLoading}
              type="primary"
              onClick={handleSubmit}
            >
              提交
            </Button>
          </div>
        </div>
      </Affix>
      <Prompt
        when={change}
        message={(a, b) => {
          return '当前页面还有未保存的修改，是否离开？';
        }}
      />
    </div>
  );
};
export default NoticeRules;
