// 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';
import {
  ICON_KEYS,
  resolveMiniappIcon,
  getPindaoConfig,
  resolvePindaoImages,
  refreshPindaoConfig,
  warmupPindaoConfig,
  PINDAO_ICON_FALLBACK,
} from '../../utils/miniapp-icons.js';

Page(createPage({
  data: {
    avatarUrl: '',
    userNicheng: '',
    userUid: '',
    showLoginBtn: false,
    orderCounts: { daifuwu:0, fuwuzhong:0, yiwancheng:0, yituikuan:0 },
    settingIcon: '', refreshIcon: '',
    daifuwuIcon: '', fuwuzhongIcon: '', yiwanchengIcon: '', yituikuanIcon: '',
    dashouIcon: '', shangjiaIcon: '', guanshiIcon: '', kefuIcon: '',
    zuzhangIcon: '', guanzhualongIcon: '', pindaoIcon: '', arrowRightIcon: '', qingchuIcon: '',
    dashouCertified: false,
    shangjiaCertified: false,
    staffCertified: false,
    staffTag: '入驻',
    bottomSafePadding: 0,
    pindaoVisible: false,
    pindaoTitle: '频道',
    pindaoChannelNo: '',
    pindaoImages: [],
    showPindaoEntry: false,
    _profileRefreshing: false,
  },

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

  onShow() {
    ensurePhoneAuth({
      redirect: true,
      returnPage: '/pages/mine/mine',
    }).then((phoneOk) => {
      if (!phoneOk) return;
      this.registerNotificationComponent();
      this.loadUserData();
      this.updateOrderCounts();
      this.updatePindaoEntry();
    });
  },

  updatePindaoEntry() {
    const dashou = isRoleStatusActive(wx.getStorageSync('dashoustatus'));
    this.setData({ showPindaoEntry: dashou });
  },

  setBottomSafe() {
    const sys = wx.getSystemInfoSync();
    const safeBottom = sys.screenHeight - sys.safeArea.bottom;
    const tabBarHeight = (sys.windowWidth / 750) * 100;
    this.setData({
      bottomSafePadding: safeBottom + tabBarHeight + 4,
    });
  },

  initIconUrls() {
    const base = (app.globalData.ossImageUrl || '') + 'beijing/tubiao/';
    this.setData({
      settingIcon: base + 'grzx_shezhi.jpg',
      refreshIcon: resolveMiniappIcon(app, ICON_KEYS.ICON_REFRESH, 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',
      pindaoIcon: resolveMiniappIcon(app, ICON_KEYS.MINE_PINDAO, base + 'grzx_pindao.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,
    }});
  },

  async onTapRefresh() {
    if (this._profileRefreshing) return;
    this._profileRefreshing = true;
    wx.showLoading({ title: '刷新中', mask: true });
    try {
      if (getSessionToken(app)) {
        await restoreStaffContextAfterAuth();
      }
      backfillUserProfileCache(app);
      this.loadUserData();
      this.updateOrderCounts();
      wx.showToast({ title: '已刷新', icon: 'success' });
    } catch (e) {
      wx.showToast({ title: '刷新失败', icon: 'none' });
    } finally {
      wx.hideLoading();
      this._profileRefreshing = false;
    }
  },

  openPindaoModal() {
    const cfg = getPindaoConfig(app);
    const images = resolvePindaoImages(app);
    this.setData({
      pindaoVisible: true,
      pindaoTitle: cfg.title || '频道',
      pindaoChannelNo: cfg.channel_no || '',
      pindaoImages: images,
    });
    refreshPindaoConfig(app).then(({ cfg: latest, images: latestImages }) => {
      if (!this.data.pindaoVisible) return;
      this.setData({
        pindaoTitle: latest.title || '频道',
        pindaoChannelNo: latest.channel_no || '',
        pindaoImages: latestImages,
      });
    }).catch(() => {});
  },

  closePindaoModal() {
    this.setData({ pindaoVisible: false });
  },

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

  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(() => {});
  },
}));
