<template>
  <ElCard shadow="never" class="info-card basic-info">
    <template #header>
      <div class="card-header">
        <div class="card-header-left">
          <span>{{ cardInfo?.asset_type === 'card' ? '卡信息' : '设备信息' }}</span>
          <ElTag :type="cardInfo?.asset_type === 'card' ? 'success' : 'primary'" size="small">
            {{ cardInfo?.asset_type === 'card' ? 'IoT卡' : '设备' }}
          </ElTag>
        </div>
        <div class="card-header-right">
          <ElTooltip content="开启后系统将自动轮询更新资产状态" placement="top">
            <div class="polling-switch-wrapper">
              <span class="polling-label">自动轮询</span>
              <ElSwitch
                :model-value="pollingEnabled"
                @update:model-value="handlePollingChange"
                active-text="开"
                inactive-text="关"
                inline-prompt
                size="default"
              />
            </div>
          </ElTooltip>
        </div>
      </div>
    </template>
    <ElDescriptions :column="4" border>
      <!-- 卡专属字段 -->
      <template v-if="cardInfo?.asset_type === 'card'">
        <ElDescriptionsItem label="ICCID">{{ cardInfo?.iccid || '-' }}</ElDescriptionsItem>
        <ElDescriptionsItem label="运营商账户">{{
          cardInfo?.carrier_name || '-'
        }}</ElDescriptionsItem>
        <ElDescriptionsItem label="实名状态">
          <ElTag :type="getRealNameStatusType(cardInfo?.real_name_status)" size="small">
            {{ getRealNameStatusName(cardInfo?.real_name_status) }}
          </ElTag>
        </ElDescriptionsItem>

        <ElDescriptionsItem label="店铺">{{ cardInfo?.shop_name || '-' }}</ElDescriptionsItem>
        <ElDescriptionsItem label="套餐系列">{{ cardInfo?.series_name || '-' }}</ElDescriptionsItem>
        <ElDescriptionsItem label="虚拟号">{{ cardInfo?.virtual_no || '-' }}</ElDescriptionsItem>
        <ElDescriptionsItem label="网络状态">
          <ElTag :type="cardInfo?.network_status === 1 ? 'success' : 'danger'" size="small">
            {{ cardInfo?.network_status === 1 ? '正常' : '停机' }}
          </ElTag>
        </ElDescriptionsItem>

        <ElDescriptionsItem label="本月已用流量">{{
          formatDataSize(cardInfo?.current_month_usage_mb || 0)
        }}</ElDescriptionsItem>
        <ElDescriptionsItem label="实名时间">{{
          cardInfo?.real_name_at ? formatDateTime(cardInfo.real_name_at) : '-'
        }}</ElDescriptionsItem>

        <ElDescriptionsItem label="MSISDN">{{ cardInfo?.msisdn || '-' }}</ElDescriptionsItem>
        <ElDescriptionsItem label="资产状态">
          <ElTag :type="getAssetStatusType(cardInfo?.status)" size="small">
            {{ getAssetStatusName(cardInfo?.status) }}
          </ElTag>
        </ElDescriptionsItem>
      </template>

      <!-- 设备专属字段 -->
      <template v-if="cardInfo?.asset_type === 'device'">
        <ElDescriptionsItem label="IMEI">{{ cardInfo?.imei || '-' }}</ElDescriptionsItem>
        <ElDescriptionsItem label="设备类型">{{ cardInfo?.device_type || '-' }}</ElDescriptionsItem>
        <ElDescriptionsItem label="实名状态">
          <ElTag :type="getRealNameStatusType(currentCard?.real_name_status)" size="small">
            {{ getRealNameStatusName(currentCard?.real_name_status) }}
          </ElTag>
        </ElDescriptionsItem>

        <ElDescriptionsItem label="店铺">{{ cardInfo?.shop_name || '-' }}</ElDescriptionsItem>
        <ElDescriptionsItem label="设备名称">{{ cardInfo?.device_name || '-' }}</ElDescriptionsItem>
        <ElDescriptionsItem label="设备状态">
          <ElTag :type="getAssetStatusType(cardInfo?.status)" size="small">
            {{ getAssetStatusName(cardInfo?.status) }}
          </ElTag>
        </ElDescriptionsItem>

        <ElDescriptionsItem label="虚拟号">{{ cardInfo?.virtual_no || '-' }}</ElDescriptionsItem>
        <ElDescriptionsItem label="SN">{{ cardInfo?.sn || '-' }}</ElDescriptionsItem>
        <ElDescriptionsItem label="设备型号">{{
          cardInfo?.device_model || '-'
        }}</ElDescriptionsItem>

        <ElDescriptionsItem label="供应商">{{ cardInfo?.supplier || '-' }}</ElDescriptionsItem>
        <ElDescriptionsItem label="已绑定卡数">{{
          cardInfo?.bound_card_count || 0
        }}</ElDescriptionsItem>
        <ElDescriptionsItem label="最大卡槽数">{{
          cardInfo?.max_sim_slots || '-'
        }}</ElDescriptionsItem>

        <ElDescriptionsItem label="激活时间">{{
          cardInfo?.activated_at || '-'
        }}</ElDescriptionsItem>
        <ElDescriptionsItem label="实名时间">{{
          cardInfo?.real_name_at ? formatDateTime(cardInfo.real_name_at) : '-'
        }}</ElDescriptionsItem>
        <ElDescriptionsItem label="信号强度">
          <ElTag :type="getSignalStrengthType()" size="small">
            {{ calculateSignalStrength() }}
          </ElTag>
        </ElDescriptionsItem>

        <ElDescriptionsItem label="在线状态">
          <ElTag :type="getOnlineStatusType(cardInfo?.online_status)" size="small">
            {{ getOnlineStatusName(cardInfo?.online_status) }}
          </ElTag>
        </ElDescriptionsItem>
        <ElDescriptionsItem label="固件版本">{{
          cardInfo?.software_version || '-'
        }}</ElDescriptionsItem>
        <ElDescriptionsItem label="切卡模式">{{
          getSwitchModeName(cardInfo?.switch_mode)
        }}</ElDescriptionsItem>

        <ElDescriptionsItem label="最后在线时间">{{
          formatDateTime(cardInfo?.last_online_time) || '-'
        }}</ElDescriptionsItem>
        <ElDescriptionsItem label="最后同步时间">{{
          formatDateTime(cardInfo?.last_gateway_sync_at) || '-'
        }}</ElDescriptionsItem>
        <ElDescriptionsItem label="制造商">{{ cardInfo?.manufacturer || '-' }}</ElDescriptionsItem>
      </template>
    </ElDescriptions>

    <!-- 设备绑定卡列表 -->
    <template v-if="cardInfo?.asset_type === 'device'">
      <ElDivider content-position="left">绑定卡列表</ElDivider>
      <ElTable
        v-if="cardInfo.cards && cardInfo.cards.length > 0"
        :data="sortedDeviceCards"
        border
        style="margin-top: 16px"
      >
        <ElTableColumn label="ICCID">
          <template #default="scope">
            <ElButton type="primary" link @click="handleNavigateToCardInfo(scope.row.iccid)">
              {{ scope.row.iccid }}
            </ElButton>
          </template>
        </ElTableColumn>
        <ElTableColumn prop="msisdn" label="MSISDN" />
        <ElTableColumn prop="carrier_name" label="运营商" width="120" />
        <ElTableColumn prop="slot_position" label="卡槽位置" align="center" width="130">
          <template #default="scope">
            <div style="display: flex; gap: 10px; align-items: center; justify-content: center">
              <span>SIM-{{ scope.row.slot_position }}</span>
              <ElTag v-if="scope.row.is_current" type="primary" size="small">当前</ElTag>
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn label="网络状态" align="center" width="100">
          <template #default="scope">
            <ElTag :type="scope.row.network_status === 1 ? 'success' : 'danger'" size="small">
              {{ scope.row.network_status === 1 ? '正常' : '停机' }}
            </ElTag>
          </template>
        </ElTableColumn>
        <ElTableColumn label="实名状态" align="center" width="100">
          <template #default="scope">
            <ElTag :type="getRealNameStatusType(scope.row.real_name_status)" size="small">
              {{ getRealNameStatusName(scope.row.real_name_status) }}
            </ElTag>
          </template>
        </ElTableColumn>
        <ElTableColumn label="实名时间" width="170">
          <template #default="scope">
            {{ scope.row.real_name_at ? formatDateTime(scope.row.real_name_at) : '-' }}
          </template>
        </ElTableColumn>
        <ElTableColumn label="操作" width="200" align="center">
          <template #default="scope">
            <!-- 根据网络状态显示启用或停用按钮 -->
            <ElButton
              v-if="scope.row.network_status === 0"
              type="success"
              size="small"
              link
              @click="handleEnableBindingCard(scope.row)"
              v-permission="'iot_card:start'"
            >
              启用此卡
            </ElButton>
            <ElButton
              v-if="scope.row.network_status === 1"
              type="warning"
              size="small"
              link
              @click="handleDisableBindingCard(scope.row)"
              v-permission="'iot_card:stop'"
            >
              停用此卡
            </ElButton>
          </template>
        </ElTableColumn>
      </ElTable>
      <ElEmpty v-else description="暂无绑定卡" :image-size="80" style="margin-top: 16px" />

      <!-- 设备实时信息 -->
      <ElDivider content-position="left">设备实时信息</ElDivider>
      <div v-if="deviceRealtime" style="margin-top: 16px">
        <ElDescriptions :column="4" border>
          <!-- 基本状态 -->
          <ElDescriptionsItem label="在线状态">
            <ElTag :type="deviceRealtime.online_status === 1 ? 'success' : 'danger'" size="small">
              {{ deviceRealtime.online_status === 1 ? '在线' : '离线' }}
            </ElTag>
          </ElDescriptionsItem>
          <ElDescriptionsItem label="设备状态">
            <ElTag :type="deviceRealtime.status === 1 ? 'success' : 'info'" size="small">
              {{ deviceRealtime.status === 1 ? '正常' : '禁用' }}
            </ElTag>
          </ElDescriptionsItem>
          <ElDescriptionsItem label="电量">
            {{
              deviceRealtime.battery_level !== null && deviceRealtime.battery_level !== undefined
                ? `${deviceRealtime.battery_level}%`
                : '-'
            }}
          </ElDescriptionsItem>

          <!-- 时间信息 -->
          <ElDescriptionsItem label="本次开机时长">
            {{ formatDuration(deviceRealtime.run_time) }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="本次联网时长">
            {{ formatDuration(deviceRealtime.connect_time) }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="最后在线时间">
            {{ formatDateTime(deviceRealtime.last_online_time) || '-' }}
          </ElDescriptionsItem>

          <!-- 信号信息 -->
          <ElDescriptionsItem label="信号强度(RSSI)">
            {{ deviceRealtime.rssi || '-' }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="接收功率(RSRP)">
            {{ deviceRealtime.rsrp ? `${deviceRealtime.rsrp} dBm` : '-' }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="接收质量(RSRQ)">
            {{ deviceRealtime.rsrq ? `${deviceRealtime.rsrq} dB` : '-' }}
          </ElDescriptionsItem>

          <ElDescriptionsItem label="信噪比(SINR)">
            {{ deviceRealtime.sinr ? `${deviceRealtime.sinr} dB` : '-' }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="最大客户端数">
            {{ deviceRealtime.max_clients || '-' }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="当前使用ICCID">
            {{ deviceRealtime.current_iccid || '-' }}
          </ElDescriptionsItem>

          <!-- WiFi 信息 -->
          <ElDescriptionsItem label="WiFi 状态">
            <ElTag :type="deviceRealtime.wifi_enabled ? 'success' : 'info'" size="small">
              {{ deviceRealtime.wifi_enabled ? '已开启' : '已关闭' }}
            </ElTag>
          </ElDescriptionsItem>
          <ElDescriptionsItem label="WiFi 名称">
            {{ deviceRealtime.ssid || '-' }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="WiFi 密码">
            {{ deviceRealtime.wifi_password || '-' }}
          </ElDescriptionsItem>

          <!-- 网络信息 -->
          <ElDescriptionsItem label="IP 地址">
            {{ deviceRealtime.ip_address || '-' }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="WAN IP">
            {{ deviceRealtime.wan_ip || '-' }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="LAN IP">
            {{ deviceRealtime.lan_ip || '-' }}
          </ElDescriptionsItem>

          <ElDescriptionsItem label="MAC 地址">
            {{ deviceRealtime.mac_address || '-' }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="IMEI">
            {{ deviceRealtime.imei || '-' }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="IMSI">
            {{ deviceRealtime.imsi || '-' }}
          </ElDescriptionsItem>

          <!-- 流量信息 -->
          <ElDescriptionsItem label="今日流量">
            {{ formatDataSize(Number(deviceRealtime.daily_usage || 0) / (1024 * 1024)) }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="本次下载">
            {{ formatDataSize(Number(deviceRealtime.dl_stats || 0) / (1024 * 1024)) }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="本次上传">
            {{ formatDataSize(Number(deviceRealtime.ul_stats || 0) / (1024 * 1024)) }}
          </ElDescriptionsItem>

          <!-- 设备配置 -->
          <ElDescriptionsItem label="限速">
            {{ deviceRealtime.limit_speed ? `${deviceRealtime.limit_speed} KB/s` : '不限速' }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="固件版本">
            {{ deviceRealtime.software_version || '-' }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="切卡模式">
            {{
              deviceRealtime.switch_mode === '0'
                ? '自动'
                : deviceRealtime.switch_mode === '1'
                  ? '手动'
                  : '-'
            }}
          </ElDescriptionsItem>

          <ElDescriptionsItem label="上报周期">
            {{ deviceRealtime.sync_interval ? `${deviceRealtime.sync_interval} 秒` : '-' }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="设备ID">
            {{ deviceRealtime.device_id || '-' }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="信息更新时间">
            {{ formatDateTime(deviceRealtime.last_update_time) || '-' }}
          </ElDescriptionsItem>
        </ElDescriptions>
      </div>
      <ElAlert
        v-else
        title="设备实时信息不可用"
        type="warning"
        :closable="false"
        style="margin-top: 16px"
      >
        <template #default>
          <div>Gateway 不可达或设备离线,无法获取实时信息</div>
        </template>
      </ElAlert>
    </template>

    <!-- IoT卡操作按钮 -->
    <div
      v-if="cardInfo?.asset_type === 'card'"
      class="card-operations"
      style="margin-top: 16px; text-align: right"
    >
      <ElButton type="success" @click="handleEnableCard"> 启用此卡 </ElButton>
      <ElButton type="warning" @click="handleDisableCard"> 停用此卡 </ElButton>
      <ElButton type="danger" @click="handleManualDeactivate"> 手动停用 </ElButton>
    </div>

    <!-- 设备操作按钮 -->
    <div v-else class="device-operations" style="margin-top: 16px; text-align: right">
      <ElButton type="primary" @click="handleRebootDevice"> 重启设备 </ElButton>
      <ElButton type="warning" @click="handleResetDevice"> 恢复出厂 </ElButton>
      <ElButton type="success" @click="handleShowSwitchCard"> 切换SIM卡 </ElButton>
      <ElButton type="primary" @click="handleShowSetWiFi"> 设置WiFi </ElButton>
    </div>
  </ElCard>
</template>

<script setup lang="ts">
  import { computed, toRef } from 'vue'
  import {
    ElCard,
    ElDescriptions,
    ElDescriptionsItem,
    ElTag,
    ElTooltip,
    ElSwitch,
    ElDivider,
    ElTable,
    ElTableColumn,
    ElButton,
    ElEmpty,
    ElAlert
  } from 'element-plus'
  import { useAssetFormatters } from '../composables/useAssetFormatters'
  import { formatDateTime } from '@/utils/business/format'

  // Props
  interface BindingCard {
    id: number
    iccid: string
    msisdn?: string
    carrier_name?: string
    slot_position?: number
    is_current: boolean
    network_status?: number
    real_name_status?: number
    real_name_at?: string
  }

  interface AssetInfo {
    asset_type: 'card' | 'device'
    iccid?: string
    imei?: string
    msisdn?: string
    carrier_name?: string
    real_name_status?: number
    network_status?: number
    current_month_usage_mb?: number
    device_type?: string
    device_name?: string
    device_model?: string
    virtual_no?: string
    sn?: string
    cards?: BindingCard[]
    status?: number
    shop_name?: string
    series_name?: string
    real_name_at?: string
    supplier?: string
    bound_card_count?: number
    max_sim_slots?: number
    activated_at?: string
    online_status?: number
    software_version?: string
    switch_mode?: string
    last_online_time?: string
    last_gateway_sync_at?: string
    manufacturer?: string
  }

  interface DeviceRealtimeInfo {
    online_status?: number
    status?: number
    battery_level?: number
    run_time?: string
    connect_time?: string
    last_online_time?: string
    rssi?: string
    rsrp?: string
    rsrq?: string
    sinr?: string
    max_clients?: number
    current_iccid?: string
    wifi_enabled?: boolean
    ssid?: string
    wifi_password?: string
    ip_address?: string
    wan_ip?: string
    lan_ip?: string
    mac_address?: string
    imei?: string
    imsi?: string
    daily_usage?: string
    dl_stats?: string
    ul_stats?: string
    limit_speed?: number
    software_version?: string
    switch_mode?: string
    sync_interval?: number
    device_id?: string
    last_update_time?: string
  }

  interface Props {
    cardInfo: AssetInfo
    deviceRealtime: DeviceRealtimeInfo | null
    pollingEnabled: boolean
  }

  const props = defineProps<Props>()

  // Emits
  interface Emits {
    (e: 'update:pollingEnabled', value: boolean): void
    (e: 'enableCard'): void
    (e: 'disableCard'): void
    (e: 'manualDeactivate'): void
    (e: 'rebootDevice'): void
    (e: 'resetDevice'): void
    (e: 'showSpeedLimit'): void
    (e: 'showSwitchCard'): void
    (e: 'show-set-wifi'): void
    (e: 'enableBindingCard', payload: { card: BindingCard }): void
    (e: 'disableBindingCard', payload: { card: BindingCard }): void
    (e: 'navigateToCard', iccid: string): void
  }

  const emit = defineEmits<Emits>()

  // 使用格式化工具
  const deviceRealtimeRef = toRef(props, 'deviceRealtime')
  const {
    formatDataSize,
    formatDuration,
    getRealNameStatusName,
    getRealNameStatusType,
    getAssetStatusName,
    getAssetStatusType,
    getOnlineStatusName,
    getOnlineStatusType,
    calculateSignalStrength,
    getSignalStrengthType,
    getSwitchModeName
  } = useAssetFormatters(deviceRealtimeRef)

  // 排序后的设备卡列表（当前卡排在最前面）
  const sortedDeviceCards = computed(() => {
    if (!props.cardInfo?.cards || props.cardInfo.cards.length === 0) {
      return []
    }
    const cards = [...props.cardInfo.cards]
    return cards.sort((a, b) => {
      if (a.is_current && !b.is_current) return -1
      if (!a.is_current && b.is_current) return 1
      return 0
    })
  })

  // 获取当前使用的卡
  const currentCard = computed(() => {
    if (!props.cardInfo?.cards || props.cardInfo.cards.length === 0) {
      return null
    }
    return props.cardInfo.cards.find((card: BindingCard) => card.is_current) || null
  })

  // 处理轮询开关变化
  const handlePollingChange = (value: boolean) => {
    emit('update:pollingEnabled', value)
  }

  // 跳转到卡片信息
  const handleNavigateToCardInfo = (iccid: string) => {
    // 触发搜索事件，让父组件处理
    emit('navigateToCard', iccid)
  }

  // 卡操作
  const handleEnableCard = () => {
    emit('enableCard')
  }

  const handleDisableCard = () => {
    emit('disableCard')
  }

  const handleManualDeactivate = () => {
    emit('manualDeactivate')
  }

  // 设备操作
  const handleRebootDevice = () => {
    emit('rebootDevice')
  }

  const handleResetDevice = () => {
    emit('resetDevice')
  }

  const handleShowSwitchCard = () => {
    emit('showSwitchCard')
  }

  const handleShowSetWiFi = () => {
    emit('show-set-wifi')
  }

  // 绑定卡操作
  const handleEnableBindingCard = (card: BindingCard) => {
    emit('enableBindingCard', { card })
  }

  const handleDisableBindingCard = (card: BindingCard) => {
    emit('disableBindingCard', { card })
  }
</script>

<style scoped lang="scss">
  .info-card {
    &.basic-info {
      .card-header {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .card-header-left {
          display: flex;
          gap: 8px;
          align-items: center;
        }

        .card-header-right {
          .polling-switch-wrapper {
            display: flex;
            gap: 8px;
            align-items: center;

            .polling-label {
              font-size: 14px;
              color: var(--el-text-color-regular);
            }
          }
        }
      }
    }
  }
</style>
