/**
 * 资产模块 API
 */
import { get, post, patch } from '@/utils/request'

/**
 * 资产类型
 */
export type AssetType = 'card' | 'device'

/**
 * 资产状态
 */
export type AssetStatus = 'active' | 'inactive' | 'suspended' | 'online' | 'offline' | 'fault'

/**
 * 资产解析响应
 */
export interface AssetResolveResponse {
  asset_type: 'card' | 'device'
  asset_id: number
  virtual_no: string
  status: number
  batch_no?: string
  first_commission_paid?: boolean
  accumulated_recharge?: number
  created_at?: string
  updated_at?: string
  real_name_status?: number
  current_package?: string
  package_total_mb?: number
  package_used_mb?: number
  package_remain_mb?: number
  // 卡片特有字段
  iccid?: string
  carrier_id?: number
  msisdn?: string
  card_category?: string
  enable_polling?: boolean
  // 设备特有字段
  shop_id?: number
  shop_name?: string
  series_id?: number
  series_name?: string
  device_protect_status?: string
  bound_card_count?: number
  cards?: Array<{
    card_id: number
    iccid: string
    msisdn?: string | null
    carrier_name?: string | null
    network_status: number
    real_name_status: number
    slot_position: number
    is_current: boolean
  }>
  device_name?: string
  imei?: string
  device_model?: string
  device_type?: string
  max_sim_slots?: number
  manufacturer?: string
  last_online_time?: string
  switch_mode?: string
  last_gateway_sync_at?: string
  [key: string]: any
}

/**
 * 卡片信息
 */
export interface CardInfo {
  id: number | string
  iccid: string
  msisdn?: string // 电话号码
  virtual_no?: string // 虚拟号
  virtual_number?: string // 虚拟号 (别名兼容)
  device_virtual_no?: string | null
  imei?: string
  carrier_id?: number // 运营商ID
  carrier_name?: string // 运营商名称
  operator?: string // 运营商 (别名兼容)
  package_name?: string // 套餐名称
  current_package?: string // 当前套餐 (别名兼容)
  status?: number // 卡状态 (1=在库, 2=激活, 3=停用等)
  status_name?: string // 状态名称
  network_status?: number // 网络状态 (0=停机, 1=正常等)
  network_status_name?: string // 网络状态名称
  data_usage?: string
  data_total?: string
  expire_date?: string
  activate_time?: string
  enterprise_id?: number
  enterprise_name?: string
  device_id?: string
  device_name?: string
  [key: string]: any
}

/**
 * 设备信息
 */
export interface DeviceInfo {
  id?: number | string
  device_id?: number // 设备ID
  virtual_no?: string // 设备虚拟号
  device_name?: string // 设备名称
  device_model?: string // 设备型号
  card_count?: number // 绑定卡数量
  authorized_at?: string // 授权时间
  sn?: string
  device_type?: string
  status?: 'online' | 'offline' | 'fault'
  location?: string
  last_online_time?: string
  create_time?: string
  enterprise_id?: number
  enterprise_name?: string
  [key: string]: any
}

/**
 * 资产详情响应
 */
export interface AssetDetailResponse {
  type: AssetType
  card?: CardInfo
  device?: DeviceInfo
}

/**
 * 历史记录
 */
export interface HistoryRecord {
  id: number
  time: string
  action: string
  operator?: string
  details?: string
  [key: string]: any
}

/**
 * 操作参数 (旧版，使用 ID)
 * @deprecated 使用 AssetOperationParams 代替
 */
export interface OperationParams {
  id: string
  reason?: string
}

/**
 * 操作参数 (新版，使用 identifier)
 */
export interface AssetOperationParams {
  identifier: string
  reason?: string
}

/**
 * 资产解析 (智能识别)
 * GET /api/admin/assets/resolve/:identifier
 */
export function resolveAsset(identifier: string) {
  return get<AssetResolveResponse>(`/api/admin/assets/resolve/${identifier}`)
}

/**
 * 获取资产详情
 * GET /api/admin/assets/:identifier (已废弃 type/id 格式)
 * @deprecated 使用 identifier 代替，路由: GET /api/admin/assets/:identifier
 */
export function getAssetDetail(type: AssetType, id: string) {
  return get<AssetDetailResponse>(`/api/admin/assets/${type}/${id}`)
}

/**
 * 获取卡片详情
 * @deprecated 请使用 resolveAsset 通过 ICCID 查询
 */
export function getCardDetail(id: string) {
  return get<CardInfo>(`/api/admin/cards/${id}`)
}

/**
 * 获取设备详情
 * GET /api/admin/devices/:virtual_no
 * @param virtualNo 设备虚拟号
 */
export function getDeviceDetail(virtualNo: string) {
  return get<DeviceInfo>(`/api/admin/devices/${virtualNo}`)
}

/**
 * 设备实时信息
 */
export interface DeviceRealtime {
  device_id?: string
  device_name?: string
  device_type?: string
  imei?: string
  imsi?: string
  mac_address?: string
  software_version?: string
  online_status?: number
  status?: number
  battery_level?: number
  client_number?: number
  max_clients?: number
  connect_time?: string
  run_time?: string
  daily_usage?: string
  dl_stats?: string
  ul_stats?: string
  limit_speed?: number
  ip_address?: string
  lan_ip?: string
  wan_ip?: string
  ssid?: string
  wifi_enabled?: boolean
  wifi_password?: string
  current_iccid?: string
  switch_mode?: string
  rsrp?: number
  rsrq?: number
  rssi?: string
  sinr?: number
  signal_quality?: string
  signal_bad_reason?: string
  last_online_time?: string
  last_update_time?: string
  sync_interval?: number
  gateway_msg?: string | null
}

/**
 * 资产实时状态响应
 */
export interface AssetRealtimeStatus {
  asset_id: number
  asset_type: 'card' | 'device'
  current_month_usage_mb?: number | null
  last_sync_time?: string | null
  network_status?: number | null
  real_name_status?: number | null
  device_protect_status?: string | null
  cards?: Array<{
    card_id: number
    iccid: string
    is_current: boolean
    msisdn?: string | null
    carrier_name?: string | null
    network_status: number
    real_name_status: number
    slot_position: number
  }>
  device_realtime?: DeviceRealtime | null
}

/**
 * 获取资产实时状态
 * GET /api/admin/assets/:identifier/realtime-status
 * @param identifier ICCID 或 VirtualNo
 */
export function getAssetRealtimeStatus(identifier: string) {
  return get<AssetRealtimeStatus>(`/api/admin/assets/${identifier}/realtime-status`)
}

/**
 * 资产套餐信息
 */
export interface AssetPackage {
  package_id: number
  package_name: string
  package_type: 'formal' | 'addon'
  order_id?: number
  order_no?: string
  status: number
  status_name: string
  usage_type: string
  priority: number
  package_usage_id: number
  master_usage_id: number | null
  paid_amount?: number
  enable_virtual_data?: boolean
  reduction_pct?: number
  real_total_mb?: number
  real_used_mb?: number
  virtual_total_mb?: number
  data_limit_mb: number
  data_usage_mb: number
  virtual_limit_mb: number
  virtual_used_mb: number
  virtual_remain_mb: number
  virtual_ratio: number
  created_at: string
  activated_at: string | null
  expires_at: string | null
}

/**
 * 获取资产套餐列表
 * GET /api/admin/assets/:identifier/packages
 * @param identifier ICCID 或 VirtualNo
 */
export function getAssetPackages(identifier: string, params?: { page?: number, page_size?: number }) {
  return get<{
    items: AssetPackage[]
    page: number
    page_size: number
    total: number
  }>(`/api/admin/assets/${identifier}/packages`, { params })
}

/**
 * 获取当前生效套餐
 * GET /api/admin/assets/:identifier/current-package
 * @param identifier ICCID 或 VirtualNo
 */
export function getCurrentPackage(identifier: string) {
  return get<AssetPackage>(`/api/admin/assets/${identifier}/current-package`)
}

/**
 * 获取资产历史记录
 * GET /api/admin/assets/:identifier/history
 * @param identifier ICCID 或 VirtualNo
 */
export function getAssetHistory(identifier: string, params?: { page?: number, pageSize?: number }) {
  return get<{
    list: HistoryRecord[]
    total: number
    page: number
    pageSize: number
  }>(`/api/admin/assets/${identifier}/history`, { params })
}

/**
 * 停用卡片
 * @deprecated 使用 stopAsset 代替，路由: POST /api/admin/assets/:identifier/stop
 */
export function stopCard(data: OperationParams) {
  return post<void>(`/api/admin/cards/${data.id}/stop`, {
    data: { reason: data.reason },
  })
}

/**
 * 启用卡片
 * @deprecated 使用 startAsset 代替，路由: POST /api/admin/assets/:identifier/start
 */
export function startCard(data: OperationParams) {
  return post<void>(`/api/admin/cards/${data.id}/start`, {
    data: { reason: data.reason },
  })
}

/**
 * 停用设备
 * POST /api/admin/devices/:virtual_no/stop
 * @param virtualNo 设备虚拟号
 */
export function stopDevice(virtualNo: string, reason?: string) {
  return post<void>(`/api/admin/devices/${virtualNo}/stop`, {
    data: { reason },
  })
}

/**
 * 启用设备
 * POST /api/admin/devices/:virtual_no/start
 * @param virtualNo 设备虚拟号
 */
export function startDevice(virtualNo: string, reason?: string) {
  return post<void>(`/api/admin/devices/${virtualNo}/start`, {
    data: { reason },
  })
}

/**
 * 设备停机失败项
 */
export interface DeviceStopFailedItem {
  iccid: string
  reason: string
}

/**
 * 设备停机响应
 */
export interface DeviceStopResponse {
  success_count: number
  fail_count: number
  skip_count: number
  failed_items: DeviceStopFailedItem[]
}

/**
 * 设备停机 (批量停机设备下所有已实名卡)
 * @deprecated 使用 stopAsset 代替，路由: POST /api/admin/assets/:identifier/stop
 */
export function stopDeviceAsset(deviceId: number) {
  return post<DeviceStopResponse>(`/api/admin/assets/device/${deviceId}/stop`)
}

/**
 * 设备复机 (批量复机设备下所有已实名卡)
 * @deprecated 使用 startAsset 代替，路由: POST /api/admin/assets/:identifier/start
 */
export function startDeviceAsset(deviceId: number) {
  return post<void>(`/api/admin/assets/device/${deviceId}/start`)
}

/**
 * 单卡停机 (通过ICCID)
 * @deprecated 使用 stopAsset 代替，路由: POST /api/admin/assets/:identifier/stop
 */
export function stopCardByIccid(iccid: string) {
  return post<void>(`/api/admin/assets/card/${iccid}/stop`)
}

/**
 * 单卡复机 (通过ICCID)
 * @deprecated 使用 startAsset 代替，路由: POST /api/admin/assets/:identifier/start
 */
export function startCardByIccid(iccid: string) {
  return post<void>(`/api/admin/assets/card/${iccid}/start`)
}

/**
 * 统一停机接口 (卡/设备)
 * POST /api/admin/assets/:identifier/stop
 * @param identifier ICCID 或 VirtualNo
 * @param reason 停机原因
 */
export function stopAsset(identifier: string, reason?: string) {
  return post<void>(`/api/admin/assets/${identifier}/stop`, {
    data: { reason },
  })
}

/**
 * 统一复机接口 (卡/设备)
 * POST /api/admin/assets/:identifier/start
 * @param identifier ICCID 或 VirtualNo
 * @param reason 复机原因
 */
export function startAsset(identifier: string, reason?: string) {
  return post<void>(`/api/admin/assets/${identifier}/start`, {
    data: { reason },
  })
}

/**
 * 统一停用接口 (卡/设备)
 * POST /api/admin/assets/:identifier/deactivate
 * @param identifier ICCID 或 VirtualNo
 */
export function deactivateAsset(identifier: string) {
  return post<void>(`/api/admin/assets/${identifier}/deactivate`)
}

/**
 * 资产钱包信息
 * GET /api/admin/assets/:identifier/wallet
 * @param identifier ICCID 或 VirtualNo
 */
export function getAssetWallet(identifier: string) {
  return get<{
    available_balance: number
    frozen_balance: number
    total_balance: number
  }>(`/api/admin/assets/${identifier}/wallet`)
}

/**
 * 资产钱包交易记录
 * GET /api/admin/assets/:identifier/wallet/transactions
 * @param identifier ICCID 或 VirtualNo
 */
export function getAssetWalletTransactions(identifier: string, params?: { page?: number, page_size?: number }) {
  return get<{
    items: Array<{
      id: number
      type: string
      amount: number
      balance_after: number
      remark?: string
      created_at: string
    }>
    page: number
    page_size: number
    total: number
  }>(`/api/admin/assets/${identifier}/wallet/transactions`, { params })
}

/**
 * 更新资产轮询状态
 * PATCH /api/admin/assets/:identifier/polling-status
 * @param identifier ICCID 或 VirtualNo
 */
export function updatePollingStatus(identifier: string, enable: boolean) {
  return patch<void>(`/api/admin/assets/${identifier}/polling-status`, {
    data: { enable_polling: enable },
  })
}

/**
 * 资产历史订单
 * GET /api/admin/assets/:identifier/orders
 * @param identifier ICCID 或 VirtualNo
 * @param params 查询参数
 */
export function getAssetOrders(identifier: string, params?: {
  page?: number
  page_size?: number
  include_previous?: boolean
}) {
  return get<{
    current_generation: {
      generation: number
      identifier: string
      asset_type: string
      total: number
      page: number
      page_size: number
      items: Array<{
        order_no: string
        order_type: string
        payment_status: number
        payment_status_text: string
        total_amount: number
        payment_method: string
        paid_at?: string
        generation: number
        items: Array<{
          package_name: string
          quantity: number
          unit_price: number
          amount: number
        }>
        created_at: string
      }>
    }
    previous_generations?: Array<{
      generation: number
      identifier: string
      asset_type: string
      exchange_no: string
      exchanged_at: string
      total: number
    }>
    truncated?: boolean
  }>(`/api/admin/assets/${identifier}/orders`, { params })
}
