/**
 * 网卡相关 API
 */

import { BaseService } from '../BaseService'
import type {
  Card,
  SimCardProduct,
  CardQueryParams,
  CardImportBatch,
  CardOperationParams,
  CardAssignParams,
  BatchRechargeRecord,
  CardChangeApplication,
  ProcessCardChangeParams,
  FlowDetail,
  SuspendResumeRecord,
  CardOrder,
  BaseResponse,
  PaginationParams,
  PaginationResponse,
  ListResponse,
  GatewayRealnameLinkResponse,
  ImportIotCardRequest,
  ImportIotCardResponse,
  IotCardImportTask,
  IotCardImportTaskDetail,
  IotCardImportTaskQueryParams,
  StandaloneCardQueryParams,
  StandaloneIotCard,
  AllocateStandaloneCardsRequest,
  AllocateStandaloneCardsResponse,
  RecallStandaloneCardsRequest,
  AssetAllocationRecordQueryParams,
  AssetAllocationRecord,
  AssetAllocationRecordDetail,
  BatchSetCardSeriesBindingRequest,
  BatchSetCardSeriesBindingResponse,
  BatchUpdateAssetRealnamePolicyRequest
} from '@/types/api'

type ApiQueryParams = PaginationParams & Record<string, unknown>

interface ImportFailureRecord {
  line?: number
  row?: number
  iccid?: string
  reason: string
}

interface CardChangeNotice {
  id: string | number
  iccids: string[]
  reason: string
  createTime?: string
  operatorName?: string
}

export class CardService extends BaseService {
  // ========== 号卡商品管理 ==========

  /**
   * 获取号卡商品列表
   * @param params 查询参数
   */
  static getSimCardProducts(params?: ApiQueryParams): Promise<PaginationResponse<SimCardProduct>> {
    return this.getPage<SimCardProduct>('/api/simcard-products', params)
  }

  /**
   * 创建号卡商品
   * @param data 商品数据
   */
  static createSimCardProduct(data: Partial<SimCardProduct>): Promise<BaseResponse> {
    return this.create('/api/simcard-products', data)
  }

  /**
   * 更新号卡商品
   * @param id 商品ID
   * @param data 商品数据
   */
  static updateSimCardProduct(
    id: string | number,
    data: Partial<SimCardProduct>
  ): Promise<BaseResponse> {
    return this.update(`/api/simcard-products/${id}`, data)
  }

  /**
   * 删除号卡商品
   * @param id 商品ID
   */
  static deleteSimCardProduct(id: string | number): Promise<BaseResponse> {
    return this.remove(`/api/simcard-products/${id}`)
  }

  /**
   * 号卡分配
   * @param params 分配参数
   */
  static assignCard(params: CardAssignParams): Promise<BaseResponse> {
    return this.post<BaseResponse>('/api/simcard-products/assign', params)
  }

  // ========== 网卡管理 ==========

  /**
   * 获取网卡列表
   * @param params 查询参数
   */
  static getCards(params?: CardQueryParams): Promise<PaginationResponse<Card>> {
    return this.getPage<Card>('/api/cards', params)
  }

  /**
   * 根据ICCID获取单卡信息（旧接口，用于现有功能）
   * @param iccid ICCID
   */
  static getCardByIccid(iccid: string): Promise<BaseResponse<Card>> {
    return this.getOne<Card>(`/api/cards/iccid/${iccid}`)
  }

  /**
   * 网卡操作（充值、停复机、增减流量等）
   * @param params 操作参数
   */
  static cardOperation(params: CardOperationParams): Promise<BaseResponse> {
    return this.post<BaseResponse>('/api/cards/operation', params)
  }

  /**
   * 套餐充值
   * @param iccid ICCID
   * @param packageId 套餐ID
   */
  static rechargePackage(iccid: string, packageId: string | number): Promise<BaseResponse> {
    return this.post<BaseResponse>(`/api/cards/${iccid}/recharge`, { packageId })
  }

  /**
   * 停机
   * @param iccid ICCID
   * @param remark 备注
   */
  static suspend(iccid: string, remark?: string): Promise<BaseResponse> {
    return this.post<BaseResponse>(`/api/cards/${iccid}/suspend`, { remark })
  }

  /**
   * 复机
   * @param iccid ICCID
   * @param remark 备注
   */
  static resume(iccid: string, remark?: string): Promise<BaseResponse> {
    return this.post<BaseResponse>(`/api/cards/${iccid}/resume`, { remark })
  }

  /**
   * 获取流量详情
   * @param iccid ICCID
   * @param startDate 开始日期
   * @param endDate 结束日期
   */
  static getFlowDetails(
    iccid: string,
    startDate?: string,
    endDate?: string
  ): Promise<ListResponse<FlowDetail>> {
    return this.getList<FlowDetail>(`/api/cards/${iccid}/flow-details`, {
      startDate,
      endDate
    })
  }

  /**
   * 获取停复机记录
   * @param iccid ICCID
   */
  static getSuspendResumeRecords(iccid: string): Promise<ListResponse<SuspendResumeRecord>> {
    return this.getList<SuspendResumeRecord>(`/api/cards/${iccid}/suspend-resume-records`)
  }

  /**
   * 获取往期订单
   * @param iccid ICCID
   */
  static getCardOrders(iccid: string): Promise<ListResponse<CardOrder>> {
    return this.getList<CardOrder>(`/api/cards/${iccid}/orders`)
  }

  /**
   * 更改过期时间
   * @param iccid ICCID
   * @param expireTime 过期时间
   */
  static changeExpireTime(iccid: string, expireTime: string): Promise<BaseResponse> {
    return this.put<BaseResponse>(`/api/cards/${iccid}/expire-time`, { expireTime })
  }

  /**
   * 增加流量
   * @param iccid ICCID
   * @param flow 流量（MB）
   */
  static addFlow(iccid: string, flow: number): Promise<BaseResponse> {
    return this.post<BaseResponse>(`/api/cards/${iccid}/add-flow`, { flow })
  }

  /**
   * 减少流量
   * @param iccid ICCID
   * @param flow 流量（MB）
   */
  static reduceFlow(iccid: string, flow: number): Promise<BaseResponse> {
    return this.post<BaseResponse>(`/api/cards/${iccid}/reduce-flow`, { flow })
  }

  /**
   * 变更钱包余额
   * @param iccid ICCID
   * @param amount 金额
   */
  static changeWalletBalance(iccid: string, amount: number): Promise<BaseResponse> {
    return this.put<BaseResponse>(`/api/cards/${iccid}/wallet`, { amount })
  }

  // ========== 批量操作 ==========

  /**
   * 获取导入批次列表
   * @param params 查询参数
   */
  static getImportBatches(params?: ApiQueryParams): Promise<PaginationResponse<CardImportBatch>> {
    return this.getPage<CardImportBatch>('/api/cards/import-batches', params)
  }

  /**
   * 批量导入网卡
   * @param file Excel文件
   * @param params 额外参数
   */
  static importCards(file: File, params?: Record<string, unknown>): Promise<BaseResponse> {
    return this.upload('/api/cards/import', file, params)
  }

  /**
   * 获取导入失败记录
   * @param batchId 批次ID
   */
  static getImportFailures(batchId: string | number): Promise<ListResponse<ImportFailureRecord>> {
    return this.getList<ImportFailureRecord>(`/api/cards/import-batches/${batchId}/failures`)
  }

  /**
   * 批量充值记录列表
   * @param params 查询参数
   */
  static getBatchRechargeRecords(
    params?: ApiQueryParams
  ): Promise<PaginationResponse<BatchRechargeRecord>> {
    return this.getPage<BatchRechargeRecord>('/api/cards/batch-recharge-records', params)
  }

  /**
   * 批量充值导入
   * @param file Excel文件
   */
  static batchRecharge(file: File): Promise<BaseResponse> {
    return this.upload('/api/cards/batch-recharge', file)
  }

  // ========== 换卡管理 ==========

  /**
   * 获取换卡申请列表
   * @param params 查询参数
   */
  static getCardChangeApplications(
    params?: ApiQueryParams
  ): Promise<PaginationResponse<CardChangeApplication>> {
    return this.getPage<CardChangeApplication>('/api/card-change-applications', params)
  }

  /**
   * 处理换卡申请
   * @param params 处理参数
   */
  static processCardChange(params: ProcessCardChangeParams): Promise<BaseResponse> {
    return this.post<BaseResponse>('/api/card-change-applications/process', params)
  }

  /**
   * 创建换卡通知
   * @param iccids ICCID列表
   * @param reason 换卡原因
   */
  static createCardChangeNotice(iccids: string[], reason: string): Promise<BaseResponse> {
    return this.post<BaseResponse>('/api/card-change-notices', { iccids, reason })
  }

  /**
   * 获取换卡通知记录
   * @param params 查询参数
   */
  static getCardChangeNotices(
    params?: ApiQueryParams
  ): Promise<PaginationResponse<CardChangeNotice>> {
    return this.getPage<CardChangeNotice>('/api/card-change-notices', params)
  }

  // ========== ICCID批量导入相关 ==========

  /**
   * 批量导入ICCID（新版：使用 JSON 格式）
   * @param data 导入请求参数
   */
  static importIotCards(data: ImportIotCardRequest): Promise<BaseResponse<ImportIotCardResponse>> {
    return this.post<BaseResponse<ImportIotCardResponse>>('/api/admin/iot-cards/import', data)
  }

  /**
   * 获取导入任务列表
   * @param params 查询参数
   */
  static getIotCardImportTasks(
    params?: IotCardImportTaskQueryParams
  ): Promise<PaginationResponse<IotCardImportTask>> {
    return this.getPage<IotCardImportTask>('/api/admin/iot-cards/import-tasks', params)
  }

  /**
   * 获取导入任务详情
   * @param id 任务ID
   */
  static getIotCardImportTaskDetail(id: number): Promise<BaseResponse<IotCardImportTaskDetail>> {
    return this.getOne<IotCardImportTaskDetail>(`/api/admin/iot-cards/import-tasks/${id}`)
  }

  // ========== 单卡列表（未绑定设备）相关 ==========

  /**
   * 获取单卡列表（未绑定设备）
   * @param params 查询参数
   */
  static getStandaloneIotCards(
    params?: StandaloneCardQueryParams
  ): Promise<PaginationResponse<StandaloneIotCard>> {
    return this.getPage<StandaloneIotCard>('/api/admin/iot-cards/standalone', params)
  }

  /**
   * 批量分配单卡
   * @param data 分配参数
   */
  static allocateStandaloneCards(
    data: Partial<AllocateStandaloneCardsRequest>
  ): Promise<BaseResponse<AllocateStandaloneCardsResponse>> {
    return this.post<BaseResponse<AllocateStandaloneCardsResponse>>(
      '/api/admin/iot-cards/standalone/allocate',
      data
    )
  }

  /**
   * 批量回收单卡
   * @param data 回收参数
   */
  static recallStandaloneCards(
    data: Partial<RecallStandaloneCardsRequest>
  ): Promise<BaseResponse<AllocateStandaloneCardsResponse>> {
    return this.post<BaseResponse<AllocateStandaloneCardsResponse>>(
      '/api/admin/iot-cards/standalone/recall',
      data
    )
  }

  // ========== 资产分配记录相关 ==========

  /**
   * 获取资产分配记录列表
   * @param params 查询参数
   */
  static getAssetAllocationRecords(
    params?: AssetAllocationRecordQueryParams
  ): Promise<PaginationResponse<AssetAllocationRecord>> {
    return this.getPage<AssetAllocationRecord>('/api/admin/asset-allocation-records', params)
  }

  /**
   * 获取资产分配记录详情
   * @param id 记录ID
   */
  static getAssetAllocationRecordDetail(
    id: number
  ): Promise<BaseResponse<AssetAllocationRecordDetail>> {
    return this.getOne<AssetAllocationRecordDetail>(`/api/admin/asset-allocation-records/${id}`)
  }

  // ========== 批量设置卡的套餐系列绑定相关 ==========

  /**
   * 批量设置卡的套餐系列绑定
   * @param data 请求参数
   */
  static batchSetCardSeriesBinding(
    data: BatchSetCardSeriesBindingRequest
  ): Promise<BaseResponse<BatchSetCardSeriesBindingResponse>> {
    return this.patch<BaseResponse<BatchSetCardSeriesBindingResponse>>(
      '/api/admin/iot-cards/series-binding',
      data
    )
  }

  /**
   * 批量更新卡实名认证策略
   */
  static batchUpdateRealnamePolicy(
    data: BatchUpdateAssetRealnamePolicyRequest,
    config?: Record<string, any>
  ): Promise<BaseResponse<void>> {
    return this.post<BaseResponse<void>>(
      '/api/admin/iot-cards/batch-update-realname-policy',
      data,
      config
    )
  }

  // ========== IoT卡网关操作相关 ==========

  /**
   * 获取实名认证链接
   * @param iccid ICCID
   */
  static getRealnameLink(iccid: string): Promise<BaseResponse<GatewayRealnameLinkResponse>> {
    return this.get<BaseResponse<GatewayRealnameLinkResponse>>(
      `/api/admin/iot-cards/${iccid}/realname-link`
    )
  }

  /**
   * 启用 IoT 卡 单卡复机
   * @param iccid
   */
  static enableIotCard(iccid: string): Promise<BaseResponse> {
    return this.post<BaseResponse>(`/api/admin/assets/card/${iccid}/start`, {})
  }

  /**
   * 停用 IoT 卡 单卡停机
   * @param iccid
   */
  static disableIotCard(iccid: string): Promise<BaseResponse> {
    return this.post<BaseResponse>(`/api/admin/assets/card/${iccid}/stop`, {})
  }

  /**
   * 手动停用 IoT 卡
   * @param id IoT卡ID
   */
  static deactivateIotCard(id: number): Promise<BaseResponse> {
    return this.patch<BaseResponse>(`/api/admin/iot-cards/${id}/deactivate`, {})
  }

  /**
   * 获取套餐流量详单（每日流量记录）
   * @param packageUsageId 套餐使用记录ID
   */
  static getPackageDailyRecords(packageUsageId: number): Promise<
    BaseResponse<{
      package_name: string
      package_usage_id: number
      total_usage_mb: number
      records: Array<{
        date: string
        daily_usage_mb: number
        cumulative_usage_mb: number
      }>
    }>
  > {
    return this.get<
      BaseResponse<{
        package_name: string
        package_usage_id: number
        total_usage_mb: number
        records: Array<{
          date: string
          daily_usage_mb: number
          cumulative_usage_mb: number
        }>
      }>
    >(`/api/admin/package-usage/${packageUsageId}/daily-records`)
  }
}
