import type { GetSessionListVO, ModelApiTypeOption, ModelLibraryDto, ModelLibraryGetListInput, ModelTypeOption, PagedResultDto } from './types';
import { del, get, post, put } from '@/utils/request';

// 获取当前用户的模型列表
export function getModelList() {
  return get<GetSessionListVO[]>('/ai-chat/model').json();
}

// 获取模型库列表（公开接口，无需登录）
export function getModelLibraryList(params?: ModelLibraryGetListInput) {
  const queryParams = new URLSearchParams();
  if (params?.searchKey) {
    queryParams.append('SearchKey', params.searchKey);
  }
  if (params?.providerNames && params.providerNames.length > 0) {
    params.providerNames.forEach(name => queryParams.append('ProviderNames', name));
  }
  if (params?.modelTypes && params.modelTypes.length > 0) {
    params.modelTypes.forEach(type => queryParams.append('ModelTypes', type.toString()));
  }
  if (params?.modelApiTypes && params.modelApiTypes.length > 0) {
    params.modelApiTypes.forEach(type => queryParams.append('ModelApiTypes', type.toString()));
  }
  if (params?.isPremiumOnly !== undefined) {
    queryParams.append('IsPremiumOnly', params.isPremiumOnly.toString());
  }
  if (params?.skipCount !== undefined) {
    queryParams.append('SkipCount', params.skipCount.toString());
  }
  if (params?.maxResultCount !== undefined) {
    queryParams.append('MaxResultCount', params.maxResultCount.toString());
  }

  const queryString = queryParams.toString();
  const url = queryString ? `/model?${queryString}` : '/model';

  return get<PagedResultDto<ModelLibraryDto>>(url).json();
}

// 获取供应商列表（公开接口，无需登录）
export function getProviderList() {
  return get<string[]>('/model/provider-list').json();
}

// 获取模型类型选项列表（公开接口，无需登录）
export function getModelTypeOptions() {
  return get<ModelTypeOption[]>('/model/model-type-options').json();
}

// 获取API类型选项列表（公开接口，无需登录）
export function getApiTypeOptions() {
  return get<ModelApiTypeOption[]>('/model/api-type-options').json();
}
// 申请ApiKey
export function applyApiKey() {
  return post<any>('/token').json();
}
// 获取ApiKey
export function getApiKey() {
  return get<any>('/token').json();
}

// 充值记录查询参数类型
export interface RechargeLogQueryParams {
  skipCount?: number;
  maxResultCount?: number;
  isFree?: boolean;
  minRechargeAmount?: number;
  maxRechargeAmount?: number;
  startTime?: string;
  endTime?: string;
  orderByColumn?: string;
  isAsc?: string;
  isAscending?: boolean;
}

// 查询充值记录
export function getRechargeLog(params?: RechargeLogQueryParams) {
  const queryParams = new URLSearchParams();
  if (params?.skipCount !== undefined) {
    queryParams.append('SkipCount', params.skipCount.toString());
  }
  if (params?.maxResultCount !== undefined) {
    queryParams.append('MaxResultCount', params.maxResultCount.toString());
  }
  if (params?.isFree !== undefined) {
    queryParams.append('IsFree', params.isFree.toString());
  }
  if (params?.minRechargeAmount !== undefined) {
    queryParams.append('MinRechargeAmount', params.minRechargeAmount.toString());
  }
  if (params?.maxRechargeAmount !== undefined) {
    queryParams.append('MaxRechargeAmount', params.maxRechargeAmount.toString());
  }
  if (params?.startTime) {
    queryParams.append('StartTime', params.startTime);
  }
  if (params?.endTime) {
    queryParams.append('EndTime', params.endTime);
  }
  if (params?.orderByColumn) {
    queryParams.append('OrderByColumn', params.orderByColumn);
  }
  if (params?.isAsc) {
    queryParams.append('IsAsc', params.isAsc);
  }
  if (params?.isAscending !== undefined) {
    queryParams.append('IsAscending', params.isAscending.toString());
  }

  const queryString = queryParams.toString();
  const url = queryString ? `/recharge/account?${queryString}` : '/recharge/account';
  return get<any>(url).json();
}

// 查询用户近7天token消耗
// tokenId: 可选，传入则查询该token的用量，不传则查询全部
export function getLast7DaysTokenUsage(tokenId?: string) {
  const url = tokenId
    ? `/usage-statistics/last7Days-token-usage?tokenId=${tokenId}`
    : '/usage-statistics/last7Days-token-usage';
  return get<any>(url).json();
}
// 查询用户token消耗各模型占比
// tokenId: 可选，传入则查询该token的用量，不传则查询全部
export function getModelTokenUsage(tokenId?: string) {
  const url = tokenId
    ? `/usage-statistics/model-token-usage?tokenId=${tokenId}`
    : '/usage-statistics/model-token-usage';
  return get<any>(url).json();
}

// 获取当前用户得token列表
export function getTokenList(params?: {
  skipCount?: number;
  maxResultCount?: number;
  orderByColumn?: string;
  isAsc?: string;
}) {
  // 构建查询参数
  const queryParams = new URLSearchParams();
  if (params?.skipCount !== undefined) {
    queryParams.append('SkipCount', params.skipCount.toString());
  }
  if (params?.maxResultCount !== undefined) {
    queryParams.append('MaxResultCount', params.maxResultCount.toString());
  }
  if (params?.orderByColumn) {
    queryParams.append('OrderByColumn', params.orderByColumn);
  }
  if (params?.isAsc) {
    queryParams.append('IsAsc', params.isAsc);
  }

  const queryString = queryParams.toString();
  const url = queryString ? `/token/list?${queryString}` : '/token/list';

  return get<any>(url).json();
}

// 创建token
export function createToken(data: any) {
  return post<any>('/token', data).json();
}

// 编辑token
export function editToken(data: any) {
  return put('/token', data).json();
}

// 删除token
export function deleteToken(id: string) {
  return del(`/token/${id}`).json();
}

// 启用token
export function enableToken(id: string) {
  return post(`/token/${id}/enable`).json();
}

// 禁用token
export function disableToken(id: string) {
  return post(`/token/${id}/disable`).json();
}

// 新增接口2
// 获取可选择的token信息
export function getSelectableTokenInfo() {
  // return get<any>('/token/select-list').json();
  return get<any>('/token/select-list?includeDefault=false').json();
}
/*
返回数据
  [
  {
    "tokenId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
    "name": "string",
    "isDisabled": true
  }
  ] */
// 获取当前用户尊享包不同token用量占比（饼图）
export function getPremiumPackageTokenUsage() {
  return get<any>('/usage-statistics/premium-token-usage/by-token').json();
}
/* 返回数据
  [
  {
    "tokenId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
    "tokenName": "string",
    "tokens": 0,
    "percentage": 0
  }
  ] */

// 获取当前用户近24小时每小时Token消耗统计
// tokenId: 可选，传入则查询该token的用量，不传则查询全部
export function getLast24HoursTokenUsage(tokenId?: string) {
  const url = tokenId
    ? `/usage-statistics/last24Hours-token-usage?tokenId=${tokenId}`
    : '/usage-statistics/last24Hours-token-usage';
  return get<any>(url).json();
}
/* 返回数据
  [
    {
      "hour": "2026-01-23T13:32:49.237Z",
      "totalTokens": 0,
      "modelBreakdown": [
        {
          "modelId": "string",
          "tokens": 0
        }
      ]
    }
  ]
*/

// 获取当前用户今日各模型使用量统计
// tokenId: 可选，传入则查询该token的用量，不传则查询全部
export function getTodayModelUsage(tokenId?: string) {
  const url = tokenId
    ? `/usage-statistics/today-model-usage?tokenId=${tokenId}`
    : '/usage-statistics/today-model-usage';
  return get<any>(url).json();
}
/* 返回数据
  [
    {
      "modelId": "string",
      "usageCount": 0,
      "totalTokens": 0
    }
  ]
*/
