<template>
  <div class="token-debug">
    <a-card title="Token调试信息" style="margin: 20px;">
      <a-space direction="vertical" style="width: 100%;">
        <div>
          <h3>LocalStorage中的Token信息:</h3>
          <a-descriptions bordered :column="1">
            <a-descriptions-item label="Access Token">
              <span v-if="tokenInfo.accessToken">
                {{ tokenInfo.accessToken.substring(0, 50) }}...
                <br>
                <small>长度: {{ tokenInfo.accessToken.length }}</small>
              </span>
              <span v-else style="color: red;">未找到</span>
            </a-descriptions-item>
            <a-descriptions-item label="Refresh Token">
              <span v-if="tokenInfo.refreshToken">
                {{ tokenInfo.refreshToken.substring(0, 50) }}...
                <br>
                <small>长度: {{ tokenInfo.refreshToken.length }}</small>
              </span>
              <span v-else style="color: red;">未找到</span>
            </a-descriptions-item>
            <a-descriptions-item label="User Info">
              <pre v-if="tokenInfo.userInfo">{{ JSON.stringify(tokenInfo.userInfo, null, 2) }}</pre>
              <span v-else style="color: red;">未找到</span>
            </a-descriptions-item>
            <a-descriptions-item label="Token Expires At">
              <span v-if="tokenInfo.tokenExpiresAt">
                {{ new Date(tokenInfo.tokenExpiresAt).toLocaleString() }}
                <br>
                <small :style="{ color: tokenInfo.isExpired ? 'red' : 'green' }">
                  {{ tokenInfo.isExpired ? '已过期' : '未过期' }}
                </small>
              </span>
              <span v-else style="color: red;">未找到</span>
            </a-descriptions-item>
          </a-descriptions>
        </div>

        <div>
          <h3>Store中的Token信息:</h3>
          <a-descriptions bordered :column="1">
            <a-descriptions-item label="Access Token">
              <span v-if="userStore.accessToken">
                {{ userStore.accessToken.substring(0, 50) }}...
                <br>
                <small>长度: {{ userStore.accessToken.length }}</small>
              </span>
              <span v-else style="color: red;">未找到</span>
            </a-descriptions-item>
            <a-descriptions-item label="Refresh Token">
              <span v-if="userStore.refreshToken">
                {{ userStore.refreshToken.substring(0, 50) }}...
                <br>
                <small>长度: {{ userStore.refreshToken.length }}</small>
              </span>
              <span v-else style="color: red;">未找到</span>
            </a-descriptions-item>
            <a-descriptions-item label="User Info">
              <pre v-if="userStore.userInfo">{{ JSON.stringify(userStore.userInfo, null, 2) }}</pre>
              <span v-else style="color: red;">未找到</span>
            </a-descriptions-item>
            <a-descriptions-item label="Is Logged In">
              <span :style="{ color: userStore.isLoggedIn ? 'green' : 'red' }">
                {{ userStore.isLoggedIn ? '是' : '否' }}
              </span>
            </a-descriptions-item>
            <a-descriptions-item label="Is Token Expired">
              <span :style="{ color: userStore.isTokenExpired ? 'red' : 'green' }">
                {{ userStore.isTokenExpired ? '是' : '否' }}
              </span>
            </a-descriptions-item>
          </a-descriptions>
        </div>

        <div>
          <h3>API测试:</h3>
          <a-space>
            <a-button type="primary" @click="testLogin" :loading="loginLoading">
              测试登录
            </a-button>
            <a-button @click="testPermissionsAPI" :loading="permissionsLoading">
              测试权限API
            </a-button>
            <a-button @click="testRolesAPI" :loading="rolesLoading">
              测试角色API
            </a-button>
            <a-button @click="refreshTokenInfo">
              刷新Token信息
            </a-button>
          </a-space>
        </div>

        <div v-if="apiTestResults.length > 0">
          <h3>API测试结果:</h3>
          <a-list :data-source="apiTestResults" bordered>
            <template #renderItem="{ item }">
              <a-list-item>
                <a-list-item-meta>
                  <template #title>
                    <span :style="{ color: item.success ? 'green' : 'red' }">
                      {{ item.name }} - {{ item.success ? '成功' : '失败' }}
                    </span>
                  </template>
                  <template #description>
                    <div>
                      <p><strong>状态码:</strong> {{ item.status }}</p>
                      <p><strong>响应:</strong></p>
                      <pre style="background: #f5f5f5; padding: 8px; border-radius: 4px; font-size: 12px;">{{ item.response }}</pre>
                    </div>
                  </template>
                </a-list-item-meta>
              </a-list-item>
            </template>
          </a-list>
        </div>
      </a-space>
    </a-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { useUserStore } from '@/stores/user'
import { authAPI, rolePermissionAPI } from '@/utils/api'

const userStore = useUserStore()
const loginLoading = ref(false)
const permissionsLoading = ref(false)
const rolesLoading = ref(false)
const apiTestResults = ref([])

const tokenInfo = reactive({
  accessToken: null,
  refreshToken: null,
  userInfo: null,
  tokenExpiresAt: null,
  isExpired: false
})

const refreshTokenInfo = () => {
  tokenInfo.accessToken = localStorage.getItem('accessToken')
  tokenInfo.refreshToken = localStorage.getItem('refreshToken')
  tokenInfo.userInfo = JSON.parse(localStorage.getItem('userInfo') || 'null')
  tokenInfo.tokenExpiresAt = parseInt(localStorage.getItem('tokenExpiresAt') || '0')
  tokenInfo.isExpired = tokenInfo.tokenExpiresAt ? Date.now() >= tokenInfo.tokenExpiresAt : true
}

const testLogin = async () => {
  loginLoading.value = true
  try {
    const response = await authAPI.login({
      username: 'admin',
      password: '123456'
    })
    
    apiTestResults.value.unshift({
      name: '登录测试',
      success: true,
      status: response.status || '200',
      response: JSON.stringify(response.data, null, 2)
    })
    
    message.success('登录测试成功')
    refreshTokenInfo()
  } catch (error) {
    apiTestResults.value.unshift({
      name: '登录测试',
      success: false,
      status: error.response?.status || 'Error',
      response: JSON.stringify(error.response?.data || error.message, null, 2)
    })
    
    message.error('登录测试失败')
  } finally {
    loginLoading.value = false
  }
}

const testPermissionsAPI = async () => {
  permissionsLoading.value = true
  try {
    const response = await rolePermissionAPI.getAllPermissions()
    
    apiTestResults.value.unshift({
      name: '权限API测试',
      success: response.success,
      status: response.success ? '200' : 'Error',
      response: JSON.stringify(response, null, 2)
    })
    
    if (response.success) {
      message.success('权限API测试成功')
    } else {
      message.error('权限API测试失败')
    }
  } catch (error) {
    apiTestResults.value.unshift({
      name: '权限API测试',
      success: false,
      status: 'Error',
      response: JSON.stringify(error.message, null, 2)
    })
    
    message.error('权限API测试失败')
  } finally {
    permissionsLoading.value = false
  }
}

const testRolesAPI = async () => {
  rolesLoading.value = true
  try {
    const response = await rolePermissionAPI.getAllRolesWithPermissions()
    
    apiTestResults.value.unshift({
      name: '角色API测试',
      success: response.success,
      status: response.success ? '200' : 'Error',
      response: JSON.stringify(response, null, 2)
    })
    
    if (response.success) {
      message.success('角色API测试成功')
    } else {
      message.error('角色API测试失败')
    }
  } catch (error) {
    apiTestResults.value.unshift({
      name: '角色API测试',
      success: false,
      status: 'Error',
      response: JSON.stringify(error.message, null, 2)
    })
    
    message.error('角色API测试失败')
  } finally {
    rolesLoading.value = false
  }
}

onMounted(() => {
  refreshTokenInfo()
})
</script>

<style scoped>
.token-debug {
  padding: 20px;
}

pre {
  white-space: pre-wrap;
  word-wrap: break-word;
  max-height: 200px;
  overflow-y: auto;
}
</style>
