import request from "@/api/request";

// ==================== 类型定义 ====================

// RFM 评分
export interface RfmScore {
  R: number;
  F: number;
  M: number;
  total: number;
}

// 分组规则条件
export interface RuleCondition {
  type: "field" | "group" | "tag";
  field?: string;
  operator?: string;
  value?: any;
  valueType?: string;
  logic?: "AND" | "OR";
  conditions?: RuleCondition[];
}

// 分组规则配置
export interface RuleConfig {
  logic: "AND" | "OR";
  conditions: RuleCondition[];
}

// 流量池分组
export interface TrafficPoolGroup {
  id: number;
  companyId: number;
  groupCode: string;
  groupName: string;
  groupIcon: string | null;
  groupColor: string | null;
  description: string | null;
  isSystem: number;
  isDefault: number;
  ruleType: number; // 1=动态规则，2=手动添加
  ruleConfig: RuleConfig | null;
  memberCount: number;
  sort: number;
  status: number;
  createTime: number;
  // RFM 统计
  avgRfmR?: number;
  avgRfmF?: number;
  avgRfmM?: number;
  avgRfmScore?: number;
}

// 流量池成员
export interface TrafficPoolMember {
  id: number;
  poolId: number;
  identifier: string;
  companyId: number;
  friendStatus: number;
  level: number;
  intentionLevel: number;
  lifecycle: number;
  lastInteractTime: number | null;
  rfmR: number;
  rfmF: number;
  rfmM: number;
  rfmScore: RfmScore;
  totalMsgCount: number;
  totalOrderCount: number;
  totalOrderAmount: number;
  ownerWechatId: string | null;
  allocateStatus: number;
  realName: string | null;
  phone: string | null;
  createTime: number;
  // 关联的总表信息
  nickname: string | null;
  avatar: string | null;
  gender: number;
  wechatId: string | null;
  wechatAlias: string | null;
  mobile: string | null;
  region: string | null;
  // 标签
  tags: TrafficPoolTag[];
}

// 流量池标签
export interface TrafficPoolTag {
  id: number;
  tagDefineId: number;
  tagName: string;
  tagType: number;
  tagValue: string | null;
}

// 标签类目
export interface TagCategory {
  id: number;
  companyId: number;
  parentId: number;
  tagType: number;
  categoryCode: string;
  categoryName: string;
  categoryIcon: string | null;
  categoryColor: string | null;
  description: string | null;
  isSystem: number;
  children?: TagCategory[];
}

// 标签定义
export interface TagDefine {
  id: number;
  companyId: number;
  categoryId: number;
  tagType: number;
  tagCode: string;
  tagName: string;
  tagIcon: string | null;
  tagColor: string | null;
  description: string | null;
  isSystem: number;
  isExclusive: number;
  useCount: number;
}

// 流量来源
export interface TrafficSource {
  id: number;
  poolCompanyId: number;
  sourceType: number;
  sourceName: string | null;
  isFirstSource: number;
  createTime: number;
}

// 流量行为
export interface TrafficBehavior {
  id: number;
  poolCompanyId: number;
  behaviorType: number;
  behaviorName: string | null;
  targetName: string | null;
  amount: number;
  behaviorTime: number;
}

// 分配记录
export interface AllotRecord {
  id: number;
  poolCompanyId: number;
  allotType: number;
  fromWechatId: string | null;
  toWechatId: string;
  expireDays: number;
  status: number;
  createTime: number;
}

// 统计数据
export interface TrafficStatistics {
  totalCount: number;
  friendCount: number;
  todayNewCount: number;
  weekNewCount: number;
  monthNewCount: number;
  levelDistribution: { level: number; count: number }[];
  lifecycleDistribution: { lifecycle: number; count: number }[];
  sourceDistribution: { sourceType: number; count: number }[];
}

// 分页响应
export interface PageResult<T> {
  list: T[];
  total: number;
  page: number;
  pageSize: number;
}

// ==================== 分组相关 API ====================

/**
 * 获取流量池分组列表
 */
export async function getGroups(): Promise<TrafficPoolGroup[]> {
  return request("/v1/traffic/pool/v2/groups", {}, "GET");
}

/**
 * 获取分组详情
 */
export async function getGroupDetail(
  groupId: number,
): Promise<TrafficPoolGroup> {
  return request("/v1/traffic/pool/v2/group/detail", { groupId }, "GET");
}

/**
 * 创建分组
 */
export async function createGroup(data: {
  groupName: string;
  groupCode?: string;
  groupIcon?: string;
  groupColor?: string;
  description?: string;
  ruleType?: number;
  ruleConfig?: RuleConfig;
  sort?: number;
}): Promise<{ id: number }> {
  return request("/v1/traffic/pool/v2/group/create", data, "POST");
}

/**
 * 更新分组
 */
export async function updateGroup(
  groupId: number,
  data: {
    groupName?: string;
    groupIcon?: string;
    groupColor?: string;
    description?: string;
    ruleType?: number;
    ruleConfig?: RuleConfig;
    sort?: number;
    status?: number;
  },
): Promise<void> {
  return request(
    "/v1/traffic/pool/v2/group/update",
    { groupId, ...data },
    "PUT",
  );
}

/**
 * 删除分组
 */
export async function deleteGroup(groupId: number): Promise<void> {
  return request("/v1/traffic/pool/v2/group/delete", { groupId }, "DELETE");
}

/**
 * 获取分组成员列表
 */
export async function getGroupMembers(params: {
  groupId: number;
  page?: number;
  pageSize?: number;
  keyword?: string;
}): Promise<PageResult<TrafficPoolMember>> {
  return request("/v1/traffic/pool/v2/group/members", params, "GET");
}

/**
 * 添加成员到分组
 */
export async function addMembersToGroup(
  groupId: number,
  poolCompanyIds: number[],
): Promise<{ count: number }> {
  return request(
    "/v1/traffic/pool/v2/group/add-members",
    { groupId, poolCompanyIds },
    "POST",
  );
}

/**
 * 从分组移除成员
 */
export async function removeMembersFromGroup(
  groupId: number,
  poolCompanyIds: number[],
): Promise<{ count: number }> {
  return request(
    "/v1/traffic/pool/v2/group/remove-members",
    { groupId, poolCompanyIds },
    "POST",
  );
}

// ==================== 流量池成员相关 API ====================

/**
 * 获取流量池列表
 */
export async function getPoolList(params: {
  page?: number;
  pageSize?: number;
  keyword?: string;
  friendStatus?: number;
  level?: number;
  lifecycle?: number;
  allocateStatus?: number;
  ownerWechatId?: string;
  rfmMMin?: number;
  rfmMMax?: number;
}): Promise<PageResult<TrafficPoolMember>> {
  return request("/v1/traffic/pool/v2/list", params, "GET");
}

/**
 * 获取流量详情
 */
export async function getPoolDetail(id: number): Promise<
  TrafficPoolMember & {
    sources: TrafficSource[];
    behaviors: TrafficBehavior[];
    allotRecords: AllotRecord[];
  }
> {
  return request("/v1/traffic/pool/v2/detail", { id }, "GET", {
    timeout: 0, // 去除超时限制
  });
}

/**
 * 更新流量信息
 */
export async function updatePool(
  id: number,
  data: {
    realName?: string;
    phone?: string;
    email?: string;
    birthday?: string;
    address?: string;
    company?: string;
    position?: string;
    remark?: string;
    level?: number;
    intentionLevel?: number;
    lifecycle?: number;
    status?: number;
  },
): Promise<void> {
  return request("/v1/traffic/pool/v2/update", { id, ...data }, "PUT");
}

// ==================== 标签相关 API ====================

/**
 * 获取标签类目
 */
export async function getTagCategories(
  tagType?: number,
): Promise<TagCategory[]> {
  return request("/v1/traffic/pool/v2/tag/categories", { tagType }, "GET");
}

/**
 * 获取标签定义
 */
export async function getTagDefines(params?: {
  tagType?: number;
  categoryId?: number;
}): Promise<TagDefine[]> {
  return request("/v1/traffic/pool/v2/tag/defines", params || {}, "GET");
}

/**
 * 获取流量的标签
 */
export async function getPoolTags(
  poolCompanyId: number,
  tagType?: number,
): Promise<TrafficPoolTag[]> {
  return request(
    "/v1/traffic/pool/v2/tag/pool-tags",
    { poolCompanyId, tagType },
    "GET",
  );
}

/**
 * 为流量添加标签
 */
export async function addTag(
  poolCompanyId: number,
  tagDefineId: number,
  tagValue?: string,
): Promise<{ id: number }> {
  return request(
    "/v1/traffic/pool/v2/tag/add",
    { poolCompanyId, tagDefineId, tagValue },
    "POST",
  );
}

/**
 * 移除流量标签
 */
export async function removeTag(
  poolCompanyId: number,
  tagDefineId: number,
): Promise<void> {
  return request(
    "/v1/traffic/pool/v2/tag/remove",
    { poolCompanyId, tagDefineId },
    "DELETE",
  );
}

/**
 * 从标签引擎同步用户标签
 */
export async function syncTagsFromEngine(
  poolCompanyId: number,
): Promise<{ syncedCount: number; skippedCount: number; total: number }> {
  return request(
    "/v1/traffic/pool/v2/tag/sync-from-engine",
    { poolCompanyId },
    "POST",
    {
      timeout: 0, // 去除超时限制
    },
  );
}

// ==================== 来源和行为相关 API ====================

/**
 * 分页获取流量来源
 */
export async function getPoolSources(params: {
  poolCompanyId: number;
  page?: number;
  pageSize?: number;
  keyword?: string;
}): Promise<{
  list: TrafficSource[];
  total: number;
  page: number;
  pageSize: number;
}> {
  return request("/v1/traffic/pool/v2/sources", params, "GET");
}

/**
 * 分页获取流量行为轨迹
 */
export async function getPoolBehaviors(params: {
  poolCompanyId: number;
  page?: number;
  pageSize?: number;
  keyword?: string;
  behaviorType?: number;
}): Promise<{
  list: TrafficBehavior[];
  total: number;
  page: number;
  pageSize: number;
}> {
  return request("/v1/traffic/pool/v2/behaviors", params, "GET");
}

// ==================== 分配相关 API ====================

/**
 * 分配流量给客服
 */
export async function allocatePool(params: {
  poolCompanyId: number;
  toWechatId: string;
  toAccountId?: number;
  toUserId?: number;
  expireDays?: number;
}): Promise<{ id: number }> {
  return request("/v1/traffic/pool/v2/allocate", params, "POST");
}

/**
 * 回收流量分配
 */
export async function recyclePool(poolCompanyId: number): Promise<void> {
  return request("/v1/traffic/pool/v2/recycle", { poolCompanyId }, "POST");
}

// ==================== 统计相关 API ====================

/**
 * 获取流量池统计数据
 */
export async function getStatistics(): Promise<TrafficStatistics> {
  return request("/v1/traffic/pool/v2/statistics", {}, "GET");
}

// ==================== 常量定义 ====================

// 好友状态
export const FRIEND_STATUS = {
  NOT_ADDED: 0, // 未加
  PENDING: 1, // 待通过
  PASSED: 2, // 已通过
  DELETED: 3, // 已删除
  BE_DELETED: 4, // 被删除
};

export const FRIEND_STATUS_TEXT: Record<number, string> = {
  [FRIEND_STATUS.NOT_ADDED]: "未加",
  [FRIEND_STATUS.PENDING]: "待通过",
  [FRIEND_STATUS.PASSED]: "已通过",
  [FRIEND_STATUS.DELETED]: "已删除",
  [FRIEND_STATUS.BE_DELETED]: "被删除",
};

// 客户等级
export const LEVEL = {
  NORMAL: 0, // 普通
  IMPORTANT: 1, // 重要
  VIP: 2, // VIP
};

export const LEVEL_TEXT: Record<number, string> = {
  [LEVEL.NORMAL]: "普通",
  [LEVEL.IMPORTANT]: "重要",
  [LEVEL.VIP]: "VIP",
};

// 意向度
export const INTENTION_LEVEL = {
  UNKNOWN: 0, // 未知
  LOW: 1, // 低
  MEDIUM: 2, // 中
  HIGH: 3, // 高
};

export const INTENTION_LEVEL_TEXT: Record<number, string> = {
  [INTENTION_LEVEL.UNKNOWN]: "未知",
  [INTENTION_LEVEL.LOW]: "低意向",
  [INTENTION_LEVEL.MEDIUM]: "中意向",
  [INTENTION_LEVEL.HIGH]: "高意向",
};

// 生命周期
export const LIFECYCLE = {
  NEW: 1, // 新流量
  FOLLOWING: 2, // 跟进中
  CONVERTED: 3, // 已成交
  SILENT: 4, // 沉默
  LOST: 5, // 流失
};

export const LIFECYCLE_TEXT: Record<number, string> = {
  [LIFECYCLE.NEW]: "新流量",
  [LIFECYCLE.FOLLOWING]: "跟进中",
  [LIFECYCLE.CONVERTED]: "已成交",
  [LIFECYCLE.SILENT]: "沉默",
  [LIFECYCLE.LOST]: "流失",
};

// 来源类型
export const SOURCE_TYPE = {
  FRIEND_ADD: 1, // 好友添加
  GROUP_MEMBER: 2, // 群成员
  POSTER: 3, // 海报获客
  PHONE: 4, // 电话获客
  ORDER: 5, // 订单获客
  API: 6, // API导入
  MANUAL: 7, // 手动导入
  FISSION: 8, // 裂变活动
};

export const SOURCE_TYPE_TEXT: Record<number, string> = {
  [SOURCE_TYPE.FRIEND_ADD]: "好友添加",
  [SOURCE_TYPE.GROUP_MEMBER]: "群成员",
  [SOURCE_TYPE.POSTER]: "海报获客",
  [SOURCE_TYPE.PHONE]: "电话获客",
  [SOURCE_TYPE.ORDER]: "订单获客",
  [SOURCE_TYPE.API]: "API导入",
  [SOURCE_TYPE.MANUAL]: "手动导入",
  [SOURCE_TYPE.FISSION]: "裂变活动",
};

// 标签类型
export const TAG_TYPE = {
  WECHAT: 1, // 微信标签
  SITE: 2, // 站内标签
  AI: 3, // AI标签
};

export const TAG_TYPE_TEXT: Record<number, string> = {
  [TAG_TYPE.WECHAT]: "微信标签",
  [TAG_TYPE.SITE]: "站内标签",
  [TAG_TYPE.AI]: "AI标签",
};
