import request from '../../utils/request.js';
import { STAFF_API } from '../../utils/staff-api.js';

const ORDER_AUDIT_ACTIONS = [
  'DISPATCH', 'LINK_GENERATE', 'SETTLE', 'CANCEL', 'REFUND_APPLY',
  'CHANGE_PLAYER', 'PENALTY_APPLY', 'PENALTY_MANAGE',
];

Page({
  data: {
    tab: 'audit',
    auditList: [],
    rankList: [],
    page: 1,
    hasMore: true,
    loading: false,
    total: 0,
  },

  onLoad(options) {
    if (options.tab === 'rank') this.setData({ tab: 'rank' });
    wx.setNavigationBarTitle({
      title: options.tab === 'rank' ? '客服排行' : '操作日志',
    });
    this.loadData(true);
  },

  onPullDownRefresh() {
    this.loadData(true).finally(() => wx.stopPullDownRefresh());
  },

  onReachBottom() {
    if (this.data.tab === 'audit' && this.data.hasMore && !this.data.loading) {
      this.loadAudit(false);
    }
  },

  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    wx.setNavigationBarTitle({ title: tab === 'rank' ? '客服排行' : '操作日志' });
    this.setData({ tab, page: 1, hasMore: true }, () => this.loadData(true));
  },

  loadData(reset) {
    if (this.data.tab === 'audit') return this.loadAudit(reset);
    return this.loadRank();
  },

  async loadAudit(reset) {
    if (this.data.loading) return;
    const page = reset ? 1 : this.data.page;
    this.setData({ loading: true });
    try {
      const res = await request({
        url: STAFF_API.auditList,
        method: 'POST',
        data: { page, page_size: 20 },
      });
      if (res.data && res.data.code === 0) {
        const d = res.data.data || {};
        const list = (d.list || []).map((item) => ({
          ...item,
          canJumpOrder: ORDER_AUDIT_ACTIONS.indexOf(item.action) >= 0 && !!item.resource_id,
        }));
        this.setData({
          auditList: reset ? list : [...this.data.auditList, ...list],
          page: page + 1,
          hasMore: !!d.has_more,
          total: d.total || 0,
          loading: false,
        });
      } else {
        this.setData({ loading: false });
        wx.showToast({ title: res.data?.msg || '加载失败', icon: 'none' });
      }
    } catch (e) {
      this.setData({ loading: false });
    }
  },

  async loadRank() {
    const res = await request({
      url: STAFF_API.rank,
      method: 'POST',
      data: { period: 'month', sort_by: 'dispatch_count' },
    });
    if (res.data && res.data.code === 0) {
      this.setData({ rankList: (res.data.data && res.data.data.list) || [] });
    }
  },

  goOrderDetail(e) {
    const item = e.currentTarget.dataset.item;
    if (!item || !item.canJumpOrder || !item.resource_id) return;
    wx.navigateTo({
      url: `/pages/merchant-order-detail/merchant-order-detail?dingdan_id=${encodeURIComponent(item.resource_id)}`,
    });
  },
});
