// pages/shangjiazhongxin/shangjiiazhongxin.js

import { createPage, ensureRoleOnCenterPage, lockPrimaryRole, parseSceneOptions, request } from '../../utils/base-page.js';
import { ensureLogin } from '../../utils/login.js';
import {
  STAFF_API, isStaffMode, isMerchantPortalUser, refreshStaffContext, syncStaffUi, getStaffContext,
  restoreStaffContextAfterAuth, applyStaffStatsToPage, guardMerchantOwnerAction, clearStaffSession,
} from '../../utils/staff-api.js';
import { clearCacheAndEnterNormal } from '../../utils/base-page.js';

const app = getApp();

Page(createPage({
  data: {
    // 图片资源
    imgUrls: {
      pageBg: '',
      avatarCardBg: '',
      assetCardBg: '',
      statCardBg: '',
      funcItemBg: '',
      primaryFuncBg: '',
      highlightFuncBg: '',
      iconRelease: '',
      iconFast: '',
      iconOrders: '',
      iconService: '',
      iconPunish: '',
      iconRank: '',
      iconRecharge: '',
      iconWithdraw: '',
      iconRefresh: '',
      iconCopy: '',
      avatarFrame: '',
      iconClear: '',
    },

    // 商家状态
    isShangjia: false,
    isStaffMode: false,
    staffRoleName: '',
    quotaAvailable: '0.00',
    canDispatch: true,
    canStaffManage: true,
    canAudit: true,
    showRechargeWithdraw: true,
    isAutoRegistering: false,
    staffBooting: false,

    // 用户基础信息
    uid: '',
    avatarUrl: '',
    nicheng: '',

    // 商家核心数据
    sjyue: '0.00',
    fabu: 0,
    tuikuan: 0,
    jinriliushui: '0.00',
    jinyueliushui: '0.00',
    jinridingdan: 0,
    jinrituikuan: 0,
    chenghaoList: [],

    // 交互控制
    inviteCode: '',
    pendingCount: 0,
    punishPending: 0,
    scrollRefreshing: false,
    statusBar: 20,
    navBar: 44,
  },

  async onLoad(options) {
    const sys = wx.getSystemInfoSync();
    this.setData({
      statusBar: sys.statusBarHeight || 20,
      navBar: (sys.statusBarHeight || 20) + 44,
    });
    const parsed = parseSceneOptions(options);
    this.setupImageUrls();
    if (wx.getStorageSync('token')) {
      await restoreStaffContextAfterAuth();
    }
    this.checkRoleStatus();

    const inviteCode = parsed.inviteCode;
    if (inviteCode) {
      this.setData({ inviteCode });
      setTimeout(() => this.handleInviteCodeWithLoginCheck({
        inviteCode,
        role: 'shangjia',
        statusKey: 'shangjiastatus',
        alreadyMsg: '您已是商家',
        onNeedLogin: (code) => {
          this.setData({ inviteCode: code });
          ensureLogin({ silent: false, page: this })
            .then(() => {
              if (!this.data.isShangjia) {
                wx.showLoading({ title: '商家注册中...', mask: true });
                this.setData({ isAutoRegistering: true });
                this.onRegister();
              }
            })
            .catch(() => {});
        },
        onAlreadyRegistered: () => {
          wx.showToast({ title: '您已是商家', icon: 'success' });
          ensureRoleOnCenterPage(this, 'shangjia');
        },
      }), 500);
    }

    this.checkColdStartPopup('shangjiaduan');
  },

  async onShow() {
    this.registerNotificationComponent();
    try {
      const token = wx.getStorageSync('token');
      const isOwner = Number(wx.getStorageSync('shangjiastatus')) === 1;
      if (token && !isOwner) {
        await restoreStaffContextAfterAuth();
      }
      this.checkRoleStatus();
      syncStaffUi(this);
      if (this.data.isShangjia) {
        ensureRoleOnCenterPage(this, 'shangjia');
        this.applyCachedShangjiaFromGlobal();
      }
    } catch (err) {
      console.error('商家个人中心 onShow', err);
      this.setData({ isLoading: false, staffBooting: false });
    }
  },

  applyCachedShangjiaFromGlobal() {
    const cached = app.globalData.shangjia || {};
    const ctx = getStaffContext();
    if (isStaffMode() && ctx) {
      syncStaffUi(this);
      return;
    }
    if (!cached.nicheng && !cached.sjyue) return;
    this.setData({
      nicheng: cached.nicheng || this.data.nicheng || '',
      sjyue: cached.sjyue || this.data.sjyue || '0.00',
      fabu: cached.fadanzong ?? this.data.fabu ?? 0,
      tuikuan: cached.tuikuanzong ?? this.data.tuikuan ?? 0,
      jinriliushui: cached.riliushui || this.data.jinriliushui || '0.00',
      jinyueliushui: cached.yueliushui || this.data.jinyueliushui || '0.00',
      jinridingdan: cached.jinripaidan ?? this.data.jinridingdan ?? 0,
      jinrituikuan: cached.jinrituikuan ?? this.data.jinrituikuan ?? 0,
      chenghaoList: cached.chenghao_list || this.data.chenghaoList || [],
    });
  },

  async onPullDownRefresh() {
    if (this._pullRefreshing) return;
    this._pullRefreshing = true;
    this.setData({ scrollRefreshing: true });
    try {
      if (isStaffMode()) {
        await refreshStaffContext(request);
        await this.loadStaffProfile();
      } else {
        await this.getShangjiaInfo();
        await Promise.allSettled([this.loadPendingCount(), this.loadPunishPending()]);
      }
      syncStaffUi(this);
      wx.showToast({ title: '已更新', icon: 'success', duration: 1200 });
    } catch (e) {
      wx.showToast({ title: '刷新失败', icon: 'none' });
    } finally {
      this._pullRefreshing = false;
      this.setData({ scrollRefreshing: false });
    }
  },

  // 图片路径初始化
  setupImageUrls() {
    const ossBase = app.globalData.ossImageUrl || '';
    const imgDir = `${ossBase}beijing/shangjiaduan/`;
    this.setData({
      imgUrls: this.initImageUrls({
        pageBg: `${imgDir}page_bg.png`,
        avatarCardBg: `${imgDir}avatar_card_bg.png`,
        assetCardBg: `${imgDir}asset_card_bg.png`,
        statCardBg: `${imgDir}stat_card_bg.png`,
        funcItemBg: `${imgDir}func_item_bg.png`,
        primaryFuncBg: `${imgDir}primary_func_bg.png`,
        highlightFuncBg: `${imgDir}highlight_func_bg.png`,
        iconRelease: `${imgDir}icon_release.png`,
        iconFast: `${imgDir}icon_fast.png`,
        iconOrders: `${imgDir}icon_orders.png`,
        iconService: `${imgDir}icon_service.png`,
        iconPunish: `${imgDir}icon_punish.png`,
        iconRank: `${imgDir}icon_rank.png`,
        iconRecharge: `${imgDir}icon_recharge.png`,
        iconWithdraw: `${imgDir}icon_withdraw.png`,
        iconRefresh: `${imgDir}icon_refresh.png`,
        iconCopy: `${imgDir}icon_copy.png`,
        avatarFrame: `${imgDir}avatar_frame.png`,
        iconClear: `${ossBase}beijing/tubiao/grzx_qingchu.jpg`,
        iconSwitch: '/images/_exit.png',
      })
    });
  },

  // 商家状态检查（子客服与老板均可进入；子客服绝不走商家注册接口）
  checkRoleStatus() {
    try {
      const uid = wx.getStorageSync('uid');
      const portal = isMerchantPortalUser();
      const staffFlag = Number(wx.getStorageSync('staffstatus')) === 1;

      if (portal) {
        this.setData({ isShangjia: true, uid: uid || '', staffBooting: false, isLoading: false });
        syncStaffUi(this);
        if (isStaffMode()) {
          this.loadStaffProfile();
        } else if (Number(wx.getStorageSync('shangjiastatus')) === 1) {
          this.loadAvatar();
          this.getShangjiaInfo();
        } else if (staffFlag) {
          this.bootStaffPortal(uid);
        }
        ensureRoleOnCenterPage(this, 'shangjia');
        return;
      }

      if (staffFlag) {
        this.bootStaffPortal(uid);
        return;
      }

      this.setData({ isShangjia: false, staffBooting: false, isLoading: false });
      syncStaffUi(this);
    } catch (error) {
      console.error('读取商家状态失败', error);
      this.setData({ isShangjia: false, staffBooting: false, isLoading: false });
      syncStaffUi(this);
    }
  },

  /** 已绑定客服、尚未拉到 context 时恢复身份（不展示商家邀请码） */
  async bootStaffPortal(uid) {
    this.setData({ staffBooting: true, isLoading: true, uid: uid || '' });
    syncStaffUi(this);
    await restoreStaffContextAfterAuth();
    if (isMerchantPortalUser()) {
      this.setData({ isShangjia: true, staffBooting: false, isLoading: false });
      syncStaffUi(this);
      if (isStaffMode()) {
        await this.loadStaffProfile();
      }
      ensureRoleOnCenterPage(this, 'shangjia');
      return;
    }
    this.setData({ staffBooting: false, isLoading: false, isShangjia: false });
    syncStaffUi(this);
    wx.showToast({ title: '客服身份已失效，请联系商家老板', icon: 'none' });
  },

  onInviteCodeInput(e) {
    this.setData({ inviteCode: (e.detail.value || '').trim() });
  },

  goToStaffJoin() {
    wx.navigateTo({ url: '/pages/staff-join/staff-join' });
  },

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

  async loadStaffProfile() {
    const ctx = await refreshStaffContext(request);
    const profile = wx.getStorageSync('nicheng') || (ctx && ctx.display_name) || '商家客服';
    this.loadAvatar();
    this.setData({
      nicheng: (ctx && ctx.display_name) || profile,
      sjyue: (ctx && ctx.wallet && ctx.wallet.quota_available) || '0.00',
      chenghaoList: [],
      isLoading: false,
    });
    syncStaffUi(this);
    applyStaffStatsToPage(this, ctx);
  },

  // 获取商家信息（仅商家老板；子客服禁止调用）
  async getShangjiaInfo() {
    if (isStaffMode() || Number(wx.getStorageSync('staffstatus')) === 1) {
      return this.loadStaffProfile();
    }
    return this.loadData({
      url: '/yonghu/shangjiaxinxi',
      method: 'POST',
      successCode: 200,
      errorMsg: '获取商家信息失败',
      onSuccess: (data) => {
        // 更新全局缓存
        app.globalData.shangjia = data;
        wx.setStorageSync('shangjiastatus', 1);

        const chenghaoList = data.chenghao_list || [];

        this.setData({
          nicheng: data.nicheng || '',
          sjyue: data.sjyue || '0.00',
          fabu: data.fadanzong || 0,
          tuikuan: data.tuikuanzong || 0,
          jinriliushui: data.riliushui || '0.00',
          jinyueliushui: data.yueliushui || '0.00',
          jinridingdan: data.jinripaidan || 0,
          jinrituikuan: data.jinrituikuan || 0,
          chenghaoList: chenghaoList,
          isLoading: false,
        });

        if (this.data.isAutoRegistering) {
          this.setData({ isAutoRegistering: false });
          wx.showToast({ title: '商家注册成功', icon: 'success' });
        }
      },
    });
  },

  refreshShangjiaInfo() {
    if (isStaffMode()) {
      this.throttledRefresh(() => this.loadStaffProfile());
      return;
    }
    this.throttledRefresh(() => this.getShangjiaInfo());
  },

  async loadPendingCount() {
    try {
      const res = await request({
        url: isStaffMode() ? STAFF_API.orderList : '/dingdan/sjdingdanhq',
        method: 'POST',
        data: { zhuangtai_list: [8], page: 1, page_size: 1 },
      });
      if (res && res.data && (res.data.code === 0 || res.data.code === 200)) {
        this.setData({ pendingCount: res.data.data.pending_count || 0 });
      }
    } catch (e) {
      console.error('待结算数量失败', e);
    }
  },

  async loadPunishPending() {
    try {
      const res = await request({
        url: '/yonghu/sjcfjlhq',
        method: 'POST',
        data: { page: 1, page_size: 1, zhuangtai: 0 },
      });
      if (res && res.data && (res.data.code === 0 || res.data.code === 200)) {
        const d = res.data.data || {};
        this.setData({ punishPending: d.daichuli_count || d.pending_count || 0 });
      }
    } catch (e) {
      /* 接口字段未定时静默 */
    }
  },

  async onRegister() {
    const { inviteCode } = this.data;
    await this.registerWithInviteCode({
      inviteCode,
      apiUrl: '/yonghu/shangjiahuce',
      role: 'shangjia',
      statusKey: 'shangjiastatus',
      successMsg: '商家注册成功',
      onSuccess: (userData) => {
        app.globalData.shangjia = userData;
        const chenghaoList = userData.chenghao_list || [];
        this.setData({
          isShangjia: true,
          nicheng: userData.nicheng || '',
          sjyue: userData.sjyue || '0.00',
          fabu: userData.fabu || 0,
          tuikuan: userData.tuikuan || 0,
          jinriliushui: userData.jinriliushui || '0.00',
          jinyueliushui: userData.jinyueliushui || '0.00',
          jinridingdan: userData.jinridingdan || 0,
          chenghaoList: chenghaoList,
          isAutoRegistering: false,
        });
        this.loadAvatar();
        ensureRoleOnCenterPage(this, 'shangjia');
        lockPrimaryRole('shangjia');
      },
    });
  },

  previewAvatar() {
    if (this.data.avatarUrl) {
      wx.previewImage({ urls: [this.data.avatarUrl] });
    }
  },

  // 页面跳转
  goToPaiDan() { wx.navigateTo({ url: '/pages/merchant-dispatch/merchant-dispatch' }); },
  goToJiSuPaiDan() {
    wx.vibrateShort({ type: 'medium' });
    wx.navigateTo({ url: '/pages/express-order/express-order' });
  },
  goToMyOrders() { wx.redirectTo({ url: '/pages/merchant-orders/merchant-orders' }); },
  goToPendingOrders() { wx.redirectTo({ url: '/pages/merchant-orders/merchant-orders' }); },
  goToHome() { wx.redirectTo({ url: '/pages/merchant-home/merchant-home' }); },
  goToKefuKey() { wx.navigateTo({ url: '/pages/merchant-kefu-key/merchant-kefu-key' }); },
  goToKefuList() { wx.navigateTo({ url: '/pages/merchant-kefu-list/merchant-kefu-list' }); },
  goToAuditLog() { wx.navigateTo({ url: '/pages/merchant-staff-audit/merchant-staff-audit' }); },
  goToStaffRank() { wx.navigateTo({ url: '/pages/merchant-staff-audit/merchant-staff-audit?tab=rank' }); },
  goToRecharge() {
    if (!guardMerchantOwnerAction('子客服无法充值，请联系商家老板')) return;
    wx.navigateTo({ url: '/pages/merchant-recharge/merchant-recharge' });
  },
  goToWithdraw() {
    if (!guardMerchantOwnerAction('子客服无法提现，请联系商家老板')) return;
    wx.navigateTo({ url: '/pages/withdraw/withdraw' });
  },
  goToRanking() { wx.navigateTo({ url: '/pages/fighter-rank/fighter-rank?type=shangjia' }); },
  goToMessages() { wx.navigateTo({ url: '/pages/merchant-msg/merchant-msg' }); },
}, {
  roleConfig: {
    role: 'shangjia',
    statusKey: 'shangjiastatus',
    dataFlag: 'isShangjia',
    pageId: 'shangjiaduan',
    apiUrl: '/yonghu/shangjiaxinxi',
  },
}));
