// pages/notification/detail/detail.js
Page({
  data: {
    statusBarHeight: 0,
    loading: true,
    notificationId: '',
    notificationInfo: {}
  },

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

    // 获取通知ID
    if (options.id) {
      this.setData({
        notificationId: options.id
      });
      this.loadNotificationDetail();
    } else {
      wx.showToast({
        title: '参数错误',
        icon: 'error'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  onShow() {
    // 检查登录状态
    this.checkLoginStatus();
  },

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

  // 加载通知详情
  async loadNotificationDetail() {
    try {
      this.setData({ loading: true });
      
      // 模拟API调用
      const notificationData = await this.fetchNotificationDetail(this.data.notificationId);
      
      this.setData({
        notificationInfo: notificationData,
        loading: false
      });

      // 标记为已读
      this.markAsRead();
    } catch (error) {
      console.error('加载通知详情失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      });
      this.setData({ loading: false });
    }
  },

  // 模拟获取通知详情API
  fetchNotificationDetail(notificationId) {
    return new Promise((resolve) => {
      setTimeout(() => {
        // 根据ID生成不同类型的模拟数据
        const mockData = this.generateMockNotification(notificationId);
        resolve(mockData);
      }, 1000);
    });
  },

  // 生成模拟通知数据
  generateMockNotification(id) {
    const types = ['system', 'alert', 'task'];
    const type = types[parseInt(id) % 3];
    
    const baseData = {
      id: id,
      type: type,
      time: this.formatTime(new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000)),
      isRead: false
    };

    switch (type) {
      case 'system':
        return {
          ...baseData,
          title: '系统维护通知',
          content: '系统将于今晚22:00-24:00进行例行维护，期间可能影响部分功能使用，请提前做好相关准备工作。维护期间如有紧急情况，请联系技术支持热线。',
          attachments: [
            {
              id: '1',
              name: '维护说明文档.pdf',
              size: '2.3MB'
            }
          ],
          processRecords: [
            {
              id: '1',
              time: '10:30',
              action: '发布通知',
              operator: '系统管理员',
              remark: '定期系统维护通知'
            }
          ]
        };
        
      case 'alert':
        return {
          ...baseData,
          title: '牲畜异常告警',
          content: '检测到张三养殖场出现牲畜异常情况，请及时处理。系统监测显示该养殖场的牲畜活动异常，可能存在健康风险，建议立即派遣检查人员前往现场核实情况。',
          alertDetails: {
            level: 'high',
            farmerName: '张三',
            location: '西夏区兴泾镇张三养殖场',
            reason: '牲畜活动异常，疑似健康问题'
          },
          processRecords: [
            {
              id: '1',
              time: '14:25',
              action: '系统自动告警',
              operator: '监控系统',
              remark: '检测到异常数据'
            }
          ]
        };
        
      case 'task':
        return {
          ...baseData,
          title: '月度检查任务',
          content: '请在本月底前完成辖区内所有养殖户的月度例行检查工作。检查内容包括：牲畜健康状况、饲料质量、环境卫生、防疫措施等。请及时提交检查报告。',
          taskDetails: {
            taskType: '月度例行检查',
            deadline: '2024-01-31 18:00',
            status: 'pending',
            priority: 'medium'
          },
          attachments: [
            {
              id: '1',
              name: '检查清单.xlsx',
              size: '156KB'
            },
            {
              id: '2',
              name: '报告模板.docx',
              size: '89KB'
            }
          ],
          processRecords: [
            {
              id: '1',
              time: '09:00',
              action: '任务分配',
              operator: '管理员',
              remark: '月度例行检查任务'
            }
          ]
        };
        
      default:
        return baseData;
    }
  },

  // 格式化时间
  formatTime(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hour = String(date.getHours()).padStart(2, '0');
    const minute = String(date.getMinutes()).padStart(2, '0');
    
    return `${year}-${month}-${day} ${hour}:${minute}`;
  },

  // 标记为已读
  async markAsRead() {
    try {
      // 模拟API调用
      await this.markNotificationAsRead(this.data.notificationId);
      console.log('通知已标记为已读');
    } catch (error) {
      console.error('标记已读失败:', error);
    }
  },

  // 模拟标记已读API
  markNotificationAsRead(notificationId) {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve({ success: true });
      }, 500);
    });
  },

  // 处理告警
  onHandleAlert() {
    const alertDetails = this.data.notificationInfo.alertDetails;
    wx.showModal({
      title: '处理告警',
      content: `确定要处理来自${alertDetails.farmerName}的告警吗？`,
      success: (res) => {
        if (res.confirm) {
          // 这里可以跳转到具体的处理页面
          wx.showToast({
            title: '正在处理...',
            icon: 'loading'
          });
          
          setTimeout(() => {
            wx.showToast({
              title: '处理成功',
              icon: 'success'
            });
          }, 2000);
        }
      }
    });
  },

  // 处理任务
  onHandleTask() {
    const taskDetails = this.data.notificationInfo.taskDetails;
    wx.showModal({
      title: '处理任务',
      content: `确定要开始处理"${taskDetails.taskType}"任务吗？`,
      success: (res) => {
        if (res.confirm) {
          // 这里可以跳转到具体的任务处理页面
          wx.showToast({
            title: '任务已接受',
            icon: 'success'
          });
        }
      }
    });
  },

  // 分享通知
  onShare() {
    wx.showActionSheet({
      itemList: ['复制链接', '发送给同事', '保存到本地'],
      success: (res) => {
        switch (res.tapIndex) {
          case 0:
            wx.setClipboardData({
              data: `通知详情：${this.data.notificationInfo.title}`,
              success: () => {
                wx.showToast({
                  title: '已复制到剪贴板',
                  icon: 'success'
                });
              }
            });
            break;
          case 1:
            wx.showToast({
              title: '功能开发中',
              icon: 'none'
            });
            break;
          case 2:
            wx.showToast({
              title: '保存成功',
              icon: 'success'
            });
            break;
        }
      }
    });
  },

  // 查看附件
  onAttachmentTap(e) {
    const attachment = e.currentTarget.dataset.attachment;
    wx.showModal({
      title: '查看附件',
      content: `确定要查看附件"${attachment.name}"吗？`,
      success: (res) => {
        if (res.confirm) {
          wx.showToast({
            title: '正在打开...',
            icon: 'loading'
          });
          
          // 这里可以实现附件预览或下载功能
          setTimeout(() => {
            wx.showToast({
              title: '功能开发中',
              icon: 'none'
            });
          }, 1500);
        }
      }
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadNotificationDetail().finally(() => {
      wx.stopPullDownRefresh();
    });
  }
});