<template>
  <div class="push-page">
    <el-card class="query-card">
      <template #header>
        <div class="header-row">
          <span>Push 诊断</span>
          <div class="header-actions">
            <el-tag v-if="diagnostics" :type="diagnostics.online ? 'success' : 'info'">
              {{ diagnostics.online ? '用户在线' : '用户离线' }}
            </el-tag>
            <el-button
              v-if="diagnostics?.appKey && diagnostics?.userId"
              type="primary"
              :disabled="!diagnostics.deliverableDevices?.length"
              :loading="testLoading"
              @click="sendTestOffline"
            >
              发送测试离线消息
            </el-button>
          </div>
        </div>
      </template>

      <el-form :model="form" label-width="96px" class="query-form" @submit.prevent="search">
        <el-form-item label="Token">
          <el-input
            v-model="form.token"
            type="textarea"
            :rows="3"
            placeholder="输入 IM token 或厂商 push token"
            clearable
          />
        </el-form-item>
        <el-form-item label="AppId">
          <el-input v-model="form.appKey" placeholder="可选；push token 无法解析 AppId 时使用" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="search">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <template v-if="diagnostics">
      <el-row :gutter="16" class="summary-row">
        <el-col :xs="24" :md="8">
          <el-card>
            <el-statistic title="Token 类型" :value="diagnostics.tokenType" />
          </el-card>
        </el-col>
        <el-col :xs="24" :md="8">
          <el-card>
            <el-statistic title="用户" :value="diagnostics.userId || '-'" />
          </el-card>
        </el-col>
        <el-col :xs="24" :md="8">
          <el-card>
            <el-statistic title="离线消息" :value="diagnostics.canSendOfflineMessage ? '可送达' : '不可送达'" />
          </el-card>
        </el-col>
      </el-row>

      <el-card class="section-card">
        <template #header>当前离线可送达设备</template>
        <el-empty v-if="!diagnostics.deliverableDevices?.length" description="暂无可送达设备" />
        <el-table v-else :data="diagnostics.deliverableDevices" border stripe>
          <el-table-column prop="vendor" label="厂商" width="100" />
          <el-table-column label="设备" min-width="180">
            <template #default="{ row }">{{ deviceName(row) }}</template>
          </el-table-column>
          <el-table-column prop="deviceId" label="DeviceId" min-width="180" show-overflow-tooltip />
          <el-table-column prop="osVersion" label="系统" width="140" />
          <el-table-column prop="tokenPreview" label="Token" min-width="170" />
          <el-table-column label="最近登录" width="180">
            <template #default="{ row }">{{ fmt(row.lastLoginAt) }}</template>
          </el-table-column>
        </el-table>
      </el-card>

      <el-card class="section-card">
        <template #header>当前绑定设备</template>
        <el-table :data="diagnostics.devices" border stripe>
          <el-table-column prop="vendor" label="厂商" width="100" />
          <el-table-column label="设备" min-width="180">
            <template #default="{ row }">{{ deviceName(row) }}</template>
          </el-table-column>
          <el-table-column prop="deviceId" label="DeviceId" min-width="180" show-overflow-tooltip />
          <el-table-column prop="osVersion" label="系统" width="140" />
          <el-table-column prop="tokenPreview" label="Token" min-width="170" />
          <el-table-column label="接收 Push" width="110">
            <template #default="{ row }">
              <el-tag :type="row.receivePush ? 'success' : 'info'">{{ row.receivePush ? '开启' : '关闭' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="最近登录" width="180">
            <template #default="{ row }">{{ fmt(row.lastLoginAt) }}</template>
          </el-table-column>
        </el-table>
      </el-card>

      <el-card class="section-card">
        <template #header>
          <div class="header-row">
            <span>历史登录设备日志</span>
            <el-button :disabled="!diagnostics.appKey || !diagnostics.userId" :loading="logsLoading" @click="loadLogs">
              刷新
            </el-button>
          </div>
        </template>
        <el-table :data="logs" border stripe>
          <el-table-column prop="eventType" label="事件" width="150" />
          <el-table-column prop="vendor" label="厂商" width="100" />
          <el-table-column label="设备" min-width="180">
            <template #default="{ row }">{{ deviceName(row) }}</template>
          </el-table-column>
          <el-table-column prop="deviceId" label="DeviceId" min-width="180" show-overflow-tooltip />
          <el-table-column prop="tokenPreview" label="Token" min-width="170" />
          <el-table-column label="接收 Push" width="110">
            <template #default="{ row }">
              <el-tag :type="row.receivePush ? 'success' : 'info'">{{ row.receivePush ? '开启' : '关闭' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="时间" width="180">
            <template #default="{ row }">{{ fmt(row.createdAt) }}</template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="pager"
          layout="prev, pager, next, total"
          :total="logTotal"
          :page-size="logSize"
          :current-page="logPage + 1"
          @current-change="changeLogPage"
        />
      </el-card>
    </template>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { opsApi, type PushDeviceInfo, type PushDeviceLog, type PushDiagnostics } from '@/api/ops'
import { formatTime } from '@/utils/date'

const form = reactive({ token: '', appKey: '' })
const loading = ref(false)
const logsLoading = ref(false)
const testLoading = ref(false)
const diagnostics = ref<PushDiagnostics | null>(null)
const logs = ref<PushDeviceLog[]>([])
const logTotal = ref(0)
const logPage = ref(0)
const logSize = 20

async function search() {
  if (!form.token.trim()) {
    ElMessage.warning('请输入 token')
    return
  }
  loading.value = true
  try {
    const res = await opsApi.searchPushByToken(form.token.trim(), form.appKey.trim())
    diagnostics.value = res.data.data
    logs.value = []
    logTotal.value = 0
    logPage.value = 0
    if (diagnostics.value.appKey && diagnostics.value.userId) {
      await loadLogs()
    }
  } finally {
    loading.value = false
  }
}

async function loadLogs() {
  if (!diagnostics.value?.appKey || !diagnostics.value?.userId) return
  logsLoading.value = true
  try {
    const res = await opsApi.listPushDeviceLogs(
      diagnostics.value.appKey,
      diagnostics.value.userId,
      logPage.value,
      logSize,
    )
    logs.value = res.data.data.content
    logTotal.value = res.data.data.total
  } finally {
    logsLoading.value = false
  }
}

function changeLogPage(page: number) {
  logPage.value = page - 1
  loadLogs()
}

async function sendTestOffline() {
  if (!diagnostics.value?.appKey || !diagnostics.value?.userId) return
  testLoading.value = true
  try {
    const res = await opsApi.sendPushTestOffline({
      appKey: diagnostics.value.appKey,
      userId: diagnostics.value.userId,
      title: 'XuqmGroup Push 测试',
      body: `离线推送测试 ${formatTime(Date.now())}`,
      payload: JSON.stringify({ type: 'PUSH_TEST', ts: Date.now() }),
    })
    ElMessage.success(`已发送到 ${res.data.data.targetCount} 个设备`)
  } finally {
    testLoading.value = false
  }
}

function deviceName(device: PushDeviceInfo | PushDeviceLog) {
  return [device.brand, device.model].filter(Boolean).join(' ') || '-'
}

const fmt = formatTime
</script>

<style scoped>
.push-page {
  display: flex;
  flex-direction: column;
  gap: 16px;
}
.query-card,
.section-card {
  border-radius: 8px;
}
.header-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
}
.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
  justify-content: flex-end;
}
.query-form {
  max-width: 920px;
}
.summary-row {
  row-gap: 16px;
}
.pager {
  margin-top: 16px;
  justify-content: flex-end;
}
</style>
