useNotifications.js 9.98 KB
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
  };
}