// pages/shenhedating/shenhedating.js
const app = getApp();
import request from '../../utils/request.js';

Page({
  data: {
    // 模块列表 [{bankuai_id, mingcheng, count, is_related}]
    moduleList: [],
    xuanzhongBankuaiId: 0,        // 0代表全部
    // 审核记录列表
    recordList: [],
    page: 1,
    pageSize: 5,
    hasMore: true,
    isLoading: false,
    isLoadingMore: false,
    scrollViewRefreshing: false,
    lastRefreshTime: 0,
    refreshCooldown: 2000,
    // 弹窗控制
    showRuleModal: false,
    currentRuleContent: '',
    showBeizhuModal: false,
    currentBeizhuContent: '',
    // 加载状态
    loadingModules: false
  },

  onLoad() {
    this.loadModules();
  },

  onShow() {
    this.registerNotificationComponent();
  },

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

  // 加载板块模块
  async loadModules() {
    this.setData({ loadingModules: true });
    try {
      const res = await request({ url: '/dengji/shdthqmk', method: 'POST' });
      if (res && res.data.code === 0) {
        const modules = res.data.data.modules || [];
        this.setData({ moduleList: modules, xuanzhongBankuaiId: 0 });
        this.loadRecords(true);
      } else {
        wx.showToast({ title: '加载模块失败', icon: 'none' });
      }
    } catch (e) {
      wx.showToast({ title: '网络错误', icon: 'none' });
    } finally {
      this.setData({ loadingModules: false });
    }
  },

  // 选择模块（含全部）
  selectModule(e) {
    const bankuaiId = e.currentTarget.dataset.id;
    if (bankuaiId === this.data.xuanzhongBankuaiId) return;
    this.setData({
      xuanzhongBankuaiId: bankuaiId,
      recordList: [],
      page: 1,
      hasMore: true
    });
    this.loadRecords(true);
  },

  // 加载审核记录
  async loadRecords(isRefresh = false) {
    if (this.data.isLoading) return;
    const page = isRefresh ? 1 : this.data.page;
    if (!isRefresh && !this.data.hasMore) return;

    this.setData({ isLoading: true, isLoadingMore: !isRefresh });

    try {
      const res = await request({
        url: '/dengji/hqshsj',
        method: 'POST',
        data: {
          bankuai_id: this.data.xuanzhongBankuaiId || undefined,
          page: page,
          page_size: this.data.pageSize
        }
      });

      this.setData({ isLoading: false, isLoadingMore: false, scrollViewRefreshing: false });

      if (res && res.data.code === 0) {
        const list = res.data.data.list || [];
        const hasMore = res.data.data.has_more;
        const ossUrl = app.globalData.ossImageUrl || '';
        const processedList = list.map(item => {
          let avatar = item.shenqingren_avatar || '';
          if (avatar && !avatar.startsWith('http')) {
            avatar = ossUrl + avatar;
          }
          return { ...item, shenqingren_avatar: avatar };
        });
        const newList = isRefresh ? processedList : [...this.data.recordList, ...processedList];
        this.setData({ recordList: newList, page: page + 1, hasMore: hasMore });
        if (isRefresh) this.setData({ lastRefreshTime: Date.now() });
      } else {
        wx.showToast({ title: '加载记录失败', icon: 'none' });
      }
    } catch (e) {
      this.setData({ isLoading: false, isLoadingMore: false, scrollViewRefreshing: false });
      wx.showToast({ title: '网络错误', icon: 'none' });
    }
  },

  // 上拉加载更多
  onReachBottom() {
    const now = Date.now();
    if (now - this.data.lastRefreshTime < this.data.refreshCooldown ||
        this.data.isLoading || this.data.isLoadingMore) return;
    if (this.data.hasMore) {
      this.loadRecords(false);
    }
  },

  // 下拉刷新
  onPullDownRefresh() {
    const now = Date.now();
    if (now - this.data.lastRefreshTime < this.data.refreshCooldown || this.data.isLoading) {
      this.setData({ scrollViewRefreshing: false });
      return;
    }
    this.setData({ scrollViewRefreshing: true, lastRefreshTime: now, page: 1, hasMore: true });
    this.loadRecords(true);
  },

  // 查看规则详情
  showRuleDetail(e) {
    const content = e.currentTarget.dataset.content;
    this.setData({ showRuleModal: true, currentRuleContent: content });
  },
  hideRuleDetail() {
    this.setData({ showRuleModal: false, currentRuleContent: '' });
  },

  // 查看备注详情
  showBeizhuDetail(e) {
    const content = e.currentTarget.dataset.content;
    this.setData({ showBeizhuModal: true, currentBeizhuContent: content || '无' });
  },
  hideBeizhuDetail() {
    this.setData({ showBeizhuModal: false, currentBeizhuContent: '' });
  },

  // 抢单
  async onShouShen(e) {
    const jiluId = e.currentTarget.dataset.jiluid;
    const bankuaiId = e.currentTarget.dataset.bankuaiid;
    if (!jiluId) {
      wx.showToast({ title: '记录ID异常，无法接单', icon: 'none' });
      return;
    }

    const that = this;
    wx.showModal({
      title: '确认审核',
      content: '确定要审核此用户吗？审核后请前往游戏进行审核，并严格评分。',
      confirmColor: '#c9a558',
      success: async (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '接单中...', mask: true });
          try {
            const qdRes = await request({
              url: '/dengji/shqd',
              method: 'POST',
              data: { jilu_id: jiluId }
            });
            if (qdRes && qdRes.data.code === 0) {
              // 抢单成功，弹出联系打手弹窗
              wx.showModal({
                title: '接待成功',
                content: '请认真考核，点击联系他查看打手信息并打分。',
                showCancel: false,
                confirmText: '联系他',
                confirmColor: '#c9a558',
                success: (modalRes) => {
                  if (modalRes.confirm) {
                    wx.navigateTo({
                      url: '/pages/kaohe_dafen/kaohe_dafen?jilu_id=' + jiluId
                    });
                  }
                }
              });
              const newList = that.data.recordList.filter(r => r.jilu_id !== jiluId);
              that.setData({ recordList: newList });
              // 对应板块待审核数减1
              const bkId = qdRes.data.data ? qdRes.data.data.bankuai_id : bankuaiId;
              if (bkId) {
                const newModules = that.data.moduleList.map(m => {
                  if (m.bankuai_id === bkId && m.count > 0) {
                    return { ...m, count: m.count - 1 };
                  }
                  return m;
                });
                that.setData({ moduleList: newModules });
              }
            } else {
              const errMsg = qdRes?.data?.msg || '接单失败，请重试';
              wx.showModal({
                title: '接单失败',
                content: errMsg,
                showCancel: false,
                confirmText: '知道了',
                confirmColor: '#c9a558'
              });
            }
          } catch (e) {
            wx.showModal({
              title: '提示',
              content: '网络错误，请重试',
              showCancel: false,
              confirmText: '知道了'
            });
          } finally {
            wx.hideLoading();
          }
        }
      }
    });
  },

  noop() {}
});