import React, { useState, useEffect, useRef } from 'react';
import { Prompt } from 'umi';
import { history } from '@sensoro/core';
import { Button, Row, Col, Spin, message, Affix } from 'antd';
import { APP_TYPE, Category } from '../../types';
import { appTypeToCategory } from '../../config';
import useNoticeRules from '../../hooks/notice-rules/use-notice-rules';
import {
  EventRuleItem,
  NoticeRuleItem,
  TemplatePackageType,
} from '../../services/notice-rules/type';

export interface NoticeContextValue {}

export const NoticeContext = React.createContext<NoticeContextValue>(
  {} as NoticeContextValue,
);

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 NoticeContextProps {
  appType: APP_TYPE;
  className?: string;
  editable?: boolean;
  onChange?: (value: boolean) => void;
}

const NoticeContextProvider: React.FC<NoticeContextProps> = props => {
  const { appType, editable = true, children } = props;
  const [unavailable, setUnavailable] = useState(false);
  const [noticeData, setNoticeData] = useState<NoticeRuleItem[]>([]);
  const [eventData, setEventData] = useState<EventRuleItem[]>([]);
  const [change, setChange] = useState(false);
  const unblockRef = useRef<any>();
  const {
    loading,
    noticeRules,
    eventRules,
    updateLoading,
    updateRequest,
  } = useNoticeRules(appType);
  const category = appTypeToCategory[appType];

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

  // 动态更新
  useEffect(() => {
    setEventData(eventRules || []);
  }, [eventRules]);
  useEffect(() => {
    if (change) {
      unblockRef.current = history.block((_, action: 'PUSH' | 'POP') => {
        if (action === 'PUSH') {
          return '信息还没保存，确定离开吗？';
        }
      });
    }

    return () => {
      unblockRef?.current?.();
    };
  }, [change]);

  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);
  };
  const handleUnavailable = (value: boolean) => {
    setUnavailable(value);
  };

  return (
    <NoticeContext.Provider
      value={{
        category,
        eventData,
        noticeData,
        editable,
        onEventRule: handleEventRule,
        onNoticeRule: handleNoticeRule,
        onUnavailable: handleUnavailable,
        onSubmit: handleSubmit,
        loading,
        change,
        disabled: !editable || !change || unavailable || updateLoading,
      }}
    >
      {children}
      <Prompt
        when={change}
        message={(a, b) => {
          return '当前页面还有未保存的修改，是否离开？';
        }}
      />
    </NoticeContext.Provider>
  );
};

export default NoticeContextProvider;

export const useNoticeContext = (): NoticeContextValue =>
  React.useContext(NoticeContext);
