const app = getApp();
const apiService = require('../../utils/api.js');

Page({
  data: {
    statusBarHeight: 0,
    loading: true,
    
    // 筛选状态
    selectedType: 'all',
    selectedStatus: 'all',
    
    // 筛选选项
    typeOptions: [
      { value: 'all', label: '全部类型' },
      { value: 'system', label: '系统通知' },
      { value: 'alert', label: '预警通知' },
      { value: 'task', label: '任务通知' }
    ],
    
    statusOptions: [
      { value: 'all', label: '全部状态' },
      { value: 'unread', label: '未读' },
      { value: 'read', label: '已读' }
    ],
    
    // 通知列表
    notificationList: [],
    
    // 分页
    currentPage: 1,
    pageSize: 10,
    totalCount: 0,
    hasMore: true,
    
    // 统计信息
    statistics: {
      total: 0,
      unread: 0,
      system: 0,
      alert: 0,
      task: 0
    }
  },

  onLoad() {
    // 获取状态栏高度
    const systemInfo = wx.getSystemInfoSync();
    this.setData({
      statusBarHeight: systemInfo.statusBarHeight
    });
    
    // 检查登录状态
    this.checkLoginStatus();
  },

  onShow() {
    // 每次显示页面时刷新数据
    this.loadData();
  },

  // 检查登录状态
  checkLoginStatus() {
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.reLaunch({
        url: '/pages/login/login'
      });
      return false;
    }
    return true;
  },

  // 加载数据
  async loadData(isRefresh = true) {
    if (!this.checkLoginStatus()) return;
    
    if (isRefresh) {
      this.setData({ 
        loading: true,
        currentPage: 1,
        notificationList: [],
        hasMore: true
      });
    }
    
    try {
      await this.loadNotifications();
    } catch (error) {
      console.error('数据加载失败:', error);
      // 加载模拟数据作为备用
      this.loadMockData();
    } finally {
      this.setData({ loading: false });
    }
  },

  // 加载通知列表
  async loadNotifications() {
    try {
      const params = {
        page: this.data.currentPage,
        pageSize: this.data.pageSize,
        type: this.data.selectedType === 'all' ? '' : this.data.selectedType,
        status: this.data.selectedStatus === 'all' ? '' : this.data.selectedStatus
      };
      
      // 这里可以调用实际的通知API
      // const result = await apiService.getNotifications(params);
      
      // 暂时使用模拟数据
      this.loadMockData();
    } catch (error) {
      console.error('获取通知列表失败:', error);
      throw error;
    }
  },

  // 加载模拟数据
  loadMockData() {
    const mockNotifications = [
      {
        id: 1,
        type: 'alert',
        title: '养殖户异常预警',
        content: '张三养殖场检测到异常情况，请及时处理',
        status: 'unread',
        priority: 'high',
        createTime: '2024-01-15 10:30:00',
        farmerId: 1,
        farmerName: '张三',
        farmName: '张家养殖场'
      },
      {
        id: 2,
        type: 'system',
        title: '系统维护通知',
        content: '系统将于今晚22:00-24:00进行维护，期间可能影响正常使用',
        status: 'read',
        priority: 'medium',
        createTime: '2024-01-15 09:15:00'
      },
      {
        id: 3,
        type: 'task',
        title: '检查任务提醒',
        content: '您有一个待处理的检查任务：李氏牧场定期检查',
        status: 'unread',
        priority: 'medium',
        createTime: '2024-01-15 08:45:00',
        farmerId: 2,
        farmerName: '李四',
        farmName: '李氏牧场'
      },
      {
        id: 4,
        type: 'alert',
        title: '设备离线预警',
        content: '王家农场的监控设备已离线超过2小时',
        status: 'unread',
        priority: 'high',
        createTime: '2024-01-14 16:20:00',
        farmerId: 3,
        farmerName: '王五',
        farmName: '王家农场'
      },
      {
        id: 5,
        type: 'system',
        title: '数据同步完成',
        content: '今日数据同步已完成，共同步1250条记录',
        status: 'read',
        priority: 'low',
        createTime: '2024-01-14 15:30:00'
      }
    ];
    
    // 根据筛选条件过滤数据
    let filteredNotifications = mockNotifications;
    
    if (this.data.selectedType !== 'all') {
      filteredNotifications = filteredNotifications.filter(n => n.type === this.data.selectedType);
    }
    
    if (this.data.selectedStatus !== 'all') {
      filteredNotifications = filteredNotifications.filter(n => n.status === this.data.selectedStatus);
    }
    
    this.setData({
      notificationList: filteredNotifications,
      totalCount: filteredNotifications.length,
      hasMore: false,
      statistics: {
        total: mockNotifications.length,
        unread: mockNotifications.filter(n => n.status === 'unread').length,
        system: mockNotifications.filter(n => n.type === 'system').length,
        alert: mockNotifications.filter(n => n.type === 'alert').length,
        task: mockNotifications.filter(n => n.type === 'task').length
      }
    });
  },

  // 类型筛选
  onTypeChange(e) {
    const type = e.currentTarget.dataset.type;
    this.setData({
      selectedType: type
    });
    this.loadData(true);
  },

  // 状态筛选
  onStatusChange(e) {
    const status = e.currentTarget.dataset.status;
    this.setData({
      selectedStatus: status
    });
    this.loadData(true);
  },

  // 生成模拟通知数据
  generateMockNotifications() {
    const types = ['system', 'alert', 'task']
    const typeNames = { system: '系统通知', alert: '告警通知', task: '任务通知' }
    const icons = { system: '🔔', alert: '⚠️', task: '📋' }
    
    const notifications = []
    const pageSize = this.data.pageSize
    
    for (let i = 0; i < pageSize; i++) {
      const type = types[Math.floor(Math.random() * types.length)]
      const isRead = Math.random() > 0.3
      const id = Date.now() + i
      
      notifications.push({
        id,
        type,
        typeName: typeNames[type],
        icon: icons[type],
        title: this.getNotificationTitle(type),
        content: this.getNotificationContent(type),
        time: this.formatTime(new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000)),
        isRead
      })
    }
    
    return notifications.filter(item => {
      if (this.data.selectedTab === 'all') return true
      return item.type === this.data.selectedTab
    })
  },

  // 获取通知标题
  getNotificationTitle(type) {
    const titles = {
      system: ['系统维护通知', '版本更新提醒', '账户安全提醒', '数据备份完成'],
      alert: ['设备离线告警', '异常数据告警', '温度超标告警', '网络连接异常'],
      task: ['检疫任务提醒', '报告提交截止', '数据统计任务', '设备巡检任务']
    }
    const typeList = titles[type] || titles.system
    return typeList[Math.floor(Math.random() * typeList.length)]
  },

  // 获取通知内容
  getNotificationContent(type) {
    const contents = {
      system: ['系统将于今晚进行维护，预计持续2小时', '新版本已发布，请及时更新', '检测到异常登录，请注意账户安全', '数据备份已完成，请查看备份报告'],
      alert: ['监控摄像头#001已离线超过30分钟', '养殖场温度传感器检测到异常数据', '养殖区域温度超过安全范围', '网络连接不稳定，请检查网络设备'],
      task: ['您有新的检疫任务需要处理', '月度报告提交截止日期临近', '请完成本周数据统计工作', '设备巡检任务已分配给您']
    }
    const typeList = contents[type] || contents.system
    return typeList[Math.floor(Math.random() * typeList.length)]
  },

  // 格式化时间
  formatTime(date) {
    const now = new Date()
    const diff = now - date
    const minutes = Math.floor(diff / (1000 * 60))
    const hours = Math.floor(diff / (1000 * 60 * 60))
    const days = Math.floor(diff / (1000 * 60 * 60 * 24))

    if (minutes < 1) return '刚刚'
    if (minutes < 60) return `${minutes}分钟前`
    if (hours < 24) return `${hours}小时前`
    if (days < 7) return `${days}天前`
    
    return `${date.getMonth() + 1}-${date.getDate()}`
  },

  // 更新标签计数
  updateTabCounts() {
    const tabs = this.data.tabs.map(tab => {
      if (tab.key === 'all') {
        tab.count = this.data.notificationList.filter(item => !item.isRead).length
      } else {
        tab.count = this.data.notificationList.filter(item => item.type === tab.key && !item.isRead).length
      }
      return tab
    })
    
    this.setData({ tabs })
  },

  // 标签切换
  onTabChange(e) {
    const { key } = e.currentTarget.dataset
    this.setData({
      selectedTab: key,
      currentPage: 1,
      notificationList: [],
      hasMore: true
    })
    this.loadNotifications()
  },

  // 通知点击事件
  onNotificationTap(e) {
    const { item } = e.currentTarget.dataset
    console.log('点击通知:', item)

    // 标记为已读
    if (!item.isRead) {
      const notificationList = this.data.notificationList.map(notification => {
        if (notification.id === item.id) {
          notification.isRead = true
        }
        return notification
      })
      
      this.setData({ notificationList })
      this.updateTabCounts()
    }

    // 根据通知类型跳转到相应页面
    switch (item.type) {
      case 'alert':
        wx.navigateTo({
          url: '/pages/alert/detail/detail?id=' + item.id
        })
        break
      case 'task':
        wx.navigateTo({
          url: '/pages/task/detail/detail?id=' + item.id
        })
        break
      default:
        wx.showToast({
          title: '查看详情功能开发中',
          icon: 'none'
        })
    }
  },

  // 删除通知
  onDeleteNotification(e) {
    const { item } = e.currentTarget.dataset
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这条通知吗？',
      success: (res) => {
        if (res.confirm) {
          const notificationList = this.data.notificationList.filter(notification => notification.id !== item.id)
          this.setData({ notificationList })
          this.updateTabCounts()
          
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          })
        }
      }
    })
  },

  // 全部已读
  onMarkAllRead() {
    const notificationList = this.data.notificationList.map(item => {
      item.isRead = true
      return item
    })
    
    this.setData({ notificationList })
    this.updateTabCounts()
    
    wx.showToast({
      title: '已全部标记为已读',
      icon: 'success'
    })
  },

  // 加载更多
  onLoadMore() {
    this.loadNotifications()
  }
})