import request from "@/api/request";
import { createGroup, type RuleCondition, type RuleConfig } from "../api";

// 创建流量包
export interface CreateTrafficPackageParams {
  groupName: string;
  description?: string;
  groupIcon?: string;
  groupColor?: string;
  ruleType: number; // 1=动态规则，2=手动添加
  ruleConfig?: RuleConfig;
  memberIds?: number[]; // 手动添加时的成员ID列表
}

export interface CreateTrafficPackageResponse {
  id: number;
  groupName: string;
}

export async function createTrafficPackage(
  params: CreateTrafficPackageParams,
): Promise<CreateTrafficPackageResponse> {
  // 调用V2接口创建分组
  return createGroup(params);
}

// 获取用户列表（根据筛选条件）
export interface GetUsersByFilterParams {
  ruleConfig: RuleConfig & { keyword?: string };
  page?: number;
  pageSize?: number;
}

export interface User {
  id: number;
  identifier: string;
  nickname: string | null;
  avatar: string | null;
  wechatId: string | null;
  wechatAlias: string | null;
  phone: string | null;
  region: string;
  gender: number;
  rfmScore: {
    R: number;
    F: number;
    M: number;
    total: number;
  };
  tags: string[];
  lastInteractTime: number;
  totalMsgCount: number;
  totalOrderAmount: string;
  lifecycle: number;
  intentionLevel: number;
}

export interface GetUsersByFilterResponse {
  list: User[];
  total: number;
  page: number;
  pageSize: number;
}

export async function getUsersByFilter(
  params: GetUsersByFilterParams,
): Promise<GetUsersByFilterResponse> {
  // 使用 POST 请求，因为 ruleConfig 是复杂对象
  return request("/v1/traffic/pool/v2/preview-users", params, "POST");
}

// 获取预设方案列表（基于系统分组）
export interface PresetScheme {
  id: string;
  name: string;
  description: string;
  conditions: any[];
  userCount: number;
  color: string;
}

export async function getPresetSchemes(): Promise<PresetScheme[]> {
  try {
    // 获取所有分组作为推荐方案
    const groups = await request("/v1/traffic/pool/v2/groups", {}, "GET");

    // 去重（根据 id）并过滤掉没有规则配置的分组
    const uniqueGroups: any[] = [];
    const seenIds = new Set<number>();

    for (const group of groups) {
      if (!seenIds.has(group.id)) {
        seenIds.add(group.id);
        uniqueGroups.push(group);
      }
    }

    // 转换为PresetScheme格式，优先显示系统分组
    const sortedGroups = uniqueGroups.sort((a: any, b: any) => {
      // 系统分组排前面
      if (a.isSystem !== b.isSystem) return b.isSystem - a.isSystem;
      // 同类型按 id 排序
      return a.id - b.id;
    });

    return sortedGroups.map((group: any) => ({
      id: String(group.id),
      name: group.groupName,
      description: group.description || (group.isSystem ? `系统预设：${group.groupName}` : `自定义：${group.groupName}`),
      conditions: group.ruleConfig?.conditions || [],
      userCount: group.memberCount || 0,
      color: group.groupColor || (group.isSystem ? "#1677ff" : "#52c41a"),
    }));
  } catch (error) {
    console.error("获取预设方案失败:", error);
    // 返回空数组或默认方案
    return [];
  }
}

// 获取筛选字段元数据
export interface FilterField {
  field: string;
  label: string;
  type: 'select' | 'input' | 'number' | 'province' | 'friend_search';
  options?: { label: string; value: any }[];
  placeholder?: string;
}

export async function getFilterFields(): Promise<FilterField[]> {
  return request("/v1/traffic/pool/v2/filter-fields", {}, "GET");
}

// 兼容旧接口名称
export async function getIndustryOptions(): Promise<FilterField[]> {
  return getFilterFields();
}
