import { createPage, request, ensureRoleOnCenterPage } from '../../utils/base-page.js';
import { getOrderStatusText } from '../../utils/api-helper.js';
import {
  STAFF_API, isStaffMode, isMerchantPortalUser, refreshStaffContext, syncStaffUi,
  restoreStaffContextAfterAuth, applyStaffStatsToPage, getStaffContext,
} from '../../utils/staff-api.js';
import { ensurePhoneAuth } from '../../utils/phone-auth.js';
import { fetchGonggaoLunbo, isGonggaoCacheValid } from '../../utils/display-config';
import { ICON_KEYS, resolveMiniappIcon } from '../../utils/miniapp-icons.js';
import { fetchMerchantOrderStats, applyOrderStatsToHome } from '../../utils/merchant-order-stats.js';

const app = getApp();

const XYM_HOME_FALLBACK = {
  noticeIco: 'https://bintao.xmxym88.com/xcx/bintao/38.png',
  statCardBg: 'https://bintao.xmxym88.com/xcx/bintao/3.png',
  kefuKeyBtn: 'https://bintao.xmxym88.com/xcx/bintao/13.png',
  kefuListBtn: 'https://bintao.xmxym88.com/xcx/bintao/21.png',
  iconRegular: 'https://bintao.xmxym88.com/xcx/bintao/74.png',
  iconCustom: 'https://bintao.xmxym88.com/xcx/bintao/76.png',
};

/** 与订单页「全部」Tab 一致的状态筛选 */
const ALL_ORDER_ZHUANGTAI = [1, 2, 3, 4, 5, 6, 7, 8];
const RECENT_ORDER_SIZE = 5;

Page(createPage({
  data: {
    statusBar: 20,
    navBar: 44,
    isShangjia: false,
    isStaffMode: false,
    staffRoleName: '',
    quotaAvailable: '0.00',
    canDispatch: true,
    canStaffManage: true,
    lunboList: [],
    lunbozhanwei: '/images/lunbozhanwei.jpg',
    gonggao: '',
    swiperCurrent: 0,
    imgUrls: {
      noticeIco: XYM_HOME_FALLBACK.noticeIco,
      statCardBg: XYM_HOME_FALLBACK.statCardBg,
      kefuKeyBtn: XYM_HOME_FALLBACK.kefuKeyBtn,
      kefuListBtn: XYM_HOME_FALLBACK.kefuListBtn,
      iconRegular: XYM_HOME_FALLBACK.iconRegular,
      iconCustom: XYM_HOME_FALLBACK.iconCustom,
    },
    stats: {
      pendingCount: 0,
      pendingAmount: '0.00',
      todayDispatch: 0,
      todayRefund: 0,
      completedCount: 0,
      completedAmount: '0.00',
      refundCount: 0,
      refundAmount: '0.00',
      dispatchCount: 0,
      dispatchAmount: '0.00',
    },
    recentOrders: [],
    recentLoading: false,
  },

  async onLoad() {
    const sys = wx.getSystemInfoSync();
    this.setData({
      statusBar: sys.statusBarHeight || 20,
      navBar: (sys.statusBarHeight || 20) + 44,
      lunbozhanwei: app.globalData.lunbozhanwei || '/images/lunbozhanwei.jpg',
    });
    if (wx.getStorageSync('token')) {
      await restoreStaffContextAfterAuth();
    }
    this.checkRole();
    syncStaffUi(this);
    this.setupImageUrls();
    await this.waitForConfigAndLoadBanner();
    if (this.data.isShangjia) {
      await this.loadDashboard(false);
    }
    this._merchantHomeSessionReady = true;
    this._skipShowRefresh = true;
    this.checkColdStartPopup('shangjiaduan');
  },

  async onShow() {
    if (!app.globalData._shangjiaPhoneChecked) {
      const phoneOk = await ensurePhoneAuth({ redirect: true, role: 'shangjia' });
      if (!phoneOk) return;
      app.globalData._shangjiaPhoneChecked = true;
    }

    this.registerNotificationComponent();
    // 先用本地缓存渲染，再向服务端同步子客服身份
    this.checkRole();
    syncStaffUi(this);
    if (app.globalData.ossImageUrl || app.globalData.miniappIcons) {
      this.setupImageUrls();
    }
    const token = wx.getStorageSync('token');
    const isOwner = Number(wx.getStorageSync('shangjiastatus')) === 1;
    if (token && !isOwner) {
      await restoreStaffContextAfterAuth();
      this.checkRole();
      syncStaffUi(this);
    } else if (isStaffMode()) {
      await refreshStaffContext(request);
      this.checkRole();
      syncStaffUi(this);
      applyStaffStatsToPage(this, getStaffContext());
    }

    if (this.data.isShangjia) {
      ensureRoleOnCenterPage(this, 'shangjia');
    }
    if (app.startImWhenReady) app.startImWhenReady();

    if (this._skipShowRefresh) {
      this._skipShowRefresh = false;
      return;
    }

    const silent = this._merchantHomeSessionReady;
    if (this.data.isShangjia) {
      this.loadDashboard(silent);
    }
    if (silent) {
      this.loadBannerData(true, true);
    } else {
      this.loadBannerData(false);
    }
  },

  onPullDownRefresh() {
    Promise.all([
      this.loadBannerData(true),
      this.data.isShangjia ? this.loadDashboard() : Promise.resolve(),
    ]).finally(() => {
      wx.stopPullDownRefresh();
    });
  },

  waitForConfigAndLoadBanner() {
    if (app.globalData.ossImageUrl || app.globalData.apiBaseUrl) {
      this.setupImageUrls();
      return this.loadBannerData(true);
    }
    return new Promise((resolve) => {
      const tick = () => {
        if (app.globalData.ossImageUrl || app.globalData.apiBaseUrl) {
          this.setupImageUrls();
          this.loadBannerData(true).finally(resolve);
        } else {
          setTimeout(tick, 100);
        }
      };
      tick();
    });
  },

  setupImageUrls() {
    const ossBase = app.globalData.ossImageUrl || '';
    const homeDir = `${ossBase}beijing/shangjiaduan/home/`;
    const icon = (key, fallback) => resolveMiniappIcon(app, key, fallback);
    this.setData({
      imgUrls: {
        noticeIco: icon(ICON_KEYS.MERCHANT_HOME_NOTICE, XYM_HOME_FALLBACK.noticeIco),
        statCardBg: icon(ICON_KEYS.MERCHANT_HOME_STAT_BG, `${ossBase}beijing/shangjiaduan/stat_card_bg.png`) || XYM_HOME_FALLBACK.statCardBg,
        kefuKeyBtn: icon(ICON_KEYS.MERCHANT_HOME_KEFU_KEY, XYM_HOME_FALLBACK.kefuKeyBtn),
        kefuListBtn: icon(ICON_KEYS.MERCHANT_HOME_KEFU_LIST, XYM_HOME_FALLBACK.kefuListBtn),
        iconRegular: icon(ICON_KEYS.MERCHANT_HOME_REGULAR, XYM_HOME_FALLBACK.iconRegular),
        iconCustom: icon(ICON_KEYS.MERCHANT_HOME_CUSTOM, XYM_HOME_FALLBACK.iconCustom),
      },
    });
  },

  processImageUrls(urlList) {
    if (!urlList || !Array.isArray(urlList)) return [];
    const oss = app.globalData.ossImageUrl || '';
    return urlList.map((url) => (url && url.startsWith('http') ? url : oss + url));
  },

  checkRole() {
    syncStaffUi(this);
  },

  loadBannerData(forceFetch, silent) {
    const g = app.globalData || {};
    const cachedList = g.shangpinlunbo || [];
    if (!forceFetch && isGonggaoCacheValid(app) && cachedList.length) {
      this.setData({
        lunboList: this.processImageUrls(cachedList),
        gonggao: g.shangpingonggao || '',
        lunbozhanwei: g.lunbozhanwei || this.data.lunbozhanwei,
      });
      return Promise.resolve();
    }
    return fetchGonggaoLunbo(app, 'merchant_home').then((data) => {
      if (!data) return;
      this.setData({
        lunboList: this.processImageUrls(app.globalData.shangpinlunbo),
        gonggao: app.globalData.shangpingonggao || '',
      });
    }).catch(() => {});
  },

  async loadDashboard(silent = false) {
    await Promise.all([
      this.loadShangjiaBrief(),
      this.loadPendingStats(),
      this.loadRecentOrders(silent),
    ]);
  },

  async loadShangjiaBrief() {
    if (isStaffMode()) {
      const ctx = await refreshStaffContext(request);
      syncStaffUi(this);
      applyStaffStatsToPage(this, ctx);
      return;
    }
    try {
      const res = await request({
        url: '/yonghu/shangjiaxinxi',
        method: 'POST',
      });
      if (res.data && res.data.code === 200) {
        const d = res.data.data || {};
        app.globalData.shangjia = d;
        this.setData({
          stats: {
            ...this.data.stats,
            todayDispatch: d.jinripaidan || 0,
            todayRefund: d.jinrituikuan || 0,
          },
        });
      }
    } catch (e) {
      console.error('商家信息加载失败', e);
    }
  },

  async loadPendingStats() {
    try {
      const data = await fetchMerchantOrderStats(request, {});
      applyOrderStatsToHome(this, data);
    } catch (e) {
      console.warn('待结算统计失败', e);
    }
  },

  /** 最近订单：同订单页「全部」筛选，取最新若干条 */
  async loadRecentOrders(silent = false) {
    if (this.data.recentLoading && !silent) return;
    if (silent && this._recentOrdersRequesting) return;
    if (!silent) {
      this.setData({ recentLoading: true });
    }
    this._recentOrdersRequesting = true;
    try {
      const res = await request({
        url: isStaffMode() ? STAFF_API.orderList : '/dingdan/sjdingdanhq',
        method: 'POST',
        data: {
          zhuangtai_list: ALL_ORDER_ZHUANGTAI,
          page: 1,
          page_size: RECENT_ORDER_SIZE,
        },
      });
      if (res.data && (res.data.code === 0 || res.data.code === 200)) {
        const oss = app.globalData.ossImageUrl || '';
        const list = (res.data.data.list || []).map((item) => {
          let tupian = item.tupian || '';
          if (tupian && !tupian.startsWith('http')) {
            tupian = oss + tupian;
          }
          const raw = { ...item, tupian };
          return {
            dingdan_id: item.dingdan_id,
            title: item.jieshao || '暂无描述',
            time: item.create_time || item.CreateTime || '',
            status: getOrderStatusText(item.zhuangtai),
            money: item.jine || '0.00',
            raw,
          };
        });
        this.setData({ recentOrders: list });
      }
    } catch (e) {
      console.error('最近订单加载失败', e);
    } finally {
      this._recentOrdersRequesting = false;
      if (!silent) {
        this.setData({ recentLoading: false });
      }
    }
  },

  onSwiperChange(e) {
    this.setData({ swiperCurrent: e.detail.current });
  },

  goRegularDispatch() {
    wx.navigateTo({ url: '/pages/merchant-regular-dispatch/merchant-regular-dispatch' });
  },

  goLinkDispatch() {
    wx.navigateTo({ url: '/pages/express-order/express-order' });
  },

  goCustomDispatch() {
    wx.navigateTo({ url: '/pages/merchant-dispatch/merchant-dispatch' });
  },

  goDispatch() {
    this.goCustomDispatch();
  },

  goExpress() {
    this.goLinkDispatch();
  },

  goOrdersTab() {
    wx.redirectTo({ url: '/pages/merchant-orders/merchant-orders' });
  },

  goPendingOrders() {
    wx.redirectTo({ url: '/pages/merchant-orders/merchant-orders' });
  },

  goOrderDetail(e) {
    const index = e.currentTarget.dataset.index;
    const row = this.data.recentOrders[index];
    if (!row || !row.raw) return;
    const dataStr = encodeURIComponent(JSON.stringify(row.raw));
    wx.navigateTo({
      url: `/pages/merchant-order-detail/merchant-order-detail?dingdanData=${dataStr}`,
    });
  },

  goKefuKey() {
    wx.navigateTo({ url: '/pages/merchant-kefu-key/merchant-kefu-key' });
  },

  goKefuList() {
    wx.navigateTo({ url: '/pages/merchant-kefu-list/merchant-kefu-list' });
  },

  goMerchantProfile() {
    wx.redirectTo({ url: '/pages/merchant/merchant' });
  },

  goRegister() {
    wx.redirectTo({ url: '/pages/merchant/merchant' });
  },
}, {
  roleConfig: {
    role: 'shangjia',
    statusKey: 'shangjiastatus',
    dataFlag: 'isShangjia',
    pageId: 'shangjiaduan',
  },
}));
