import request from '@/utils/request';
import type { ApiResult, PageResult } from '@/api';
import { BaseUrl } from '@/config/app';

/**
 * 小程序码生成参数
 */
export interface MiniProgramCodeParam {
  // 小程序页面路径
  page?: string;
  // 场景值，最大32个可见字符
  scene: string;
  // 二维码宽度，单位 px，最小 280px，最大 1280px
  width?: number;
  // 是否检查页面是否存在
  checkPath?: boolean;
  // 环境版本
  envVersion?: 'release' | 'trial' | 'develop';
}

/**
 * 邀请关系参数
 */
export interface InviteRelationParam {
  // 邀请人ID
  inviterId: number;
  // 被邀请人ID
  inviteeId: number;
  // 邀请来源
  source: string;
  // 场景值
  scene?: string;
  // 邀请时间
  inviteTime?: string;
}

/**
 * 绑定推荐关系参数
 */
export interface BindRefereeParam {
  // 推荐人ID
  dealerId: number;
  // 被推荐人ID (可选，如果不传则使用当前登录用户)
  userId?: number;
  // 推荐来源
  source?: string;
  // 场景值
  scene?: string;
}

/**
 * 邀请统计数据
 */
export interface InviteStats {
  // 总邀请数
  totalInvites: number;
  // 成功注册数
  successfulRegistrations: number;
  // 转化率
  conversionRate: number;
  // 今日邀请数
  todayInvites: number;
  // 本月邀请数
  monthlyInvites: number;
  // 邀请来源统计
  sourceStats: InviteSourceStat[];
}

/**
 * 邀请来源统计
 */
export interface InviteSourceStat {
  source: string;
  count: number;
  successCount: number;
  conversionRate: number;
}

/**
 * 邀请记录
 */
export interface InviteRecord {
  id?: number;
  inviterId?: number;
  inviteeId?: number;
  inviterName?: string;
  inviteeName?: string;
  source?: string;
  scene?: string;
  status?: 'pending' | 'registered' | 'activated';
  inviteTime?: string;
  registerTime?: string;
  activateTime?: string;
}

/**
 * 邀请记录查询参数
 */
export interface InviteRecordParam {
  page?: number;
  limit?: number;
  inviterId?: number;
  status?: string;
  source?: string;
  startTime?: string;
  endTime?: string;
}

/**
 * 生成小程序码
 */
export async function generateMiniProgramCode(data: MiniProgramCodeParam) {
  try {
    const url = '/wx-login/getOrderQRCodeUnlimited/' + data.scene;
    // 由于接口直接返回图片buffer，我们直接构建完整的URL
    return `${BaseUrl}${url}`;
  } catch (error: any) {
    throw new Error(error.message || '生成小程序码失败');
  }
}

/**
 * 生成邀请小程序码
 */
export async function generateInviteCode(inviterId: number) {
  const scene = `uid_${inviterId}`;

  return generateMiniProgramCode({
    page: 'pages/index/index',
    scene: scene,
    width: 180,
    checkPath: true,
    envVersion: 'trial'
  });
}

/**
 * 建立邀请关系 (旧接口，保留兼容性)
 */
export async function createInviteRelation(data: InviteRelationParam) {
  const res = await request.post<ApiResult<unknown>>(
    '/invite/create-relation',
    data
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 绑定推荐关系 (新接口)
 */
export async function bindRefereeRelation(data: BindRefereeParam) {
  try {
    const res = await request.post<ApiResult<unknown>>(
      '/shop/shop-dealer-referee',
      {
        dealerId: data.dealerId,
        userId: data.userId,
        source: data.source || 'qrcode',
        scene: data.scene
      }
    );

    if (res.code === 0) {
      return res.data;
    }

    throw new Error(res.message || '绑定推荐关系失败');
  } catch (error: any) {
    console.error('绑定推荐关系API调用失败:', error);
    throw new Error(error.message || '绑定推荐关系失败');
  }
}

/**
 * 处理邀请场景值
 */
export async function processInviteScene(scene: string, userId: number) {
  const res = await request.post<ApiResult<unknown>>(
    '/invite/process-scene',
    { scene, userId }
  );
  if (res.code === 0) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 获取邀请统计数据
 */
export async function getInviteStats(inviterId: number) {
  const res = await request.get<ApiResult<InviteStats>>(
    `/invite/stats/${inviterId}`
  );
  if (res.code === 0) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 分页查询邀请记录
 */
export async function pageInviteRecords(params: InviteRecordParam) {
  const res = await request.get<ApiResult<PageResult<InviteRecord>>>(
    '/invite/records/page',
    params
  );
  if (res.code === 0) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 获取我的邀请记录
 */
export async function getMyInviteRecords(params: InviteRecordParam) {
  const res = await request.get<ApiResult<PageResult<InviteRecord>>>(
    '/invite/my-records',
    params
  );
  if (res.code === 0) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 验证邀请码有效性
 */
export async function validateInviteCode(scene: string) {
  const res = await request.post<ApiResult<{ valid: boolean; inviterId?: number; source?: string }>>(
    '/invite/validate-code',
    { scene }
  );
  if (res.code === 0) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 更新邀请状态
 */
export async function updateInviteStatus(inviteId: number, status: 'registered' | 'activated') {
  const res = await request.put<ApiResult<unknown>>(
    `/invite/update-status/${inviteId}`,
    { status }
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 获取邀请排行榜
 */
export async function getInviteRanking(params?: { limit?: number; period?: 'day' | 'week' | 'month' }) {
  const res = await request.get<ApiResult<Array<{
    inviterId: number;
    inviterName: string;
    inviteCount: number;
    successCount: number;
    conversionRate: number;
  }>>>(
    '/invite/ranking',
    params
  );
  if (res.code === 0) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}
