<template>
  <div v-if="app">
    <el-page-header @back="$router.back()" :content="app.name" style="margin-bottom:24px" />

    <el-card class="info-card" style="margin-bottom:16px">
      <template #header>
        <div style="display:flex;justify-content:space-between;align-items:center">
          <span>应用信息</span>
          <el-button size="small" @click="openEditDialog">编辑</el-button>
        </div>
      </template>
      <el-descriptions :column="isMobile ? 1 : 2" border>
        <el-descriptions-item label="应用名称">{{ app.name }}</el-descriptions-item>
        <el-descriptions-item label="Android 包名">{{ app.packageName }}</el-descriptions-item>
        <el-descriptions-item label="iOS Bundle ID">{{ app.iosBundleId || '-' }}</el-descriptions-item>
        <el-descriptions-item label="鸿蒙 Bundle Name">{{ app.harmonyBundleName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="AppKey">
          <el-text class="mono">{{ app.appKey }}</el-text>
          <el-button link @click="copy(app.appKey)"><el-icon><CopyDocument /></el-icon></el-button>
        </el-descriptions-item>
        <el-descriptions-item label="AppSecret">
          <el-text class="mono">{{ revealedSecret ?? '••••••••••••••••' }}</el-text>
          <el-button link @click="openVerifyDialog('REVEAL_SECRET')" title="查看">
            <el-icon><View /></el-icon>
          </el-button>
          <el-button v-if="revealedSecret" link @click="copy(revealedSecret!)">
            <el-icon><CopyDocument /></el-icon>
          </el-button>
          <el-button link type="warning" @click="openVerifyDialog('RESET_SECRET')">重置</el-button>
        </el-descriptions-item>
        <el-descriptions-item label="简述" :span="2">{{ app.description || '-' }}</el-descriptions-item>
        <el-descriptions-item label="Config 文件">
          <el-button size="small" type="primary" plain @click="downloadConfigFile">下载</el-button>
          <el-button size="small" plain @click="openRegenerateDialog">重新生成</el-button>
          <div class="config-metadata">
            <span>版本：{{ app.configFileRevision ?? '尚未生成' }}</span>
            <span>签发：{{ app.configFileIssuedAt ? formatTime(app.configFileIssuedAt) : '-' }}</span>
            <span>有效期：{{ app.configFileExpiresAt ? formatTime(app.configFileExpiresAt) : '长期有效' }}</span>
          </div>
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <el-card class="info-card" style="margin-bottom:16px">
      <template #header>即时通讯服务</template>
      <div class="service-grid">
        <el-card class="service-card">
          <div class="service-header">
            <span class="service-name">{{ serviceLabel('IM') }}</span>
            <el-switch :model-value="imEnabled" @change="(val: boolean) => onToggleService('IM', val)" />
          </div>
          <template v-if="imService">
            <div style="margin-top:10px;display:flex;gap:8px;flex-wrap:wrap">
              <el-button size="small" @click="$router.push({ path: `/apps/${app.appKey}/im`, query: { appKey: app.appKey } })">
                即时通讯管理 →
              </el-button>
              <el-button size="small" type="primary" plain @click="$router.push(`/apps/${app.appKey}/im-config`)">
                服务配置 →
              </el-button>
            </div>
          </template>
          <template v-else>
            <div style="margin-top:10px">
              <el-button size="small" type="primary" plain @click="openActivationRequest('IM')">
                申请开通
              </el-button>
            </div>
          </template>
        </el-card>
      </div>
    </el-card>

    <el-card class="info-card">
      <template #header>离线推送</template>
      <div class="service-grid">
        <el-card class="service-card">
          <div class="service-header">
            <div class="service-title-block">
              <span class="service-name">{{ serviceLabel('PUSH') }}</span>
              <span class="service-help">{{ serviceHelp('PUSH') }}</span>
            </div>
            <el-switch
              :model-value="isServiceEnabled('PUSH')"
              @change="(val: boolean) => onToggleService('PUSH', val)"
            />
          </div>
          <div class="service-status-row">
            <el-tag :type="isServiceEnabled('PUSH') ? 'success' : 'info'" size="small">
              {{ isServiceEnabled('PUSH') ? '已开通' : '未开通' }}
            </el-tag>
            <span class="service-status-text">
              推送服务开通后即可在终端接收设备级推送。
            </span>
          </div>
          <div class="service-actions">
            <template v-if="isServiceEnabled('PUSH')">
              <el-button size="small" type="primary" plain @click="$router.push(`/apps/${app.appKey}/push-config`)">
                推送配置 →
              </el-button>
              <el-button size="small" @click="$router.push(`/apps/${app.appKey}/push-management`)">
                推送管理 →
              </el-button>
            </template>
            <el-button v-else size="small" type="primary" plain @click="openActivationRequest('PUSH')">
              申请开通
            </el-button>
          </div>
        </el-card>
      </div>
    </el-card>

    <el-card class="info-card" style="margin-top:16px">
      <template #header>版本管理</template>
      <div class="service-grid">
        <el-card class="service-card">
          <div class="service-header">
            <div class="service-title-block">
              <span class="service-name">{{ serviceLabel('UPDATE') }}</span>
              <span class="service-help">{{ serviceHelp('UPDATE') }}</span>
            </div>
            <el-switch
              :model-value="isServiceEnabled('UPDATE')"
              @change="(val: boolean) => onToggleService('UPDATE', val)"
            />
          </div>
          <div class="service-status-row">
            <el-tag :type="isServiceEnabled('UPDATE') ? 'success' : 'info'" size="small">
              {{ isServiceEnabled('UPDATE') ? '已开通' : '未开通' }}
            </el-tag>
            <span class="service-status-text">
              Android 整包版本在版本管理页上传；iOS / 鸿蒙仅记录版本号和市场跳转页。商店配置与发布配置都在版本管理页。
            </span>
          </div>
          <div class="service-actions">
            <el-button v-if="isServiceEnabled('UPDATE')" size="small" type="primary" plain @click="$router.push(`/apps/${app.appKey}/update`)">
              版本管理 →
            </el-button>
            <el-button v-else size="small" type="primary" plain @click="openActivationRequest('UPDATE')">
              申请开通
            </el-button>
          </div>
        </el-card>
      </div>
    </el-card>

    <el-card class="info-card" style="margin-top:16px">
      <template #header>崩溃收集</template>
      <div class="service-grid">
        <el-card class="service-card">
          <div class="service-header">
            <div class="service-title-block">
              <span class="service-name">{{ serviceLabel('BUG_COLLECT') }}</span>
              <span class="service-help">{{ serviceHelp('BUG_COLLECT') }}</span>
            </div>
            <el-switch
              :model-value="isServiceEnabled('BUG_COLLECT')"
              @change="(val: boolean) => onToggleService('BUG_COLLECT', val)"
            />
          </div>
          <div class="service-status-row">
            <el-tag :type="isServiceEnabled('BUG_COLLECT') ? 'success' : 'info'" size="small">
              {{ isServiceEnabled('BUG_COLLECT') ? '已开通' : '未开通' }}
            </el-tag>
            <span class="service-status-text">
              采集 App 崩溃、异常与自定义事件，支持漏斗分析和 Webhook 告警。
            </span>
          </div>
          <div class="service-actions">
            <template v-if="isServiceEnabled('BUG_COLLECT')">
              <el-button size="small" type="primary" plain @click="$router.push({ path: '/bugcollect/overview', query: { appKey: app.appKey } })">
                崩溃概览 →
              </el-button>
              <el-button size="small" @click="$router.push({ path: '/bugcollect/issues', query: { appKey: app.appKey } })">
                错误列表 →
              </el-button>
            </template>
            <el-button v-else size="small" type="primary" plain @click="openActivationRequest('BUG_COLLECT')">
              申请开通
            </el-button>
          </div>
        </el-card>
      </div>
    </el-card>

    <!-- API Key 管理 -->
    <el-card class="info-card" style="margin-top:16px">
      <template #header>
        <div style="display:flex;justify-content:space-between;align-items:center">
          <span>API Key 管理</span>
          <el-button size="small" type="primary" @click="openCreateApiKey" :disabled="apiKeys.length >= 8">
            创建 API Key
          </el-button>
        </div>
      </template>
      <p style="color:#606266;font-size:13px;margin-bottom:12px">
        API Key 用于外部工具（Postman / CI/CD）调用平台 API 进行认证，支持 update / push / im / bugcollect 等服务。每个应用最多 8 个，创建后仅显示一次。
      </p>
      <el-table :data="apiKeys" v-loading="loadingApiKeys" border stripe>
        <el-table-column prop="name" label="名称" min-width="120" />
        <el-table-column label="API Key" min-width="200">
          <template #default="{ row }">
            <el-text class="mono">{{ row.apiKey }}</el-text>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.enabled ? 'success' : 'info'" size="small">
              {{ row.enabled ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="170">
          <template #default="{ row }">{{ formatTime(row.createdAt) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button link :type="row.enabled ? 'warning' : 'success'" size="small" @click="toggleApiKey(row)">
              {{ row.enabled ? '禁用' : '启用' }}
            </el-button>
            <el-button link type="danger" size="small" @click="deleteApiKey(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- Create API Key Dialog -->
    <el-dialog v-model="showCreateApiKey" title="创建 API Key" :width="dialogWidth">
      <el-form label-width="80px">
        <el-form-item label="名称">
          <el-input v-model="newApiKeyName" placeholder="如：CI Pipeline、Postman 测试（可选）" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateApiKey = false">取消</el-button>
        <el-button type="primary" :loading="creatingApiKey" @click="submitCreateApiKey">创建</el-button>
      </template>
    </el-dialog>

    <!-- API Key Created Result Dialog -->
    <el-dialog v-model="showApiKeyResult" title="API Key 已创建" :width="dialogWidth" :close-on-click-modal="false">
      <el-alert type="warning" :closable="false" show-icon style="margin-bottom:16px">
        <template #title>请立即复制保存，关闭后无法再次查看完整内容</template>
      </el-alert>
      <div class="api-key-result-box">{{ createdApiKey }}</div>
      <el-button type="primary" plain size="small" style="margin-top:12px" @click="copyApiKey">复制 API Key</el-button>
      <template #footer>
        <el-button type="primary" @click="showApiKeyResult = false">我已保存，关闭</el-button>
      </template>
    </el-dialog>

    <!-- Email Verify Dialog (reveal or reset) -->
    <el-dialog v-model="showVerifyDialog" :title="verifyPurpose === 'REVEAL_SECRET' ? '查看 AppSecret' : '重置 AppSecret'" :width="dialogWidth">
      <div v-if="!codeSent">
        <p style="color:#555;margin-bottom:16px">
          {{ verifyPurpose === 'REVEAL_SECRET'
            ? '为保护账号安全，查看 AppSecret 需要通过邮箱验证。'
            : '重置后旧 AppSecret 立即失效，请确认后继续。' }}
        </p>
        <el-button type="primary" :loading="sendingCode" @click="sendVerifyCode">
          发送验证码到邮箱
        </el-button>
      </div>
      <div v-else>
        <p style="color:#555;margin-bottom:16px">验证码已发送至您的注册邮箱，请查收并输入：</p>
        <el-input v-model="verifyCode" placeholder="6位验证码" maxlength="6" style="margin-bottom:12px" />
        <div style="display:flex;gap:8px">
          <el-button @click="sendVerifyCode" :loading="sendingCode" size="small">重新发送</el-button>
        </div>
      </div>
      <template #footer>
        <el-button @click="showVerifyDialog = false">取消</el-button>
        <el-button v-if="codeSent" type="primary" :loading="submittingVerify" @click="submitVerify">
          {{ verifyPurpose === 'REVEAL_SECRET' ? '查看' : '确认重置' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- Edit App Info Dialog -->
    <el-dialog v-model="showEditDialog" title="编辑应用信息" :width="dialogWidth">
      <el-form label-width="120px" :model="editForm">
        <el-form-item label="应用名称">
          <el-input v-model="editForm.name" placeholder="应用名称" />
        </el-form-item>
        <el-form-item label="Android 包名">
          <el-input v-model="editForm.packageName" placeholder="com.example.app（可选）" />
        </el-form-item>
        <el-form-item label="iOS Bundle ID">
          <el-input v-model="editForm.iosBundleId" placeholder="com.example.app（可选）" />
        </el-form-item>
        <el-form-item label="鸿蒙 Bundle Name">
          <el-input v-model="editForm.harmonyBundleName" placeholder="com.example.app（可选）" />
        </el-form-item>
        <el-form-item label="简述">
          <el-input v-model="editForm.description" type="textarea" :rows="3" placeholder="应用简述（可选）" />
        </el-form-item>
        <el-form-item label="图标 URL">
          <el-input v-model="editForm.iconUrl" placeholder="https://cdn.example.com/icon.png（可选）" />
        </el-form-item>
      </el-form>
      <div class="form-tip" style="margin-top:-8px">至少填写一个平台的包名</div>
      <template #footer>
        <el-button @click="showEditDialog = false">取消</el-button>
        <el-button type="primary" :loading="savingEdit" @click="submitEdit">保存</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="showRegenerateDialog" title="重新生成 Config 文件" :width="dialogWidth">
      <el-alert
        title="重新生成后旧文件将失效；已安装应用仍可运行，但下次构建必须使用新文件。"
        type="warning"
        :closable="false"
        show-icon
        style="margin-bottom:16px"
      />
      <el-descriptions :column="1" border style="margin-bottom:16px">
        <el-descriptions-item label="当前版本">{{ app.configFileRevision ?? '尚未生成' }}</el-descriptions-item>
        <el-descriptions-item label="配置 ID">{{ app.configFileId || '-' }}</el-descriptions-item>
        <el-descriptions-item label="签发时间">{{ app.configFileIssuedAt ? formatTime(app.configFileIssuedAt) : '-' }}</el-descriptions-item>
        <el-descriptions-item label="到期时间">{{ app.configFileExpiresAt ? formatTime(app.configFileExpiresAt) : '长期有效' }}</el-descriptions-item>
      </el-descriptions>
      <el-form label-width="90px">
        <el-form-item label="有效方式">
          <el-radio-group v-model="configExpiryMode">
            <el-radio value="longTerm">长期有效</el-radio>
            <el-radio value="expiresAt">指定到期时间</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="configExpiryMode === 'expiresAt'" label="到期时间">
          <el-date-picker
            v-model="configExpiresAt"
            type="datetime"
            placeholder="请选择到期时间"
            :disabled-date="date => date.getTime() < Date.now() - 86400000"
            style="width:100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showRegenerateDialog = false">取消</el-button>
        <el-button type="primary" :loading="regenerating" @click="regenerateConfigFile">确认重新生成</el-button>
      </template>
    </el-dialog>

    <!-- Activation Request Dialog -->
    <el-dialog v-model="showActivationDialog" title="申请开通服务" :width="dialogWidth">
      <el-form label-width="80px">
        <el-form-item label="服务">{{ serviceLabel(activationForm.serviceType) }}</el-form-item>
        <el-form-item label="申请理由">
          <el-input v-model="activationForm.reason" type="textarea" :rows="3" placeholder="请描述您的业务场景" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showActivationDialog = false">取消</el-button>
        <el-button type="primary" :loading="submittingActivation" @click="submitActivationRequest">提交申请</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { View } from '@element-plus/icons-vue'
import { appApi, type App, type FeatureService } from '@/api/app'
import client from '@/api/client'
import { formatTime } from '@/utils/date'
import {
  connectServiceActivationRealtime,
  disconnectServiceActivationRealtime,
} from '@/services/storeReviewRealtime'

const route = useRoute()
const app = ref<App | null>(null)
const services = ref<FeatureService[]>([])
const imService = computed(() => services.value.find(s => s.serviceType === 'IM') ?? null)
const imEnabled = computed(() => imService.value?.enabled ?? false)
const isMobile = ref(false)
const dialogWidth = computed(() => (isMobile.value ? 'calc(100vw - 24px)' : '420px'))

const revealedSecret = ref<string | null>(null)

const showVerifyDialog = ref(false)
const verifyPurpose = ref<'REVEAL_SECRET' | 'RESET_SECRET'>('REVEAL_SECRET')
const codeSent = ref(false)
const sendingCode = ref(false)
const verifyCode = ref('')
const submittingVerify = ref(false)

const showActivationDialog = ref(false)
const submittingActivation = ref(false)
const activationForm = ref({ platform: '', serviceType: '', reason: '' })
const regenerating = ref(false)
const showRegenerateDialog = ref(false)
const configExpiryMode = ref<'longTerm' | 'expiresAt'>('longTerm')
const configExpiresAt = ref<Date | null>(null)

// ── API Key Management ──
const apiKeys = ref<{ id: string; appKey: string; apiKey: string; name: string; enabled: boolean; createdAt: string }[]>([])
const loadingApiKeys = ref(false)
const showCreateApiKey = ref(false)
const creatingApiKey = ref(false)
const newApiKeyName = ref('')
const showApiKeyResult = ref(false)
const createdApiKey = ref('')

async function loadApiKeys() {
  if (!app.value) return
  loadingApiKeys.value = true
  try {
    const res = await client.get(`/apps/${app.value.appKey}/api-keys`)
    apiKeys.value = res.data.data
  } catch {
    apiKeys.value = []
  } finally {
    loadingApiKeys.value = false
  }
}

function openCreateApiKey() {
  newApiKeyName.value = ''
  showCreateApiKey.value = true
}

async function submitCreateApiKey() {
  if (!app.value) return
  creatingApiKey.value = true
  try {
    const res = await client.post(`/apps/${app.value.appKey}/api-keys`, {
      name: newApiKeyName.value.trim() || undefined,
    })
    createdApiKey.value = res.data.data.apiKey
    showCreateApiKey.value = false
    showApiKeyResult.value = true
    await loadApiKeys()
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || '创建失败')
  } finally {
    creatingApiKey.value = false
  }
}

async function toggleApiKey(key: { id: string; enabled: boolean }) {
  if (!app.value) return
  try {
    await client.patch(`/apps/${app.value.appKey}/api-keys/${key.id}`, {
      enabled: !key.enabled,
    })
    ElMessage.success(key.enabled ? '已禁用' : '已启用')
    await loadApiKeys()
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || '操作失败')
  }
}

async function deleteApiKey(key: { id: string; name: string }) {
  if (!app.value) return
  try {
    await ElMessageBox.confirm(`确定删除 API Key${key.name ? ` "${key.name}"` : ''}？删除后不可恢复。`, '删除 API Key', {
      type: 'warning',
      confirmButtonText: '删除',
      cancelButtonText: '取消',
    })
  } catch { return }
  try {
    await client.delete(`/apps/${app.value.appKey}/api-keys/${key.id}`)
    ElMessage.success('已删除')
    await loadApiKeys()
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || '删除失败')
  }
}

function copyApiKey() {
  navigator.clipboard.writeText(createdApiKey.value)
  ElMessage.success('已复制')
}

const showEditDialog = ref(false)
const savingEdit = ref(false)
const editForm = ref({
  name: '',
  packageName: '',
  iosBundleId: '',
  harmonyBundleName: '',
  description: '',
  iconUrl: '',
})

function openEditDialog() {
  if (!app.value) return
  editForm.value = {
    name: app.value.name || '',
    packageName: app.value.packageName || '',
    iosBundleId: app.value.iosBundleId || '',
    harmonyBundleName: app.value.harmonyBundleName || '',
    description: app.value.description || '',
    iconUrl: app.value.iconUrl || '',
  }
  showEditDialog.value = true
}

async function submitEdit() {
  if (!editForm.value.name.trim()) {
    ElMessage.warning('应用名称不能为空')
    return
  }
  if (!editForm.value.packageName.trim() && !editForm.value.iosBundleId.trim() && !editForm.value.harmonyBundleName.trim()) {
    ElMessage.warning('至少填写一个平台的包名')
    return
  }
  savingEdit.value = true
  try {
    await appApi.update(app.value!.appKey, {
      packageName: editForm.value.packageName.trim() || undefined,
      name: editForm.value.name.trim(),
      iosBundleId: editForm.value.iosBundleId.trim() || undefined,
      harmonyBundleName: editForm.value.harmonyBundleName.trim() || undefined,
      description: editForm.value.description.trim() || undefined,
      iconUrl: editForm.value.iconUrl.trim() || undefined,
    })
    ElMessage.success('应用信息已更新')
    showEditDialog.value = false
    await loadData()
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || '保存失败')
  } finally {
    savingEdit.value = false
  }
}

function isServiceEnabled(svcType: string) {
  return services.value.some(s => s.serviceType === svcType && s.enabled)
}

function serviceLabel(type: string) {
  return {
    IM: '即时通讯 (IM)',
    PUSH: '离线推送',
    UPDATE: '版本管理',
    BUG_COLLECT: '崩溃收集 (BugCollect)',
  }[type] ?? type
}

function serviceHelp(type: string) {
  return {
    IM: 'IM 服务独立开通后，在管理页配置回调和消息能力。',
    PUSH: '一次开通后，可在推送配置页按厂商维护配置。',
    UPDATE: '一次开通后，版本管理页独立管理版本上传、商店配置和灰度发布。',
    BUG_COLLECT: '采集 App 崩溃与自定义事件，支持漏斗分析和 Webhook 告警。',
  }[type] ?? ''
}

function getServiceRepresentative(svcType: string) {
  return services.value.find(s => s.serviceType === svcType) ?? null
}

async function loadData() {
  const appKey = route.params.appKey as string
  const [appRes, svcRes] = await Promise.all([
    appApi.get(appKey), appApi.getServices(appKey),
  ])
  app.value = appRes.data.data
  services.value = svcRes.data.data
  revealedSecret.value = null
  loadApiKeys()
}

async function onToggleService(svcType: string, enable: boolean) {
  if (enable) {
    openActivationRequest(svcType)
  } else {
    await ElMessageBox.confirm(`确认关闭 ${serviceLabel(svcType)} 服务？`, '关闭服务', {
      type: 'warning', confirmButtonText: '确认关闭', cancelButtonText: '取消',
    })
    const platform = getServiceRepresentative(svcType)?.platform ?? 'ANDROID'
    await appApi.toggleService(app.value?.appKey ?? (route.params.appKey as string), platform, svcType, false)
    ElMessage.success('已关闭')
    loadData()
  }
}

function openActivationRequest(svcType: string) {
  activationForm.value = { platform: 'ANDROID', serviceType: svcType, reason: '' }
  showActivationDialog.value = true
}

async function submitActivationRequest() {
  if (!activationForm.value.reason.trim()) {
    return ElMessage.warning('请填写申请理由')
  }
  submittingActivation.value = true
  try {
    await client.post(`/apps/${app.value?.appKey ?? (route.params.appKey as string)}/services/request-activation`, null, {
      params: {
        platform: activationForm.value.platform,
        serviceType: activationForm.value.serviceType,
        applyReason: activationForm.value.reason,
      },
    })
    ElMessage.success('申请已提交，等待运营审核')
    showActivationDialog.value = false
  } finally {
    submittingActivation.value = false
  }
}

function openVerifyDialog(purpose: 'REVEAL_SECRET' | 'RESET_SECRET') {
  verifyPurpose.value = purpose
  codeSent.value = false
  verifyCode.value = ''
  showVerifyDialog.value = true
}

async function sendVerifyCode() {
  sendingCode.value = true
  try {
    await appApi.requestSecretVerify(app.value?.appKey ?? (route.params.appKey as string), verifyPurpose.value)
    codeSent.value = true
    ElMessage.success('验证码已发送')
  } catch {
    ElMessage.error('发送失败，请稍后重试')
  } finally {
    sendingCode.value = false
  }
}

async function submitVerify() {
  if (verifyCode.value.length !== 6) return ElMessage.warning('请输入6位验证码')
  submittingVerify.value = true
  try {
    const appKey = app.value?.appKey ?? (route.params.appKey as string)
    if (verifyPurpose.value === 'REVEAL_SECRET') {
      const res = await appApi.revealSecret(appKey, verifyCode.value)
      revealedSecret.value = res.data.data.appSecret
      ElMessage.success('AppSecret 已显示，请妥善保管')
    } else {
      const res = await appApi.resetSecret(appKey, verifyCode.value)
      revealedSecret.value = res.data.data.appSecret
      ElMessage.success('AppSecret 已重置，旧密钥立即失效')
    }
    showVerifyDialog.value = false
  } catch {
    ElMessage.error('验证码错误或已过期')
  } finally {
    submittingVerify.value = false
  }
}

async function downloadConfigFile() {
  const current = app.value
  if (!current) return
  const res = await appApi.downloadConfigFile(current.appKey)
  const disposition = res.headers['content-disposition'] as string | undefined
  const filename = parseFilename(disposition) ?? `${current.name || current.appKey}.xuqmconfig`
  const url = URL.createObjectURL(res.data)
  const link = document.createElement('a')
  link.href = url
  link.download = filename
  document.body.appendChild(link)
  link.click()
  link.remove()
  URL.revokeObjectURL(url)
}

function openRegenerateDialog() {
  configExpiryMode.value = app.value?.configFileExpiresAt ? 'expiresAt' : 'longTerm'
  configExpiresAt.value = app.value?.configFileExpiresAt ? new Date(app.value.configFileExpiresAt) : null
  showRegenerateDialog.value = true
}

async function regenerateConfigFile() {
  const current = app.value
  if (!current) return
  if (configExpiryMode.value === 'expiresAt'
      && (!configExpiresAt.value || configExpiresAt.value.getTime() <= Date.now())) {
    ElMessage.warning('到期时间必须晚于当前时间')
    return
  }
  regenerating.value = true
  try {
    const res = await appApi.regenerateConfigFile(current.appKey, {
      longTerm: configExpiryMode.value === 'longTerm',
      expiresAt: configExpiryMode.value === 'expiresAt' ? configExpiresAt.value!.toISOString() : null,
    })
    const metadata = res.data.data
    app.value = {
      ...current,
      configFileId: metadata.configId,
      configFileRevision: metadata.revision,
      configFileIssuedAt: metadata.issuedAt,
      configFileExpiresAt: metadata.expiresAt,
    }
    showRegenerateDialog.value = false
    ElMessage.success('Config 文件已重新生成，请重新下载')
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || '重新生成失败')
  } finally {
    regenerating.value = false
  }
}

function parseFilename(disposition?: string) {
  if (!disposition) return null
  const encoded = disposition.match(/filename\*=UTF-8''([^;]+)/i)?.[1]
  if (encoded) return decodeURIComponent(encoded)
  const plain = disposition.match(/filename="?([^";]+)"?/i)?.[1]
  return plain ? decodeURIComponent(plain) : null
}

function copy(text: string) {
  navigator.clipboard.writeText(text)
  ElMessage.success('已复制')
}

function updateViewport() {
  isMobile.value = window.innerWidth < 768
}

onMounted(() => {
  const appKey = route.params.appKey as string
  loadData()
  updateViewport()
  window.addEventListener('resize', updateViewport)
  void connectServiceActivationRealtime(appKey, (event) => {
    if (event.status === 'APPROVED') {
      ElMessage.success(`${serviceLabel(event.serviceType)} 已审核通过`)
      loadData()
    } else if (event.status === 'REJECTED') {
      ElMessage.error(`${serviceLabel(event.serviceType)} 审核未通过：${event.reviewNote || '请联系运营'}`)
      loadData()
    }
  })
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', updateViewport)
  disconnectServiceActivationRealtime()
})
</script>

<style scoped>
.mono { font-family: monospace; font-size: 12px; }
.form-tip { font-size: 12px; color: var(--el-text-color-secondary); margin-top: 4px; }
.config-metadata { display:flex; flex-direction:column; margin-top:8px; color:var(--el-text-color-secondary); font-size:12px; line-height:1.7; }
.api-key-result-box {
  font-family: monospace;
  font-size: 13px;
  word-break: break-all;
  background: #f5f7fa;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 12px 16px;
  line-height: 1.6;
  user-select: all;
}
.info-card :deep(.el-descriptions__body) {
  overflow-x: auto;
}
.service-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 16px; margin-top: 16px; }
.service-card { border: 1px solid #e8e8e8; }
.service-header { display: flex; justify-content: space-between; align-items: flex-start; gap: 12px; font-weight: 500; }
.service-name { font-size: 15px; }
.service-title-block { display: flex; flex-direction: column; gap: 4px; }
.service-help { font-size: 12px; color: #6b7280; line-height: 1.4; }
.service-status-row { display: flex; align-items: center; gap: 10px; margin-top: 12px; flex-wrap: wrap; }
.service-status-text { font-size: 13px; color: #6b7280; line-height: 1.5; }
.service-actions { margin-top: 12px; display: flex; gap: 8px; flex-wrap: wrap; }

@media (max-width: 767px) {
  .service-grid {
    grid-template-columns: 1fr;
  }

  .service-header {
    flex-direction: column;
  }

  .service-actions {
    flex-direction: column;
  }

  .service-actions :deep(.el-button) {
    width: 100%;
  }

  .info-card :deep(.el-descriptions__table) {
    min-width: 100%;
  }
}
</style>
