import request from "@/api/request";
import {
  getGroups as getGroupsV2,
  deleteGroup as deleteGroupV2,
  type TrafficPoolGroup,
} from "../api";

// 兼容旧版 Package 接口
export interface Package {
  id: number;
  name: string;
  description: string;
  pic: string;
  type: number; // 0=自定义，1=系统
  createTime: string;
  num: number;
  R: number;
  F: number;
  M: number;
  RFM: number;
}

export interface PackageList {
  list: Package[];
  total: number;
}

/**
 * 获取流量池分组列表 (V2)
 * 转换为旧版 Package 格式以保持兼容
 */
export async function getPackage(params: {
  page: number;
  pageSize: number;
  keyword: string;
}): Promise<PackageList> {
  try {
    const groups = await getGroupsV2();

    // 转换为旧版格式
    let list: Package[] = groups.map((group: TrafficPoolGroup) => {
      // 处理 createTime：可能是时间戳（数字）或日期字符串
      let formattedTime = "";
      if (group.createTime) {
        if (typeof group.createTime === "number") {
          // Unix 时间戳（秒）
          formattedTime = new Date(group.createTime * 1000).toLocaleDateString();
        } else if (typeof group.createTime === "string") {
          // 已经是日期字符串，直接取日期部分
          formattedTime = group.createTime.split(" ")[0] || group.createTime;
        }
      }

      return {
        id: group.id,
        name: group.groupName,
        description: group.description || "",
        pic: group.groupIcon || "",
        type: group.isSystem, // 1=系统，0=自定义
        createTime: formattedTime,
        num: group.memberCount || 0,
        R: Math.round(group.avgRfmR || 0),
        F: Math.round(group.avgRfmF || 0),
        M: Math.round(group.avgRfmM || 0),
        RFM: group.avgRfmScore || 0,
      };
    });

    // 关键字过滤
    if (params.keyword) {
      const keyword = params.keyword.toLowerCase();
      list = list.filter(
        item =>
          item.name.toLowerCase().includes(keyword) ||
          (item.description && item.description.toLowerCase().includes(keyword)),
      );
    }

    // 分页处理
    const total = list.length;
    const start = (params.page - 1) * params.pageSize;
    const end = start + params.pageSize;
    list = list.slice(start, end);

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

/**
 * 删除分组 (V2)
 */
export async function deletePackage(id: number): Promise<{ success: boolean }> {
  try {
    await deleteGroupV2(id);
    return { success: true };
  } catch (error) {
    console.error("删除分组失败:", error);
    throw error;
  }
}
