// 通知列表页面的JS文件
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    activeTab: 0, // 当前选中的tab，0为公告，1为消息
    noticeList: [],
    userNoticesList: [],
    unreadCount: 0 // 未读消息数量
  },

  onLoad: function (options) {
    // 直接从全局数据获取通知列表
    this.setData({
      noticeList: app.globalData.notices || [],
      userNoticesList: app.globalData.userNoticesList || []

    });
    
    // 计算未读消息数量
    this.countUnreadMessages();
  },

  /**
   * 计算未读消息数量
   */
  countUnreadMessages: function() {
    const unreadCount = this.data.userNoticesList.filter(item => item.readstate === '2').length;
    this.setData({
      unreadCount: unreadCount
    });
  },

  /**
   * 切换Tab
   */
  switchTab: function(e) {
    const index = parseInt(e.currentTarget.dataset.index);
    this.setData({
      activeTab: index
    });
    
    // 重新从全局数据获取最新数据
    if (index === 0) {
      this.setData({
        noticeList: app.globalData.notices || []
      });
    } else if (index === 1) {
      this.setData({
        userNoticesList: app.globalData.userNoticesList || []
      });
      this.countUnreadMessages();
    }
  },

  /**
   * 一键已读
   */
  markAllAsRead: function(e) {
    wx.request({
      url: app.globalData.interfaceUrls.updateRadstateStatusAll,
      method: 'POST',
      data: {
        account: app.globalData.currentAccountInfo.usernumber,
        deKey: app.globalData.currentAccountInfo.dsKey,
      },
      header: {
        'content-type': 'application/json',
        'token': app.globalData.userWxInfo.token,
        'source': "wc",
        '!SAAS_LOGIN_TOKEN_!': app.globalData.currentAccountInfo.dsKey
      },
      success: (res) => {
        if (res.data.code == '200') {
          // 更新本地数据
          const updatedList = this.data.userNoticesList.map(item => {
            return {...item, readstate: '1'};
          });

          // 更新全局数据和页面数据
          app.globalData.userNoticesList = updatedList;
          this.setData({
            userNoticesList: updatedList,
            unreadCount: 0
          });
          
          // 更新未读消息数量
          this.countUnreadMessages();
          
          // 提示操作成功
          wx.showToast({
            title: '操作成功',
            icon: 'success',
            duration: 1500
          });
          
          // 通知首页刷新未读消息状态
          if (typeof app.globalData.refreshUnreadStatus === 'function') {
            app.globalData.refreshUnreadStatus();
          }
        } else {
          wx.showToast({
            title: res.data.msg || '操作失败',
            icon: 'none',
            duration: 1500
          });
        }
      },
      fail: (err) => {
        console.error('更新消息状态失败:', err);
        wx.showToast({
          title: '网络异常，请稍后重试',
          icon: 'none',
          duration: 1500
        });
      }
    });
  },
  
  /**
   * 刷新消息列表
   */
  refreshMessageList: function() {
    // 从全局数据刷新
    this.setData({
      noticeList: app.globalData.notices || [],
      userNoticesList: app.globalData.userNoticesList || []
    });
    
    // 刷新完成后重新计算未读消息数
    this.countUnreadMessages();
  },

  /**
   * 跳转到通知详情页
   */
  goToDetail: function (e) {
    const id = e.currentTarget.dataset.id;
    const tabIndex = this.data.activeTab; // 获取当前所在Tab
    const notice = tabIndex === 0 
      ? this.data.noticeList.find(item => item.id === id)
      : this.data.userNoticesList.find(item => item.id === id);
    
    if (notice) {
      // 如果是消息类型且是未读状态，调用后台方法更新已读状态
      if (tabIndex === 1 && notice.readstate === '2') {
        this.updateReadStatus(id);
      }
      
      // 将通知数据转换为JSON字符串
      const noticeStr = JSON.stringify(notice);
      // 跳转到详情页并传递完整数据
      wx.navigateTo({
        url: '/pages/tzxq/tzxq?noticeData=' + encodeURIComponent(noticeStr)
      });
    } else {
      wx.showToast({
        title: '未找到通知详情',
        icon: 'none'
      });
    }
  },

  /**
   * 更新消息的已读状态
   */
  updateReadStatus: function(id) {
    wx.request({
      url: app.globalData.interfaceUrls.updateRadstateStatus,
      method: 'POST',
      data: {
        id: id,
        account: app.globalData.currentAccountInfo.usernumber,
        deKey: app.globalData.currentAccountInfo.dsKey,
      },
      header: {
        'content-type': 'application/json',
        'token': app.globalData.userWxInfo.token,
        'source': "wc",
        '!SAAS_LOGIN_TOKEN_!': app.globalData.currentAccountInfo.dsKey
      },
      success: (res) => {
        debugger
        if (res.data.code == '200') {
          // 更新本地数据
          const updatedList = this.data.userNoticesList.map(item => {
            if (item.id === id) {
              return {...item, readstate: '1'};
            }
            return item;
          });
          // 更新全局数据和页面数据
          app.globalData.userNoticesList = updatedList;
          this.setData({
            userNoticesList: updatedList
          });
          // 更新未读消息数量
          this.countUnreadMessages();
        }
      },
      fail: (err) => {
        console.error('更新消息状态失败:', err);
      }
    });
  },

  /**
   * 获取最新消息数据
   */
  fetchLatestMessages: function() {
    wx.showLoading({
      title: '加载中...',
    });
    
    // 调用获取公告列表API
    wx.request({
      url: app.globalData.apiUrl + '/api/getNotices', 
      method: 'GET',
      success: (res) => {
        if (res.data.success) {
          // 更新全局数据和页面数据
          app.globalData.notices = res.data.data.notices || [];
          this.setData({
            noticeList: app.globalData.notices
          });
        }
      },
      complete: () => {
        // 无论成功失败都继续获取用户消息
        this.fetchUserMessages();
      }
    });
  },

  /**
   * 获取用户消息
   */
  fetchUserMessages: function() {
    wx.request({
      url: app.globalData.apiUrl + '/api/getUserMessages', 
      method: 'GET',
      data: {
        userId: app.globalData.userId 
      },
      success: (res) => {
        if (res.data.success) {
          // 更新全局数据和页面数据
          app.globalData.userNoticesList = res.data.data.messages || [];
          this.setData({
            userNoticesList: app.globalData.userNoticesList
          });
          
          // 更新未读消息数量
          this.countUnreadMessages();
        }
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },

  /**
   * 返回上一页
   */
  goBack: function() {
    wx.navigateBack();
  },
  
  // 页面显示时刷新数据
  onShow: function() {
    this.fetchLatestMessages();
  }
})
