// pages/wode/wode.js
const app = getApp();
import { ensureLogin } from '../../utils/login';
import {
  backfillUserProfileCache,
  getUserProfileForDisplay,
  clearCacheAndEnterNormal,
  isRoleStatusActive,
  ensureRoleOnCenterPage,
} from '../../utils/role-tab-bar';
import { enterLockedRole } from '../../utils/primary-role.js';

Page({
  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,
    bottomSafePadding: 0
  },

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

  onShow() {
    this.initIconUrls();
    this.registerNotification();
    this.checkAvatarPrompt();
    backfillUserProfileCache(app);
    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 微调，确保不留缝隙
    })
  },

  registerNotification() {
    const comp = this.selectComponent('#global-notification')
    if (comp?.showNotification) {
      app.globalData.globalNotification = {
        show: d => comp.showNotification(d),
        hide: () => comp.hideNotification()
      }
    }
  },

  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: '#C9A962',
        success: r => r.confirm && wx.navigateTo({ url: '/pages/xiugai/xiugai' })
      })
    }
  },

  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);
    this.setData({
      avatarUrl: profile.avatarUrl,
      userNicheng: profile.nick,
      userUid: profile.uid,
      showLoginBtn: !profile.isLoggedIn,
      dashouCertified: isRoleStatusActive(wx.getStorageSync('dashoustatus')),
      shangjiaCertified: isRoleStatusActive(wx.getStorageSync('shangjiastatus')),
    });
  },

  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/xiugai/xiugai' }) },

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

  goToOrder(e) { wx.navigateTo({ url: `/pages/dingdan/dingdan?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(() => {
        this.loadUserData();
        const statusKey = type === 'dashou' ? 'dashoustatus' : 'shangjiastatus';
        if (isRoleStatusActive(wx.getStorageSync(statusKey))) {
          ensureRoleOnCenterPage(this, type);
          enterLockedRole(type, app);
          return;
        }
        wx.navigateTo({ url: `/pages/renzheng/renzheng?type=${type}` });
      })
      .catch(() => {});
  },

  goToKefu() {
    const { link, enterpriseId } = app.globalData.kefuConfig || {}
    if (!link || !enterpriseId) { wx.showToast({ title: '客服配置未加载', icon: 'none' }); return }
    wx.openCustomerServiceChat({ extInfo: { url: link }, corpId: enterpriseId })
  },
  goToCustomService() { this.goToKefu() },
  goToGuanzhuA() { wx.navigateTo({ url: '/pages/guanzhual/guanzhual' }) },

  clearCache() {
    wx.showModal({
      title: '清除缓存',
      content: '将清除所有登录与身份数据，并回到点单端，确定继续？',
      confirmText: '确定',
      cancelText: '取消',
      success: r => {
        if (r.confirm) {
          clearCacheAndEnterNormal(this);
        }
      },
    });
  },
})