import request from "@/api/request";
import {
  getPoolList,
  getGroups,
  createGroup,
  addMembersToGroup,
  type TrafficPoolGroup,
  type TrafficPoolMember,
  type PageResult,
} from "../api";

// 兼容旧版返回格式
export interface PoolListItem {
  id: number;
  identifier: string;
  nickname: string | null;
  avatar: string | null;
  phone: string | null;
  level: number;
  lifecycle: number;
  rfmR: number;
  rfmF: number;
  rfmM: number;
  rfmScore: number;
  totalMsgCount: number;
  totalOrderAmount: number;
  tags: string[];
}

export interface PoolListResult {
  list: PoolListItem[];
  total: number;
}

/**
 * 获取流量池列表 (V2)
 */
export async function fetchTrafficPoolList(params: {
  page?: number;
  pageSize?: number;
  keyword?: string;
}): Promise<PoolListResult> {
  try {
    const result = await getPoolList({
      page: params.page || 1,
      pageSize: params.pageSize || 10,
      keyword: params.keyword || "",
    });

    const list: PoolListItem[] = result.list.map(item => ({
      id: item.id,
      identifier: item.identifier,
      nickname: item.nickname,
      avatar: item.avatar,
      phone: item.phone || item.mobile || null,
      level: item.level,
      lifecycle: item.lifecycle,
      rfmR: item.rfmR,
      rfmF: item.rfmF,
      rfmM: item.rfmM,
      rfmScore: item.rfmScore?.total || 0,
      totalMsgCount: item.totalMsgCount,
      totalOrderAmount: item.totalOrderAmount,
      tags: item.tags?.map(t => t.tagName) || [],
    }));

    return {
      list,
      total: result.total,
    };
  } catch (error) {
    console.error("获取流量池列表失败:", error);
    throw error;
  }
}

/**
 * 获取获客场景列表
 */
export async function fetchScenarioOptions() {
  return request("/v1/plan/scenes", {}, "GET");
}

/**
 * 获取流量池分组选项 (V2)
 */
export async function fetchPackageOptions(): Promise<{
  list: Array<{ id: number; name: string; type: number; num: number }>;
  total: number;
}> {
  try {
    const groups = await getGroups();
    const list = groups.map((g: TrafficPoolGroup) => ({
      id: g.id,
      name: g.groupName,
      type: g.isSystem,
      num: g.memberCount || 0,
    }));
    return { list, total: list.length };
  } catch (error) {
    console.error("获取流量池分组选项失败:", error);
    throw error;
  }
}

/**
 * 创建分组或添加成员到分组 (V2)
 */
export async function addPackage(params: {
  type: string; // 类型 1搜索 2选择用户 3文件上传
  addPackageId?: number; // 要添加到的分组ID
  addStatus?: number;
  deviceId?: string;
  keyword?: string;
  packageId?: number;
  packageName?: string; // 添加的流量池名称
  tableFile?: number;
  taskId?: number;
  userIds?: number[]; // 要添加的用户ID列表
  userValue?: number;
}) {
  try {
    // 如果是添加成员到现有分组
    if (params.addPackageId && params.userIds && params.userIds.length > 0) {
      const result = await addMembersToGroup(params.addPackageId, params.userIds);
      return { success: true, count: result.count };
    }

    // 如果是创建新分组
    if (params.packageName) {
      const result = await createGroup({
        groupName: String(params.packageName),
        ruleType: 2, // 手动添加类型
      });

      // 如果有要添加的用户
      if (params.userIds && params.userIds.length > 0) {
        await addMembersToGroup(result.id, params.userIds);
      }

      return { success: true, id: result.id };
    }

    throw new Error("缺少必要参数");
  } catch (error) {
    console.error("创建分组或添加成员失败:", error);
    throw error;
  }
}

// 导出V2 API供直接使用
export {
  getGroups,
  createGroup,
  addMembersToGroup,
  removeMembersFromGroup,
  getPoolDetail,
  updatePool,
  getStatistics,
} from "../api";
