<template>
  <div class="login-test">
    <a-card title="登录测试" style="margin: 20px;">
      <a-space direction="vertical" style="width: 100%;">
        <div>
          <h3>快速登录测试</h3>
          <a-form :model="loginForm" @finish="handleLogin">
            <a-form-item>
              <a-input v-model:value="loginForm.username" placeholder="用户名" />
            </a-form-item>
            <a-form-item>
              <a-input-password v-model:value="loginForm.password" placeholder="密码" />
            </a-form-item>
            <a-form-item>
              <a-button type="primary" html-type="submit" :loading="loginLoading" block>
                登录
              </a-button>
            </a-form-item>
          </a-form>
        </div>

        <div>
          <h3>Token状态检查</h3>
          <a-descriptions bordered :column="1">
            <a-descriptions-item label="Store中的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="LocalStorage中的Access Token">
              <span v-if="localStorageToken">
                {{ localStorageToken.substring(0, 50) }}...
                <br>
                <small>长度: {{ localStorageToken.length }}</small>
              </span>
              <span v-else style="color: red;">未找到</span>
            </a-descriptions-item>
            <a-descriptions-item label="是否已登录">
              <span :style="{ color: userStore.isLoggedIn ? 'green' : 'red' }">
                {{ userStore.isLoggedIn ? '是' : '否' }}
              </span>
            </a-descriptions-item>
            <a-descriptions-item label="Token是否过期">
              <span :style="{ color: userStore.isTokenExpired ? 'red' : 'green' }">
                {{ userStore.isTokenExpired ? '是' : '否' }}
              </span>
            </a-descriptions-item>
          </a-descriptions>
        </div>

        <div>
          <h3>API测试</h3>
          <a-space>
            <a-button @click="testPermissionsAPI" :loading="permissionsLoading">
              测试权限API
            </a-button>
            <a-button @click="testRolesAPI" :loading="rolesLoading">
              测试角色API
            </a-button>
            <a-button @click="refreshStatus">
              刷新状态
            </a-button>
          </a-space>
        </div>

        <div v-if="testResults.length > 0">
          <h3>测试结果</h3>
          <a-list :data-source="testResults" 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 testResults = ref([])

const loginForm = reactive({
  username: 'admin',
  password: '123456'
})

const localStorageToken = ref('')

const refreshStatus = () => {
  localStorageToken.value = localStorage.getItem('accessToken') || ''
}

const handleLogin = async () => {
  loginLoading.value = true
  try {
    const response = await authAPI.login(loginForm)
    
    if (response.data && (response.data.status === 'success' || response.data.code === 200)) {
      const data = response.data.data
      
      if (data.accessToken && data.refreshToken) {
        userStore.setAuthData({
          accessToken: data.accessToken,
          refreshToken: data.refreshToken,
          user: data.user || data.userInfo,
          expiresIn: data.accessTokenExpiresIn || 900
        })
        
        testResults.value.unshift({
          name: '登录测试',
          success: true,
          status: '成功',
          response: JSON.stringify({
            message: '登录成功',
            tokenLength: data.accessToken.length,
            user: data.user?.username
          }, null, 2)
        })
        
        message.success('登录成功')
        refreshStatus()
      } else {
        throw new Error('响应数据格式不正确：缺少token信息')
      }
    } else {
      throw new Error(response.data?.message || '登录失败')
    }
  } catch (error) {
    testResults.value.unshift({
      name: '登录测试',
      success: false,
      status: '失败',
      response: JSON.stringify(error.response?.data || error.message, null, 2)
    })
    
    message.error('登录失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loginLoading.value = false
  }
}

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

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

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

<style scoped>
.login-test {
  padding: 20px;
}

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