<template>
  <div class="space-y-6">
    <!-- 主卡片 -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
      <div class="border-b border-gray-200 pb-4 mb-6">
        <div class="flex items-center justify-between">
          <h2 class="text-xl font-semibold text-gray-800 flex items-center gap-2">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-green-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
            </svg>
            OAuth 授权列表
          </h2>
          <el-button type="primary" @click="handleGetAuthUrl">
            <el-icon><Promotion /></el-icon>
            去授权
          </el-button>
        </div>
      </div>

      <!-- 数据统计 -->
      <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
        <div class="bg-gradient-to-br from-blue-50 to-blue-100 rounded-lg p-4 border border-blue-200">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm text-blue-600 mb-1">总授权数</p>
              <p class="text-2xl font-bold text-blue-700">{{ authList.length }}</p>
            </div>
            <div class="p-3 bg-blue-200 rounded-lg">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-blue-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
              </svg>
            </div>
          </div>
        </div>
        <div class="bg-gradient-to-br from-green-50 to-green-100 rounded-lg p-4 border border-green-200">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm text-green-600 mb-1">有效授权</p>
              <p class="text-2xl font-bold text-green-700">{{ validCount }}</p>
            </div>
            <div class="p-3 bg-green-200 rounded-lg">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-green-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
            </div>
          </div>
        </div>
        <div class="bg-gradient-to-br from-yellow-50 to-yellow-100 rounded-lg p-4 border border-yellow-200">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm text-yellow-600 mb-1">即将过期</p>
              <p class="text-2xl font-bold text-yellow-700">{{ expiringCount }}</p>
            </div>
            <div class="p-3 bg-yellow-200 rounded-lg">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-yellow-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
              </svg>
            </div>
          </div>
        </div>
      </div>

      <!-- 授权列表表格 -->
      <el-table
        :data="authList"
        style="width: 100%"
        v-loading="loading"
        border
        stripe
      >
      <el-table-column prop="state" label="工号" width="150" />
        <el-table-column prop="accountId" label="账户ID" width="150" />
        <el-table-column label="Access Token" width="200">
          <template #default="{ row }">
            <el-text truncated>{{ row.accessToken }}</el-text>
          </template>
        </el-table-column>
        <el-table-column label="过期时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.accessTokenExpiresAt) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '有效' : '失效' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="授权范围" width="150">
          <template #default="{ row }">
            <el-text truncated>{{ row.scope || '-' }}</el-text>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="180">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              link
              @click="handleRefreshToken(row)"
            >
              刷新Token
            </el-button>
            <el-button
              type="info"
              size="small"
              link
              @click="handleViewDetail(row)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="授权详情"
      width="700px"
    >
      <el-descriptions :column="1" border v-if="currentAuth">
        <el-descriptions-item label="工号">
          {{ currentAuth.state }}
        </el-descriptions-item>
        <el-descriptions-item label="账户ID">
          {{ currentAuth.accountId }}
        </el-descriptions-item>
        <el-descriptions-item label="账户UIN">
          {{ currentAuth.accountUin || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="微信账户ID">
          {{ currentAuth.wechatAccountId || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="账户类型">
          {{ currentAuth.accountType || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="账户角色类型">
          {{ currentAuth.accountRoleType || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="角色类型">
          {{ currentAuth.roleType || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="授权范围列表">
          {{ currentAuth.scopeList || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="Access Token">
          <el-text>{{ currentAuth.accessToken }}</el-text>
        </el-descriptions-item>
        <el-descriptions-item label="Refresh Token">
          <el-text>{{ currentAuth.refreshToken }}</el-text>
        </el-descriptions-item>
        <el-descriptions-item label="Access Token 过期时间">
          {{ formatDateTime(currentAuth.accessTokenExpiresAt) }}
        </el-descriptions-item>
        <el-descriptions-item label="Refresh Token 过期时间">
          {{ formatDateTime(currentAuth.refreshTokenExpiresAt) }}
        </el-descriptions-item>
        <el-descriptions-item label="授权范围">
          {{ currentAuth.scope || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="currentAuth.status === 1 ? 'success' : 'danger'">
            {{ currentAuth.status === 1 ? '有效' : '失效' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ formatDateTime(currentAuth.createTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间">
          {{ formatDateTime(currentAuth.updateTime) }}
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
defineOptions({
  name: 'Auth'
})

import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Promotion } from '@element-plus/icons-vue'
import {
  listAuths,
  getAuthorizationUrl,
  refreshToken,
  listExpiringAuths
} from '@/api/auth'

// 数据
const loading = ref(false)
const authList = ref([])
const expiringList = ref([])

// 对话框
const detailDialogVisible = ref(false)
const authUrlLoading = ref(false)


const authUrl = ref('')
const currentAuth = ref(null)

// 计算属性
const validCount = computed(() => {
  return authList.value.filter(item => item.status === 1).length
})

const expiringCount = computed(() => {
  return expiringList.value.length
})

// 方法
const loadAuthList = async () => {
  loading.value = true
  try {
    const res = await listAuths()
    authList.value = res.data || []
  } catch (error) {
    console.error('加载授权列表失败：', error)
  } finally {
    loading.value = false
  }
}

const loadExpiringList = async () => {
  try {
    const res = await listExpiringAuths()
    expiringList.value = res.data || []
  } catch (error) {
    console.error('加载即将过期列表失败：', error)
  }
}

const handleGetAuthUrl = async () => {
  try {
    const res = await getAuthorizationUrl()
    authUrl.value = res.data
    window.open(authUrl.value, '_blank')
  } catch (error) {
    console.error('获取授权URL失败：', error)
  } finally {
    authUrlLoading.value = false
  }
}

const handleRefreshToken = async (row) => {
  try {
    await refreshToken({ id: row.id })
    ElMessage.success('刷新成功')
    loadAuthList()
  } catch (error) {
    console.error('刷新Token失败：', error)
  }
}

const handleViewDetail = (row) => {
  currentAuth.value = row
  detailDialogVisible.value = true
}

const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  loadAuthList()
  loadExpiringList()
})
</script>

<style scoped>
/* 使用Tailwind CSS类替代自定义样式 */
</style>
