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';

const app = getApp();

/** 与订单页「全部」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: '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',
    },
    stats: {
      pendingCount: 0,
      pendingAmount: '0.00',
      todayDispatch: 0,
      todayRefund: 0,
    },
    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.waitForConfigAndLoadBanner();
    this.checkColdStartPopup('shangjiaduan');
  },

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

    this.registerNotificationComponent();
    // 先用本地缓存渲染，再向服务端同步子客服身份
    this.checkRole();
    syncStaffUi(this);
    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');
      this.loadDashboard();
    }
    this.loadBannerData();
  },

  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.loadBannerData(true);
      return;
    }
    setTimeout(() => this.waitForConfigAndLoadBanner(), 100);
  },

  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() {
    this.setData({ isShangjia: isMerchantPortalUser() });
  },

  loadBannerData(forceFetch) {
    const g = app.globalData || {};
    const cachedList = g.shangpinlunbo || [];
    if (!forceFetch && cachedList.length) {
      this.setData({
        lunboList: this.processImageUrls(cachedList),
        gonggao: g.shangpingonggao || '',
        lunbozhanwei: g.lunbozhanwei || this.data.lunbozhanwei,
      });
      return Promise.resolve();
    }
    if (!forceFetch && g.shangpingonggao) {
      this.setData({
        lunboList: this.processImageUrls(cachedList),
        gonggao: g.shangpingonggao,
      });
      return Promise.resolve();
    }
    const apiBase = g.apiBaseUrl || '';
    if (!apiBase) return Promise.resolve();
    return new Promise((resolve) => {
      wx.request({
        url: `${apiBase}/peizhi/shangpingonggao/`,
        method: 'POST',
        header: { 'content-type': 'application/json' },
        success: (res) => {
          if (res.statusCode === 200 && res.data) {
            const data = res.data;
            app.globalData.shangpingonggao = data.shangpingonggao || '';
            app.globalData.shangpinlunbo = data.shangpinlunbo || [];
            this.setData({
              lunboList: this.processImageUrls(app.globalData.shangpinlunbo),
              gonggao: app.globalData.shangpingonggao,
            });
          }
        },
        complete: resolve,
      });
    });
  },

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

  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 res = await request({
        url: isStaffMode() ? STAFF_API.orderList : '/dingdan/sjdingdanhq',
        method: 'POST',
        data: { zhuangtai_list: [8], page: 1, page_size: 20 },
      });
      if (res.data && (res.data.code === 0 || res.data.code === 200)) {
        const data = res.data.data || {};
        const list = data.list || [];
        let amount = 0;
        list.forEach((item) => {
          const v = parseFloat(item.jine || item.dingdan_jine || 0);
          if (!Number.isNaN(v)) amount += v;
        });
        this.setData({
          stats: {
            ...this.data.stats,
            pendingCount: data.pending_count != null ? data.pending_count : list.length,
            pendingAmount: amount.toFixed(2),
          },
        });
      }
    } catch (e) {
      console.error('待结算统计失败', e);
    }
  },

  /** 最近订单：同订单页「全部」筛选，取最新若干条 */
  async loadRecentOrders() {
    if (this.data.recentLoading) return;
    this.setData({ recentLoading: 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.setData({ recentLoading: false });
    }
  },

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

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

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

  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',
  },
}));
