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( {} 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 = props => { const { appType, editable = true, children } = props; const [unavailable, setUnavailable] = useState(false); const [noticeData, setNoticeData] = useState([]); const [eventData, setEventData] = useState([]); const [change, setChange] = useState(false); const unblockRef = useRef(); 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 ( {children} { return '当前页面还有未保存的修改,是否离开?'; }} /> ); }; export default NoticeContextProvider; export const useNoticeContext = (): NoticeContextValue => React.useContext(NoticeContext);