<template>
  <a-card>
    <template #title>授权状态</template>
    
    <a-descriptions :column="1" bordered v-if="authStatus">
      <a-descriptions-item label="激活状态">
        <a-tag :color="authStatus.is_activated ? 'green' : 'red'">
          {{ authStatus.is_activated ? '已激活' : '未激活' }}
        </a-tag>
      </a-descriptions-item>
      
      <a-descriptions-item label="状态信息">
        {{ authStatus.message }}
      </a-descriptions-item>
      
      <a-descriptions-item label="授权码" v-if="authStatus.license_code">
        {{ formatLicenseCode(authStatus.license_code) }}
      </a-descriptions-item>
      
      <a-descriptions-item label="激活时间" v-if="authStatus.activated_at">
        {{ formatDate(authStatus.activated_at) }}
      </a-descriptions-item>
      
      <a-descriptions-item label="过期时间" v-if="authStatus.expires_at">
        {{ formatDate(authStatus.expires_at) }}
      </a-descriptions-item>
      
      <a-descriptions-item label="设备ID">
        <a-typography-text copyable>{{ deviceID }}</a-typography-text>
      </a-descriptions-item>
    </a-descriptions>

    <a-empty v-else description="加载中..." />

    <template #actions>
      <a-button @click="handleRefresh" :loading="loading">刷新状态</a-button>
    </template>
  </a-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Message } from '@arco-design/web-vue'
import { GetAuthStatus, GetDeviceID } from '../../wailsjs/go/main/App'

const authStatus = ref(null)
const deviceID = ref('')
const loading = ref(false)

const formatLicenseCode = (code) => {
  if (!code) return ''
  const cleaned = code.replace(/[\s-]/g, '')
  return cleaned.match(/.{1,4}/g)?.join('-') || cleaned
}

const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  try {
    const date = new Date(dateStr)
    return date.toLocaleString('zh-CN')
  } catch {
    return dateStr
  }
}

const loadAuthStatus = async () => {
  loading.value = true
  try {
    const [statusResult, deviceResult] = await Promise.all([
      GetAuthStatus(),
      GetDeviceID()
    ])
    
    if (statusResult.success) {
      authStatus.value = statusResult.data
    } else {
      Message.error(statusResult.message || '获取授权状态失败')
    }
    
    if (deviceResult) {
      deviceID.value = deviceResult
    }
  } catch (err) {
    Message.error('获取授权状态失败：' + (err.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

const handleRefresh = () => {
  loadAuthStatus()
}

onMounted(() => {
  loadAuthStatus()
})

defineExpose({
  refresh: loadAuthStatus
})
</script>

<style scoped>
</style>
