// pages/shangjiazhongxin/shangjiazhongxin.js
// 🏪 商家中心 - 完全重构版 | 背景图全覆盖 | 称号从商家接口获取

import request from '../../utils/request.js';
import popupService from '../../services/popupService.js';

const app = getApp();

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

    // ========== 商家状态 ==========
    isShangjia: false,
    isLoading: 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: '',
    lastRefreshTime: 0,
    canRefresh: true,
  },

  onLoad(options) {
    this.initImageUrls();
    this.checkShangjiaStatus();

    const { inviteCode } = options || {};
    if (inviteCode) {
      this.setData({ inviteCode });
      setTimeout(() => this.handleInviteCodeWithLoginCheck(inviteCode), 500);
    }

    if (!app.globalData.hasShownPopupOnColdStart) {
      app.globalData.hasShownPopupOnColdStart = true;
      setTimeout(() => popupService.checkAndShow(this, 'shangjiaduan'), 300);
    }
  },

  onShow() {
    this.registerNotificationComponent();
    if (this.data.isShangjia) {
      this.refreshShangjiaInfo();   // 刷新时从商家接口获取所有数据（含称号）
    }
  },

  onHide() {
    const popupComp = this.selectComponent('#popupNotice');
    popupComp?.cleanup?.();
  },

  // ========== 图片路径初始化 ==========
  initImageUrls() {
    const ossBase = app.globalData.ossImageUrl || '';
    const imgDir = `${ossBase}beijing/shangjiaduan/`;
    this.setData({
      imgUrls: {
        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`,
      }
    });
  },

  // ========== 商家状态检查 ==========
  checkShangjiaStatus() {
    try {
      const shangjiastatus = wx.getStorageSync('shangjiastatus');
      const uid = wx.getStorageSync('uid');
      if (shangjiastatus === 1) {
        this.setData({ isShangjia: true, uid: uid || '' });
        this.loadAvatar();
        this.getShangjiaInfo();   // 获取完整商家数据（含称号）
      } else {
        this.setData({ isShangjia: false });
      }
    } catch (error) {
      console.error('读取商家状态失败', error);
      this.setData({ isShangjia: false });
    }
  },

  loadAvatar() {
    const { ossImageUrl = '', morentouxiang = 'avatar/default.jpg' } = app.globalData || {};
    const touxiang = wx.getStorageSync('touxiang') || '';
    let avatarUrl = '';
    if (touxiang) {
      avatarUrl = ossImageUrl + (touxiang.startsWith('/') ? touxiang : '/' + touxiang);
    } else {
      avatarUrl = ossImageUrl + (morentouxiang.startsWith('/') ? morentouxiang : '/' + morentouxiang);
    }
    this.setData({ avatarUrl });
  },

  // ========== 获取商家信息（核心接口，包含称号列表）==========
  async getShangjiaInfo() {
    this.setData({ isLoading: true });
    try {
      const res = await request({ url: '/yonghu/shangjiaxinxi', method: 'POST' });
      if (res?.data?.code === 200) {
        const data = res.data.data;
        // 更新全局缓存
        app.globalData.shangjia = data;
        wx.setStorageSync('shangjiastatus', 1);
        
        // 称号列表：优先使用接口返回的 chenghao_list，若无则空数组
        const chenghaoList = data.chenghao_list || [];
        
        // ✅ 字段映射：后端返回字段 → 前端 data 字段（只改这里，其他一律不变）
        this.setData({
          nicheng: data.nicheng || '',                      // 商家昵称（后端如有则显示）
          sjyue: data.sjyue || '0.00',                      // 商家余额
          fabu: data.fadanzong || 0,                        // 发单总量（后端 fadanzong）
          tuikuan: data.tuikuanzong || 0,                   // 退款总量（后端 tuikuanzong）
          jinriliushui: data.riliushui || '0.00',           // 今日流水（后端 riliushui）
          jinyueliushui: data.yueliushui || '0.00',         // 今月流水（后端 yueliushui）
          jinridingdan: data.jinripaidan || 0,              // 今日派单数（后端 jinripaidan）
          jinrituikuan: data.jinrituikuan || 0,             // 今日退款数（后端 jinrituikuan）
          chenghaoList: chenghaoList,
          isLoading: false,
        });
        
        if (this.data.isAutoRegistering) {
          this.setData({ isAutoRegistering: false });
          wx.showToast({ title: '商家注册成功', icon: 'success' });
        }
      } else {
        throw new Error(res?.data?.msg || '获取商家信息失败');
      }
    } catch (error) {
      console.error('获取商家信息失败', error);
      this.setData({ isLoading: false });
      wx.showToast({ title: error.message || '加载失败', icon: 'none' });
    }
  },

  refreshShangjiaInfo() {
    const now = Date.now();
    if (!this.data.canRefresh || now - this.data.lastRefreshTime < 3000) {
      wx.showToast({ title: '操作过快', icon: 'none' });
      return;
    }
    this.setData({ lastRefreshTime: now, canRefresh: false });
    this.getShangjiaInfo();   // 刷新时重新获取所有数据
    setTimeout(() => this.setData({ canRefresh: true }), 3000);
  },

  // ========== 邀请码注册 ==========
  handleInviteCodeWithLoginCheck(inviteCode) {
    const token = wx.getStorageSync('token');
    const uid = wx.getStorageSync('uid');
    if (!token || !uid) {
      wx.reLaunch({
        url: `/pages/gerenzhongxin/gerenzhongxin?autoLogin=true&inviteCode=${inviteCode}&redirect=/pages/shangjiazhongxin/shangjiazhongxin&type=shangjia`
      });
    } else {
      if (!this.data.isShangjia) {
        wx.showLoading({ title: '商家注册中...', mask: true });
        this.setData({ isAutoRegistering: true });
        this.onRegister();
      } else {
        wx.showToast({ title: '您已是商家', icon: 'success' });
      }
    }
  },

  async onRegister() {
    const { inviteCode } = this.data;
    if (!inviteCode) {
      wx.showToast({ title: '请输入邀请码', icon: 'none' });
      return;
    }
    if (inviteCode.length > 100) {
      wx.showToast({ title: '邀请码不能超过100字符', icon: 'none' });
      return;
    }
    this.setData({ isLoading: true });
    try {
      const res = await request({
        url: '/yonghu/shangjiahuce',
        method: 'POST',
        data: { inviteCode }
      });
      if (res?.data?.code === 200) {
        wx.setStorageSync('shangjiastatus', 1);
        const data = res.data.data;
        app.globalData.shangjia = data;
        const chenghaoList = data.chenghao_list || [];
        this.setData({
          isShangjia: true,
          nicheng: data.nicheng || '',
          sjyue: data.sjyue || '0.00',
          fabu: data.fabu || 0,
          tuikuan: data.tuikuan || 0,
          jinriliushui: data.jinriliushui || '0.00',
          jinyueliushui: data.jinyueliushui || '0.00',
          jinridingdan: data.jinridingdan || 0,
          chenghaoList: chenghaoList,
          isLoading: false,
          isAutoRegistering: false,
        });
        this.loadAvatar();
        wx.showToast({ title: '商家注册成功', icon: 'success' });
      } else {
        throw new Error(res?.data?.msg || '注册失败');
      }
    } catch (error) {
      console.error('商家注册失败', error);
      this.setData({ isLoading: false, isAutoRegistering: false });
      wx.showToast({ title: error.message, icon: 'error' });
    }
  },

  // ========== 辅助功能 ==========
  registerNotificationComponent() {
    const notificationComp = this.selectComponent('#global-notification');
    if (notificationComp?.showNotification) {
      app.globalData.globalNotification = {
        show: (data) => notificationComp.showNotification(data),
        hide: () => notificationComp.hideNotification()
      };
    }
  },

  copyUid() {
    if (!this.data.uid) {
      wx.showToast({ title: 'UID不存在', icon: 'none' });
      return;
    }
    wx.setClipboardData({
      data: this.data.uid,
      success: () => wx.showToast({ title: 'UID已复制', icon: 'success' }),
      fail: () => wx.showToast({ title: '复制失败', icon: 'error' })
    });
  },

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

  // ========== 页面跳转 ==========
  goToPaiDan() { wx.navigateTo({ url: '/pages/sjpaidan/sjpaidan' }); },
  goToJiSuPaiDan() { 
    wx.vibrateShort({ type: 'medium' });
    wx.navigateTo({ url: '/pages/jisufd/jisufd' });
  },
  goToMyOrders() { wx.navigateTo({ url: '/pages/sjdingdan/sjdingdan' }); },
  goToRecharge() { wx.navigateTo({ url: '/pages/sjchongzhi/sjchongzhi' }); },
  goToWithdraw() { wx.navigateTo({ url: '/pages/tixian/tixian' }); },
  goToRanking() { wx.navigateTo({ url: '/pages/sjpaihang/sjpaihang' }); },
  goToMessages() { wx.navigateTo({ url: '/pages/sjxiaoxi/sjxiaoxi' }); },
  goToKefu() {
    const { kefuConfig } = app.globalData;
    if (kefuConfig?.link && kefuConfig?.enterpriseId) {
      wx.openCustomerServiceChat({
        extInfo: { url: kefuConfig.link },
        corpId: kefuConfig.enterpriseId,
        fail: () => wx.showToast({ title: '客服暂不可用', icon: 'none' })
      });
    } else {
      wx.showToast({ title: '客服配置未加载', icon: 'none' });
    }
  },
});