// pages/mine/mine.js
const app = getApp();
import { ensureLogin } from '../../utils/login';
import {
  backfillUserProfileCache,
  getUserProfileForDisplay,
  getSessionToken,
  isRoleStatusActive,
  ensureRoleOnCenterPage,
} from '../../utils/role-tab-bar';
import { enterLockedRole } from '../../utils/primary-role.js';
import { isStaffMode, getStaffContext, restoreStaffContextAfterAuth } from '../../utils/staff-api.js';
import { createPage } from '../../utils/base-page.js';
import { ensurePhoneAuth } from '../../utils/phone-auth.js';

Page(createPage({
  data: {
    avatarUrl: '',
    userNicheng: '',
    userUid: '',
    showLoginBtn: false,
    orderCounts: { daifuwu:0, fuwuzhong:0, yiwancheng:0, yituikuan:0 },
    // 图标
    settingIcon: '', daifuwuIcon: '', fuwuzhongIcon: '', yiwanchengIcon: '', yituikuanIcon: '',
    dashouIcon: '', shangjiaIcon: '', guanshiIcon: '', kefuIcon: '',
    zuzhangIcon: '', guanzhualongIcon: '', arrowRightIcon: '', qingchuIcon: '',
    dashouCertified: false,
    shangjiaCertified: false,
    staffCertified: false,
    staffTag: '入驻',
    bottomSafePadding: 0
  },

  onLoad() {
    this.initIconUrls()
    this.loadUserData()
    this.setBottomSafe()
  },

  async onShow() {
    const phoneOk = await ensurePhoneAuth({
      redirect: true,
      returnPage: '/pages/mine/mine',
    });
    if (!phoneOk) return;

    this.initIconUrls();
    this.registerNotificationComponent();
    this.checkAvatarPrompt();
    backfillUserProfileCache(app);
    if (getSessionToken(app)) {
      restoreStaffContextAfterAuth().finally(() => {
        this.loadUserData();
        this.updateOrderCounts();
      });
    } else {
      this.loadUserData();
      this.updateOrderCounts();
    }
  },

  setBottomSafe() {
    const sys = wx.getSystemInfoSync()
    const safeBottom = sys.screenHeight - sys.safeArea.bottom  // 底部安全区高度(px)
    const tabBarHeight = (sys.windowWidth / 750) * 100          // 100rpx 转为 px
    this.setData({
      bottomSafePadding: safeBottom + tabBarHeight + 4  // 4px 微调，确保不留缝隙
    })
  },

  checkAvatarPrompt() {
    const ds = wx.getStorageSync('dashoustatus')
    const tx = wx.getStorageSync('touxiang') || ''
    if (ds === 1 && (!tx || tx === 'a_long/morentouxiang.jpg')) {
      wx.showModal({
        title: '提示', content: '请先设置头像',
        confirmText: '去设置', confirmColor: '#9333ea',
        success: r => r.confirm && wx.navigateTo({ url: '/pages/edit/edit' })
      })
    }
  },

  initIconUrls() {
    const base = (app.globalData.ossImageUrl || '') + '/beijing/tubiao/'
    this.setData({
      settingIcon: base + 'grzx_shezhi.jpg',
      daifuwuIcon: base + 'grzx_daifuwu.jpg',
      fuwuzhongIcon: base + 'grzx_fuwuzhong.jpg',
      yiwanchengIcon: base + 'grzx_yiwancheng.jpg',
      yituikuanIcon: base + 'grzx_yituikuan.jpg',
      dashouIcon: base + 'grzx_dashou.jpg',
      shangjiaIcon: base + 'grzx_shangjia.jpg',
      guanshiIcon: base + 'grzx_guanshi.jpg',
      kefuIcon: base + 'grzx_kefu.jpg',
      zuzhangIcon: base + 'grzx_zuzhang.jpg',
      guanzhualongIcon: base + 'grzx_guanzhualong.jpg',
      arrowRightIcon: base + 'grzx_arrow_right.jpg',
      qingchuIcon: base + 'grzx_qingchu.jpg',
      kaoheguanIcon: base + 'kaoheguan.png',
    })
  },

  loadUserData() {
    const profile = getUserProfileForDisplay(app);
    const ctx = getStaffContext();
    const staffActive = isStaffMode();
    this.setData({
      avatarUrl: profile.avatarUrl,
      userNicheng: profile.nick,
      userUid: profile.uid,
      showLoginBtn: !profile.isLoggedIn,
      dashouCertified: isRoleStatusActive(wx.getStorageSync('dashoustatus')),
      shangjiaCertified: isRoleStatusActive(wx.getStorageSync('shangjiastatus')),
      staffCertified: staffActive,
      staffTag: staffActive ? (ctx.role_name || '已入驻') : '入驻',
    });
  },

  updateOrderCounts() {
    const c = app.globalData.dingdanTiaoshu || {}
    this.setData({ orderCounts: {
      daifuwu: c.daifuwu||0, fuwuzhong: c.fuwuzhong||0,
      yiwancheng: c.yiwancheng||0, yituikuan: c.yituikuan||0
    }})
  },

  goToSetting() { wx.navigateTo({ url: '/pages/edit/edit' }) },

  handleWechatLogin() {
    wx.showLoading({ title: '登录中...', mask: true });
    ensureLogin({ silent: false, page: this })
      .then(() => restoreStaffContextAfterAuth())
      .then(() => {
        this.loadUserData();
        this.updateOrderCounts();
        wx.showToast({ title: '登录成功', icon: 'success' });
      })
      .catch(() => {})
      .finally(() => wx.hideLoading());
  },

  goToOrder(e) { wx.navigateTo({ url: `/pages/orders/orders?type=${e.currentTarget.dataset.type}` }) },

  goToAuth(e) {
    const type = e.currentTarget.dataset.type;
    if (!type || !['dashou', 'shangjia'].includes(type)) return;
    ensureLogin({ silent: false, page: this })
      .then(() => restoreStaffContextAfterAuth())
      .then(() => {
        this.loadUserData();
        if (type === 'shangjia' && isStaffMode()) {
          enterLockedRole('shangjia', app);
          return;
        }
        const statusKey = type === 'dashou' ? 'dashoustatus' : 'shangjiastatus';
        if (isRoleStatusActive(wx.getStorageSync(statusKey))) {
          ensureRoleOnCenterPage(this, type);
          enterLockedRole(type, app);
          return;
        }
        wx.navigateTo({ url: `/pages/verify/verify?type=${type}` });
      })
      .catch(() => {});
  },

  goToCustomService() { this.goToKefu() },

  goToStaffJoin() {
    ensureLogin({ silent: false, page: this })
      .then(() => restoreStaffContextAfterAuth())
      .then(() => {
        this.loadUserData();
        if (isStaffMode()) {
          enterLockedRole('shangjia', app);
          return;
        }
        wx.navigateTo({ url: '/pages/staff-join/staff-join' });
      })
      .catch(() => {});
  },

  goToGuanzhuA() { wx.navigateTo({ url: '/pages/manager-assign/manager-assign' }) },
}))
