<template>
  <div>
    <div v-if="isServicesPortal" class="portal-bar">
      <span class="portal-bar-title">授权管理</span>
      <el-select :model-value="appKey" placeholder="选择应用" style="width:220px" @change="switchApp">
        <el-option v-for="a in portalApps" :key="a.appKey" :label="a.name" :value="a.appKey" />
      </el-select>
    </div>
    <el-page-header v-else @back="$router.back()" :content="`授权管理 - ${appName}`" style="margin-bottom:20px" />
    <el-empty v-if="isServicesPortal && !appKey" description="请选择一个应用" style="margin-top:80px" />

    <div v-if="isServicesPortal && appKey && checkingService" v-loading="true" style="min-height:200px" />

    <template v-if="isServicesPortal && appKey && serviceEnabled === false">
      <el-empty :image-size="80" description="当前应用未开通授权管理服务" style="margin-top:60px">
        <el-button type="primary" @click="showActivationDialog = true">申请开通</el-button>
      </el-empty>
      <el-dialog v-model="showActivationDialog" title="申请开通授权管理" width="460px">
        <el-form label-width="80px">
          <el-form-item label="服务">授权管理</el-form-item>
          <el-form-item label="申请理由">
            <el-input v-model="activationReason" 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="submitActivation">提交申请</el-button>
        </template>
      </el-dialog>
    </template>

    <template v-if="!isServicesPortal || (appKey && serviceEnabled === true)">
      <el-row :gutter="16" class="stat-grid">
        <el-col :xs="24" :sm="12" :md="6" v-for="item in statCards" :key="item.label">
          <el-card shadow="never">
            <div class="stat-card">
              <span class="stat-value">{{ item.value }}</span>
              <span class="stat-label">{{ item.label }}</span>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-card shadow="never" style="margin-top:16px">
        <div class="license-summary">
          <el-descriptions :column="isMobile ? 1 : 3" border>
            <el-descriptions-item label="应用">{{ appName }}</el-descriptions-item>
            <el-descriptions-item label="AppKey">{{ appKey || '-' }}</el-descriptions-item>
            <el-descriptions-item label="授权状态">
              <el-tag :type="license?.isActive ? 'success' : 'danger'" size="small">
                {{ license?.isActive ? '正常' : '停用' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="最大设备数">
              <div v-if="!editingMaxDevices" class="max-devices-display">
                <span>{{ license?.maxDevices ?? '-' }}</span>
                <el-button link type="primary" size="small" style="margin-left:8px" @click="startEditMaxDevices">修改</el-button>
              </div>
              <div v-else class="max-devices-edit">
                <el-input-number v-model="editMaxDevicesValue" :min="1" :max="999999" size="small" />
                <el-button type="primary" size="small" :loading="savingMaxDevices" style="margin-left:8px" @click="saveMaxDevices">保存</el-button>
                <el-button size="small" style="margin-left:4px" @click="editingMaxDevices = false">取消</el-button>
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="已注册设备">{{ license?.registeredDevices ?? devices.length }}</el-descriptions-item>
            <el-descriptions-item label="过期时间">
              <div v-if="!editingExpiresAt" class="max-devices-display">
                <span>{{ license?.expiresAt ? formatDate(license.expiresAt) : '永久' }}</span>
                <el-button link type="primary" size="small" style="margin-left:8px" @click="startEditExpiresAt">修改</el-button>
              </div>
              <div v-else class="max-devices-edit">
                <el-date-picker
                  v-model="editExpiresAtValue"
                  type="datetime"
                  placeholder="留空表示永久"
                  clearable
                  style="width:200px"
                  size="small"
                />
                <el-button type="primary" size="small" :loading="savingExpiresAt" style="margin-left:8px" @click="saveExpiresAt">保存</el-button>
                <el-button size="small" style="margin-left:4px" @click="editingExpiresAt = false">取消</el-button>
              </div>
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <div class="toolbar responsive-toolbar">
          <el-button @click="loadData" :loading="loading">刷新</el-button>
        </div>

        <div class="table-wrap">
          <el-table :data="devices" v-loading="loading" border stripe>
            <el-table-column prop="deviceId" label="设备ID" min-width="220" />
            <el-table-column prop="deviceName" label="设备名称" min-width="130">
              <template #default="{ row }">{{ row.deviceName || '-' }}</template>
            </el-table-column>
            <el-table-column label="用户" min-width="180">
              <template #default="{ row }">
                <div class="stack-cell">
                  <span>{{ row.userName || row.userId || '-' }}</span>
                  <small v-if="row.userName && row.userId">{{ row.userId }}</small>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="联系方式" min-width="190">
              <template #default="{ row }">
                <div class="stack-cell">
                  <span>{{ row.userPhone || '-' }}</span>
                  <small v-if="row.userEmail">{{ row.userEmail }}</small>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="设备信息" min-width="190">
              <template #default="{ row }">
                <div class="stack-cell">
                  <span>{{ [row.deviceVendor, row.deviceModel].filter(Boolean).join(' ') || '-' }}</span>
                  <small v-if="row.osVersion">{{ row.osVersion }}</small>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="注册时间" width="170">
              <template #default="{ row }">{{ formatDate(row.registeredAt) }}</template>
            </el-table-column>
            <el-table-column label="最后验证" width="170">
              <template #default="{ row }">{{ row.lastVerifiedAt ? formatDate(row.lastVerifiedAt) : '-' }}</template>
            </el-table-column>
            <el-table-column label="状态" width="90">
              <template #default="{ row }">
                <el-tag :type="row.isActive ? 'success' : 'danger'" size="small">
                  {{ row.isActive ? '正常' : '吊销' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" fixed="right">
              <template #default="{ row }">
                <el-button v-if="row.isActive" size="small" type="danger" plain @click="revokeDevice(row)">吊销</el-button>
                <el-button v-else size="small" type="success" plain @click="reactivateDevice(row)">激活</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </template>
  </div>
</template>

<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { licenseApi, type AppLicense, type LicenseDevice } from '@/api/license'
import { appApi, type App } from '@/api/app'
import { formatTime } from '@/utils/date'
import {
  connectServiceActivationRealtime,
  disconnectServiceActivationRealtime,
  type ServiceActivationRefreshEvent,
} from '@/services/storeReviewRealtime'

const route = useRoute()
const router = useRouter()

const isMobile = ref(false)
const appKey = computed(() => (route.params.appKey as string) || (route.query.appKey as string) || '')
const isServicesPortal = computed(() => route.path.startsWith('/services/'))

const serviceEnabled = ref<boolean | null>(null)
const checkingService = ref(false)
const showActivationDialog = ref(false)
const activationReason = ref('')
const submittingActivation = ref(false)

const portalApps = ref<App[]>([])
const currentApp = ref<App | null>(null)
const license = ref<AppLicense | null>(null)
const devices = ref<LicenseDevice[]>([])
const loading = ref(false)
const editingMaxDevices = ref(false)
const editMaxDevicesValue = ref(1)
const savingMaxDevices = ref(false)
const editingExpiresAt = ref(false)
const editExpiresAtValue = ref<Date | null>(null)
const savingExpiresAt = ref(false)

const appName = computed(() => currentApp.value?.name || license.value?.name || appKey.value || '-')
const activeDevices = computed(() => devices.value.filter(d => d.isActive).length)
const revokedDevices = computed(() => devices.value.filter(d => !d.isActive).length)

const statCards = computed(() => [
  { label: '最大设备数', value: license.value?.maxDevices ?? '-' },
  { label: '已注册设备', value: license.value?.registeredDevices ?? devices.value.length },
  { label: '正常设备', value: activeDevices.value },
  { label: '吊销设备', value: revokedDevices.value },
])

async function loadData() {
  const key = appKey.value
  if (!key) return
  loading.value = true
  try {
    const [licenseRes, appRes] = await Promise.all([
      licenseApi.getAppLicense(key),
      appApi.get(key).catch(() => null),
    ])
    license.value = licenseRes.data.data.license
    devices.value = licenseRes.data.data.devices || []
    currentApp.value = appRes?.data.data ?? portalApps.value.find(item => item.appKey === key) ?? null
  } finally {
    loading.value = false
  }
}

function startEditMaxDevices() {
  editMaxDevicesValue.value = license.value?.maxDevices ?? 1
  editingMaxDevices.value = true
}

async function saveMaxDevices() {
  const key = appKey.value
  if (!key) return
  savingMaxDevices.value = true
  try {
    const res = await licenseApi.updateAppLicense(key, { maxDevices: editMaxDevicesValue.value })
    license.value = res.data.data
    editingMaxDevices.value = false
    ElMessage.success('最大设备数已更新')
  } catch {
    ElMessage.error('更新失败')
  } finally {
    savingMaxDevices.value = false
  }
}

function startEditExpiresAt() {
  editExpiresAtValue.value = license.value?.expiresAt ? new Date(license.value.expiresAt) : null
  editingExpiresAt.value = true
}

async function saveExpiresAt() {
  const key = appKey.value
  if (!key) return
  savingExpiresAt.value = true
  try {
    const expiresAt = editExpiresAtValue.value ? editExpiresAtValue.value.toISOString() : ''
    const res = await licenseApi.updateAppLicense(key, { expiresAt })
    license.value = res.data.data
    editingExpiresAt.value = false
    ElMessage.success('过期时间已更新')
  } catch {
    ElMessage.error('更新失败')
  } finally {
    savingExpiresAt.value = false
  }
}

async function revokeDevice(row: LicenseDevice) {
  try {
    await ElMessageBox.confirm('确认吊销该设备？', '吊销确认', { type: 'warning' })
    await licenseApi.revokeDevice(row.id)
    ElMessage.success('已吊销')
    loadData()
  } catch (e) {
    // cancelled
  }
}

async function reactivateDevice(row: LicenseDevice) {
  await licenseApi.reactivateDevice(row.id)
  ElMessage.success('已激活')
  loadData()
}

async function checkServiceEnabled(key: string) {
  checkingService.value = true
  serviceEnabled.value = null
  try {
    const res = await appApi.getServices(key)
    const enabled = res.data.data.some(s => s.serviceType === 'LICENSE' && s.enabled)
    serviceEnabled.value = enabled
    if (enabled) loadData()
  } catch {
    serviceEnabled.value = false
  } finally {
    checkingService.value = false
  }
}

async function submitActivation() {
  if (!activationReason.value.trim()) {
    ElMessage.warning('请填写申请理由')
    return
  }
  submittingActivation.value = true
  try {
    await appApi.requestActivation(appKey.value, 'LICENSE', activationReason.value.trim())
    ElMessage.success('申请已提交，等待运营审核')
    showActivationDialog.value = false
    activationReason.value = ''
  } catch {
    ElMessage.error('提交失败')
  } finally {
    submittingActivation.value = false
  }
}

function switchApp(key: string) {
  router.push(`/services/license/${key}`)
}

const formatDate = formatTime

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

function connectLicenseRealtime(key: string) {
  void connectServiceActivationRealtime(key, (event: ServiceActivationRefreshEvent) => {
    if (event.serviceType !== 'LICENSE') return
    if (event.status === 'APPROVED') {
      ElMessage.success('授权管理服务已审核通过')
      checkServiceEnabled(key)
    } else if (event.status === 'REJECTED') {
      ElMessage.error(`授权管理服务审核未通过：${event.reviewNote || '请联系运营'}`)
      checkServiceEnabled(key)
    }
  })
}

watch(appKey, (key) => {
  if (isServicesPortal.value) {
    if (key) checkServiceEnabled(key)
  } else {
    loadData()
  }
  if (key) connectLicenseRealtime(key)
})

onMounted(() => {
  updateViewport()
  window.addEventListener('resize', updateViewport)
  if (isServicesPortal.value) {
    appApi.list().then(res => {
      portalApps.value = res.data.data || []
      currentApp.value = portalApps.value.find(item => item.appKey === appKey.value) ?? currentApp.value
    })
    if (appKey.value) checkServiceEnabled(appKey.value)
  } else {
    loadData()
  }
  if (appKey.value) connectLicenseRealtime(appKey.value)
})

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

<style scoped>
.stat-grid { margin-bottom: 16px; }
.stat-card { display: flex; flex-direction: column; align-items: center; padding: 12px; }
.stat-value { font-size: 28px; font-weight: 700; color: #0E7BF2; }
.stat-label { font-size: 13px; color: #64748b; margin-top: 4px; }
.license-summary { margin-bottom: 16px; }
.toolbar { margin-bottom: 12px; display: flex; gap: 8px; flex-wrap: wrap; }
.table-wrap { overflow-x: auto; }
.portal-bar { display: flex; align-items: center; gap: 12px; margin-bottom: 20px; }
.portal-bar-title { font-size: 18px; font-weight: 600; }
.stack-cell { display: flex; flex-direction: column; gap: 2px; line-height: 1.35; }
.stack-cell small { color: #909399; font-size: 12px; }
.max-devices-display { display: flex; align-items: center; }
.max-devices-edit { display: flex; align-items: center; }
</style>
