/**
 * 个人中心页
 */
const api = require('../../utils/api');
const decor = require('../../utils/decor');
const util = require('../../utils/util');

Page({
  data: {
    decorEnabled: false,
    decorComponents: [],
    logged: false,
    userInfo: {},
    levelInfo: { current_level: null, next_level: null, experience: 0 }
  },

  onShow() {
    decor.init(this, 'mine');
    const token = api.getToken();
    if (token) {
      this.setData({ logged: true });
      this.loadUserInfo();
    } else {
      this.setData({ logged: false, userInfo: {}, levelInfo: {} });
    }
  },

  async loadUserInfo() {
    try {
      const [userInfo, levelInfo] = await Promise.all([
        api.getUserInfo(),
        api.getUserLevel().catch(() => ({}))
      ]);
      this.setData({ userInfo: userInfo || {}, levelInfo: levelInfo || {} });
    } catch (err) {
      console.error('用户信息加载失败:', err);
    }
  },

  maskPhone(phone) {
    return phone ? phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2') : '';
  },

  get avatarChar() {
    const { nickname, phone } = this.data.userInfo;
    const char = (nickname || phone || '?')[0];
    return char;
  },

  goLogin() {
    wx.navigateTo({ url: '/pages/login/login' });
  },

  goOrders(e) {
    const status = e.currentTarget.dataset.status || 'all';
    wx.switchTab({ url: '/pages/order/order' }).catch(() => {
      // 如果order不在tabBar中，用navigateTo
      wx.navigateTo({ url: `/pages/order/order?status=${status}` });
    });
  },

  goAddress() {
    wx.navigateTo({ url: '/pages/address/address' });
  },

  goFavorites() {
    wx.navigateTo({ url: '/pages/favorites/favorites' });
  },

  goCoupon() {
    wx.navigateTo({ url: '/pages/coupon/coupon' });
  },

  goRefund() {
    wx.navigateTo({ url: '/pages/refund/refund' });
  },

  goAbout() {
    wx.navigateTo({ url: '/pages/about/about' });
  },

  gotoMembership() { wx.navigateTo({ url: '/pages/membership/membership' }); },
  gotoDistribution() { wx.navigateTo({ url: '/pages/distribution/distribution' }); },
  gotoExchange() { wx.navigateTo({ url: '/pages/exchange/exchange' }); },
  gotoPoints() { wx.navigateTo({ url: '/pages/points/points' }); },
  gotoRecharge() { wx.navigateTo({ url: '/pages/recharge/recharge' }); },
  gotoCheckin() { wx.navigateTo({ url: '/pages/checkin/checkin' }); },
  gotoNotification() { wx.navigateTo({ url: '/pages/notification/notification' }); },
  gotoBrowseHistory() { wx.navigateTo({ url: '/pages/browse-history/browse-history' }); },
  gotoGroupBuy() { wx.navigateTo({ url: '/pages/group-buy/group-buy' }); },
  gotoPresale() { wx.navigateTo({ url: '/pages/presale/presale' }); },
  gotoBargain() { wx.navigateTo({ url: '/pages/bargain/bargain' }); },

  onLogout() {
    wx.showModal({
      title: '退出确认',
      content: '确定退出当前账号？',
      success: (res) => {
        if (res.confirm) {
          api.setToken('');
          wx.removeStorageSync('userInfo');
          this.setData({
            logged: false,
            userInfo: {},
            levelInfo: {}
          });
          wx.showToast({ title: '已退出', icon: 'success' });
        }
      }
    });
  },

  onDecorNav(e) {
    decor.onNav(this, e, {});
  },

  onDecorProduct(e) {
    const id = e.currentTarget.dataset.id;
    if (id) {
      if (typeof wx.getStorageSync === 'function') {
        try { wx.setStorageSync('_decor_cat_restore', this.data.decorEnabled ? true : false); } catch (q) {}
      }
      wx.navigateTo({ url: '/pages/product/product?id=' + id });
    }
  },
  onClaimCoupon(e) {
    const decor = require('../../utils/decor');
    decor.claimCoupon(this, e);
  },
  onDecorCategory(e) {
    if (typeof wx.switchTab === 'function') wx.switchTab({ url: '/pages/category/category' });
  }
});
