useNotifications.js
9.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
import { ref } from 'vue';
// 生成模拟数据的辅助函数
function generateMockData(count) {
const types = ['system', 'task', 'alert', 'work', 'alarm'];
const titles = {
system: ['System Alerts', 'System Updates', 'System Maintenance', 'System Status', 'System Security'],
task: ['Store Patrol Tasks', 'Daily Tasks', 'Weekly Tasks', 'Monthly Tasks', 'Special Tasks'],
alert: ['O&M Alerts', 'Security Alerts', 'Performance Alerts', 'Network Alerts', 'Database Alerts'],
work: ['O&M Work Orders', 'Maintenance Orders', 'Repair Orders', 'Installation Orders', 'Inspection Orders'],
alarm: ['YAP Alarm', 'Security Alarm', 'Fire Alarm', 'Temperature Alarm', 'Power Alarm']
};
const messages = {
system: [
'If the backup daemon falls far behind in...',
'System update is available for installation...',
'Scheduled maintenance will begin at 2:00 AM...',
'System performance has been optimized...',
'Security patches have been applied to the system...'
],
task: [
'Check if entrances and exits are unobstructed...',
'Complete daily inventory check by 5:00 PM...',
'Weekly equipment maintenance is due today...',
'Monthly financial report needs to be submitted...',
'Special event preparation tasks need attention...'
],
alert: [
'The alert module checks system partition...',
'Security breach detected in network segment B...',
'CPU usage has exceeded 90% for 15 minutes...',
'Network latency has increased significantly...',
'Database connection pool is nearly exhausted...'
],
work: [
'When the system detects that server disk...',
'Maintenance work order #45678 has been assigned...',
'Repair work order for register #3 is pending...',
'New equipment installation scheduled for tomorrow...',
'Store inspection work order has been completed...'
],
alarm: [
'PMI Store found minors entering the store...',
'Security alarm triggered at south entrance...',
'Fire alarm activated in storage area B...',
'Refrigeration temperature exceeds safe threshold...',
'Power fluctuation detected in main circuit...'
]
};
const result = [];
const now = new Date();
for (let i = 0; i < count; i++) {
const type = types[Math.floor(Math.random() * types.length)];
const titleIndex = Math.floor(Math.random() * titles[type].length);
const messageIndex = Math.floor(Math.random() * messages[type].length);
// 生成随机日期(最近30天内)
const randomDate = new Date(now);
randomDate.setDate(now.getDate() - Math.floor(Math.random() * 30));
const month = String(randomDate.getMonth() + 1).padStart(2, '0');
const day = String(randomDate.getDate()).padStart(2, '0');
const hours = String(randomDate.getHours()).padStart(2, '0');
const minutes = String(randomDate.getMinutes()).padStart(2, '0');
const time = `${month}-${day} ${hours}:${minutes}`;
// 随机未读状态和数量
const unread = Math.random() > 0.5;
const unreadCount = unread ? String(Math.floor(Math.random() * 5) + 1) : '0';
result.push({
id: `notification-${i + 1}`,
type,
title: titles[type][titleIndex],
message: messages[type][messageIndex],
time,
unread,
unreadCount
});
}
// 按日期排序,最新的在前面
return result.sort((a, b) => {
const dateA = new Date(`2023-${a.time.replace(' ', 'T')}`);
const dateB = new Date(`2023-${b.time.replace(' ', 'T')}`);
return dateB - dateA;
});
}
// 所有模拟数据
const allMockData = generateMockData(50);
export function useNotifications() {
// 通知列表数据
const notificationList = ref([]);
// 当前筛选类型
const currentFilter = ref('all');
// 加载通知数据
const fetchNotifications = (filterType = 'all') => {
return new Promise((resolve, reject) => {
try {
// 更新当前筛选类型
currentFilter.value = filterType;
// 模拟网络请求延迟
setTimeout(() => {
// 根据筛选类型过滤数据
let filteredData = [...allMockData];
if (filterType !== 'all') {
filteredData = allMockData.filter(item => item.type === filterType);
}
// 获取第一页数据
const firstPageData = filteredData.slice(0, 10);
notificationList.value = firstPageData;
resolve(firstPageData);
}, 300);
} catch (error) {
console.error('Failed to fetch notifications:', error);
uni.showToast({
title: '获取通知失败',
icon: 'none'
});
reject(error);
}
});
// 实际应用中应该替换为真实API调用
/*
return new Promise((resolve, reject) => {
uni.request({
url: 'your-api-url/notifications',
method: 'GET',
data: {
page: 1,
pageSize: 10,
type: filterType !== 'all' ? filterType : undefined
},
success: (res) => {
if (res.statusCode === 200 && res.data) {
notificationList.value = res.data.items;
resolve(res.data.items);
} else {
reject(new Error('Failed to fetch data'));
}
},
fail: (err) => {
console.error('Failed to fetch notifications:', err);
uni.showToast({
title: '获取通知失败',
icon: 'none'
});
reject(err);
}
});
});
*/
};
// 加载更多通知数据
const loadMoreNotifications = (page, pageSize) => {
return new Promise((resolve) => {
// 模拟网络请求延迟
setTimeout(() => {
// 根据筛选类型过滤数据
let filteredData = [...allMockData];
if (currentFilter.value !== 'all') {
filteredData = allMockData.filter(item => item.type === currentFilter.value);
}
// 计算起始和结束索引
const startIndex = (page - 1) * pageSize;
const endIndex = startIndex + pageSize;
// 获取当前页数据
const currentPageData = filteredData.slice(startIndex, endIndex);
// 追加到现有列表
notificationList.value = [...notificationList.value, ...currentPageData];
resolve(currentPageData);
}, 300);
});
// 实际应用中应该替换为真实API调用
/*
return new Promise((resolve, reject) => {
uni.request({
url: 'your-api-url/notifications',
method: 'GET',
data: {
page,
pageSize,
type: currentFilter.value !== 'all' ? currentFilter.value : undefined
},
success: (res) => {
if (res.statusCode === 200 && res.data) {
// 追加到现有列表
notificationList.value = [...notificationList.value, ...res.data.items];
resolve(res.data.items);
} else {
reject(new Error('Failed to fetch more data'));
}
},
fail: (err) => {
console.error('Failed to fetch more notifications:', err);
reject(err);
}
});
});
*/
};
// 标记通知为已读
const markAsRead = (index) => {
if (index >= 0 && index < notificationList.value.length) {
notificationList.value[index].unread = false;
notificationList.value[index].unreadCount = '0';
// 实际应用中应该调用API更新已读状态
// const notificationId = notificationList.value[index].id;
// updateReadStatus(notificationId);
}
};
// 标记所有通知为已读
const markAllAsRead = () => {
notificationList.value.forEach(item => {
item.unread = false;
item.unreadCount = '0';
});
// 实际应用中应该调用API更新所有通知的已读状态
// updateAllReadStatus();
};
// 更新已读状态到服务器
const updateReadStatus = (notificationId) => {
// 实际应用中应该替换为真实API调用
/*
return new Promise((resolve, reject) => {
uni.request({
url: `your-api-url/notifications/${notificationId}/read`,
method: 'PUT',
success: (res) => {
console.log('Marked as read:', res);
resolve(res.data);
},
fail: (err) => {
console.error('Failed to mark as read:', err);
reject(err);
}
});
});
*/
};
// 更新所有通知为已读
const updateAllReadStatus = () => {
// 实际应用中应该替换为真实API调用
/*
return new Promise((resolve, reject) => {
uni.request({
url: 'your-api-url/notifications/read-all',
method: 'PUT',
success: (res) => {
console.log('Marked all as read:', res);
resolve(res.data);
},
fail: (err) => {
console.error('Failed to mark all as read:', err);
reject(err);
}
});
});
*/
};
// 处理通知点击
const handleNotificationClick = (item, index) => {
console.log('Clicked notification:', item);
// 标记为已读
if (item.unread) {
markAsRead(index);
}
// 根据通知类型跳转到不同页面
navigateToDetail(item.type);
};
// 根据类型导航到详情页
const navigateToDetail = (type) => {
const routes = {
system: '/subPackages/accountGroup/pages/notification/detail/system',
task: '/subPackages/accountGroup/pages/notification/detail/task',
alert: '/subPackages/accountGroup/pages/notification/detail/alert',
work: '/subPackages/accountGroup/pages/notification/detail/work',
alarm: '/subPackages/accountGroup/pages/notification/detail/alarm'
};
const route = routes[type];
if (route) {
// uni.navigateTo({
// url: route
// });
}
};
return {
notificationList,
fetchNotifications,
loadMoreNotifications,
markAsRead,
markAllAsRead,
handleNotificationClick
};
}