// utils/imAuth/dashoujianquan.js
const imRequest = require('./imRequest.js');

/**
 * 打手 IM 权限检测
 * POST /yonghu/dshqltqx
 * 后端返回 { code: 0, allow: 1 } 或 { code: 0, allow: 0 }
 */
async function dashoujianquan(app) {
  const uid = wx.getStorageSync('uid');
  if (!uid) return { allowed: false, reason: '未登录' };

  try {
    const res = await imRequest({
      url: '/yonghu/dshqltqx',
      method: 'POST',
      data: { uid }
    });

    if (res && res.data && res.data.code === 0) {
      const allow = res.data.allow;
      if (allow === 1) {
        return { allowed: true };
      } else {
        await app.disconnectGoEasy();
        wx.showToast({
          title: '当前身份已不支持消息聊天功能，请充值会员或联系管理员后尝试',
          icon: 'none',
          duration: 2000,
          mask: true
        });
        await new Promise(r => setTimeout(r, 2100));
        return { allowed: false, reason: '打手消息权限被限制' };
      }
    }
    throw new Error(res.data?.msg || '鉴权接口异常');
  } catch (err) {
    console.error('打手鉴权失败:', err);
    await app.disconnectGoEasy();
    wx.showToast({
      title: '消息服务暂不可用，请稍后重试',
      icon: 'none',
      duration: 2000,
      mask: true
    });
    await new Promise(r => setTimeout(r, 2100));
    return { allowed: false, reason: '鉴权请求失败' };
  }
}

module.exports = { dashoujianquan };