// pages/shangjiazhongxin/shangjiiazhongxin.js

import { createPage, ensureRoleOnCenterPage, lockPrimaryRole, parseSceneOptions } from '../../utils/base-page.js';
import { ensureLogin } from '../../utils/login.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,
    isAutoRegistering: false,

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

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

    // 交互控制
    inviteCode: '',
  },

  onLoad(options) {
    const parsed = parseSceneOptions(options);
    this.setupImageUrls();
    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');
  },

  onShow() {
    this.registerNotificationComponent();
    if (this.data.isShangjia) {
      ensureRoleOnCenterPage(this, 'shangjia');
      this.refreshShangjiaInfo();
    }
  },

  // 图片路径初始化
  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，增加 getShangjiaInfo 调用）
  checkRoleStatus() {
    try {
      const shangjiastatus = wx.getStorageSync('shangjiastatus');
      const uid = wx.getStorageSync('uid');
      if (shangjiastatus) {
        this.setData({ isShangjia: true, uid: uid || '' });
        this.loadAvatar();
        this.getShangjiaInfo();
        ensureRoleOnCenterPage(this, 'shangjia');
      } else {
        this.setData({ isShangjia: false });
      }
    } catch (error) {
      console.error('读取商家状态失败', error);
      this.setData({ isShangjia: false });
    }
  },

  // 获取商家信息
  async getShangjiaInfo() {
    await 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() {
    this.throttledRefresh(() => this.getShangjiaInfo());
  },

  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.navigateTo({ url: '/pages/merchant-orders/merchant-orders' }); },
  goToRecharge() { wx.navigateTo({ url: '/pages/merchant-recharge/merchant-recharge' }); },
  goToWithdraw() { 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',
  },
}));
