const versionInfo = require('../../utils/version.js');
const { request } = require('../../utils/request.js');
const birthProfile = require('../../utils/birth-profile.js');

Page({
  data: {
    userInfo: null,
    loggedIn: false,
    logging: false,
    // 菜单角标
    profileCount: 0,
    maxFree: birthProfile.MAX_PROFILES,
    bookmarkCount: 0,
    version: versionInfo.version,
    buildNumber: versionInfo.buildNumber,
    buildTime: versionInfo.buildTime,
    commitSha: versionInfo.commitSha
  },

  onShow() {
    this.refreshUser();
    this.refreshCounts();
  },

  refreshUser() {
    const token = wx.getStorageSync('token');
    const userInfo = wx.getStorageSync('lunar-user-info');
    this.setData({ loggedIn: !!token, userInfo: userInfo || null });
  },

  refreshCounts() {
    const bookmarks = wx.getStorageSync('lunar-bookmarks') || [];
    const profiles = birthProfile.getProfiles();
    this.setData({
      bookmarkCount: bookmarks.length,
      profileCount: profiles.length
    });
  },

  // ==================== 登录 ====================

  login() {
    if (this.data.logging) return;
    this.setData({ logging: true });
    wx.login({
      success: (loginRes) => {
        if (!loginRes.code) {
          this.setData({ logging: false });
          wx.showToast({ title: '微信登录失败', icon: 'none' });
          return;
        }
        request({
          url: '/api/user/login',
          method: 'POST',
          data: { code: loginRes.code }
        }).then((res) => {
          if (res && res.code === 0 && res.data && res.data.token) {
            wx.setStorageSync('token', res.data.token);
            wx.setStorageSync('lunar-user-info', res.data.user);
            this.setData({ userInfo: res.data.user, loggedIn: true, logging: false });
            wx.showToast({ title: '登录成功', icon: 'success' });
            // 登录后拉取云端生辰档案，保证菜单计数准确
            birthProfile.syncFromServer().then(() => this.refreshCounts()).catch(() => {});
          } else {
            this.setData({ logging: false });
            wx.showToast({ title: (res && res.msg) || '登录失败', icon: 'none' });
          }
        }).catch(() => {
          this.setData({ logging: false });
          wx.showToast({ title: '登录失败，请稍后重试', icon: 'none' });
        });
      },
      fail: () => {
        this.setData({ logging: false });
        wx.showToast({ title: '微信登录失败', icon: 'none' });
      }
    });
  },

  logout() {
    wx.showModal({
      title: '退出登录',
      content: '退出后生辰档案仅保存在本机，重新登录可恢复云端档案',
      success: (res) => {
        if (!res.confirm) return;
        wx.removeStorageSync('token');
        wx.removeStorageSync('lunar-user-info');
        this.setData({ userInfo: null, loggedIn: false });
        wx.showToast({ title: '已退出', icon: 'success' });
      }
    });
  },

  navTo(e) {
    const url = e.currentTarget.dataset.url;
    // tabBar 页面必须用 switchTab 打开
    const tabPages = ['/pages/home/home', '/pages/wish-tree/wish-tree', '/pages/bazi/bazi', '/pages/wiki/wiki', '/pages/settings/settings'];
    if (tabPages.includes(url)) {
      wx.switchTab({ url });
    } else {
      wx.navigateTo({ url });
    }
  }
});
