// pages/profile/profile.ts
import { EmployeeService } from '../../services/employee';

Page({
  data: {
    username: '管理员',
    enterpriseName: '',
    avatar: '',
    publishedCount: 0,
    pendingCount: 0,  // 待审核
    rejectedCount: 0, // 已驳回
    userInfo: null as any,
    isBoundXHS: false,
    xhsAccount: ''
  },

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

    // 加载用户信息
    this.loadUserInfo();
    // 获取数据概览
    this.loadStatistics();
  },

  onShow() {
    // 设置 tabBar 选中状态
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        active: 2
      });
    }
    
    // 每次显示页面时刷新数据
    this.loadUserInfo();
    this.loadStatistics();
  },

  // 加载用户信息
  async loadUserInfo() {
    try {
      const response = await EmployeeService.getProfile();
      
      if (response.code === 200 && response.data) {
        const userInfo = response.data;
        this.setData({
          username: userInfo.name,
          enterpriseName: userInfo.enterprise_name || '',
          avatar: userInfo.avatar || '',
          userInfo,
          isBoundXHS: userInfo.is_bound_xhs === 1,
          xhsAccount: userInfo.xhs_account || ''
        });
      }
    } catch (error) {
      console.error('加载用户信息失败:', error);
      // 使用本地存储的备用数据
      const username = wx.getStorageSync('username');
      if (username) {
        this.setData({ username });
      }
    }
  },

  // 加载数据统计
  async loadStatistics() {
    try {
      // 获取已发布数量（从发布记录API获取）
      const publishResponse = await EmployeeService.getMyPublishRecords(1, 1);
      if (publishResponse.code === 200 && publishResponse.data) {
        this.setData({
          publishedCount: publishResponse.data.total || 0
        });
      }

      // TODO: 后端需要添加待审核和已驳回的API
      // 目前使用默认值
      this.setData({
        pendingCount: 0,
        rejectedCount: 0
      });
    } catch (error) {
      console.error('加载数据统计失败:', error);
      // 使用默认值
      this.setData({
        publishedCount: 0,
        pendingCount: 0,
        rejectedCount: 0
      });
    }
  },

  // 返回首页
  goToHome() {
    wx.redirectTo({
      url: '/pages/home/home'
    });
  },

  // 数据统计
  goToStats() {
    wx.navigateTo({
      url: '/pages/profile/stats/stats'
    });
  },

  // 我的文章
  goToMyArticles() {
    wx.navigateTo({
      url: '/pages/profile/my-articles/my-articles'
    });
  },

  // 已发布文章
  goToPublished() {
    wx.navigateTo({
      url: '/pages/profile/published/published'
    });
  },

  // 收藏夹
  goToFavorites() {
    wx.navigateTo({
      url: '/pages/profile/favorites/favorites'
    });
  },

  // 消息通知
  goToNotifications() {
    wx.navigateTo({
      url: '/pages/profile/notifications/notifications'
    });
  },

  // 个人资料
  goToUserInfo() {
    wx.navigateTo({
      url: '/pages/profile/user-info/user-info'
    });
  },

  // 社交账号绑定
  goToSocialBinding() {
    wx.navigateTo({
      url: '/pages/profile/social-binding/social-binding'
    });
  },

  // 意见反馈
  goToFeedback() {
    wx.navigateTo({
      url: '/pages/profile/feedback/feedback'
    });
  },

  // 关于我们
  goToAbout() {
    wx.navigateTo({
      url: '/pages/profile/about/about'
    });
  },

  // 退出登录
  handleLogout() {
    wx.showModal({
      title: '提示',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          // 清除本地存储
          wx.clearStorageSync();
          // 返回登录页
          wx.redirectTo({
            url: '/pages/login/login'
          });
        }
      }
    });
  }
});
