<template>
  <div class="token-test">
    <h2>Token 测试工具</h2>
    <div class="token-info">
      <p>当前token信息：</p>
      <pre>{{ tokenInfo }}</pre>
    </div>
    <div class="buttons">
      <el-button type="primary" @click="testToken">测试Token</el-button>
      <el-button type="info" @click="refreshToken">重新登录刷新Token</el-button>
      <el-button type="warning" @click="checkUserInfo">获取用户信息</el-button>
    </div>
    <div v-if="apiTestResult" class="api-result">
      <h3>API测试结果</h3>
      <pre>{{ apiTestResult }}</pre>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { getApiBaseUrl } from '../config';

const tokenInfo = ref('未加载');
const apiTestResult = ref('');

onMounted(() => {
  loadTokenInfo();
});

const loadTokenInfo = () => {
  const token = localStorage.getItem('token');
  const username = localStorage.getItem('username');
  const isLoggedIn = localStorage.getItem('isLoggedIn');
  
  if (token) {
    const tokenParts = token.split('.');
    let payload = {};
    try {
      if (tokenParts.length >= 2) {
        payload = JSON.parse(atob(tokenParts[1]));
      }
    } catch (e) {
      console.error('解析token失败', e);
    }
    
    tokenInfo.value = {
      token: token.substring(0, 15) + '...',
      username,
      isLoggedIn,
      expires: payload.exp ? new Date(payload.exp * 1000).toLocaleString() : '未知',
      payload
    };
  } else {
    tokenInfo.value = '未找到token';
  }
};

const testToken = async () => {
  const token = localStorage.getItem('token');
  if (!token) {
    ElMessage.warning('未找到token，请先登录');
    return;
  }
  
  try {
    // 创建一个测试API请求
    const response = await axios.get(`${getApiBaseUrl()}/health`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    
    apiTestResult.value = {
      status: response.status,
      data: response.data
    };
    
    ElMessage.success('Token有效，API测试成功');
  } catch (error) {
    console.error('API测试失败', error);
    apiTestResult.value = {
      error: true,
      status: error.response?.status,
      message: error.response?.data?.detail || error.message
    };
    
    ElMessage.error(`API测试失败: ${error.response?.data?.detail || error.message}`);
  }
};

const checkUserInfo = async () => {
  const token = localStorage.getItem('token');
  if (!token) {
    ElMessage.warning('未找到token，请先登录');
    return;
  }
  
  try {
    // 测试用户信息API
    const response = await axios.get(`${getApiBaseUrl()}/users/me`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    
    apiTestResult.value = {
      status: response.status,
      data: response.data
    };
    
    ElMessage.success('获取用户信息成功');
  } catch (error) {
    console.error('获取用户信息失败', error);
    apiTestResult.value = {
      error: true,
      status: error.response?.status,
      message: error.response?.data?.detail || error.message
    };
    
    ElMessage.error(`获取用户信息失败: ${error.response?.data?.detail || error.message}`);
  }
};

const refreshToken = async () => {
  try {
    // 使用默认账户重新获取token
    const response = await axios.post(`${getApiBaseUrl()}/token`, 
      new URLSearchParams({
        username: 'admin',
        password: '123456'
      }), 
      {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      }
    );
    
    // 保存新的token
    localStorage.setItem('token', response.data.access_token);
    localStorage.setItem('username', 'admin');
    localStorage.setItem('isLoggedIn', 'true');
    
    loadTokenInfo();
    ElMessage.success('Token已刷新');
  } catch (error) {
    console.error('刷新Token失败', error);
    ElMessage.error(`刷新Token失败: ${error.response?.data?.detail || error.message}`);
  }
};
</script>

<style scoped>
.token-test {
  padding: 20px;
  background-color: #0c1633;
  color: white;
  border-radius: 5px;
  max-width: 800px;
  margin: 0 auto;
}

.token-info {
  background-color: #1f3266;
  padding: 15px;
  border-radius: 5px;
  margin-bottom: 20px;
  border: 1px solid rgba(73,134,255,0.3);
}

pre {
  white-space: pre-wrap;
  word-break: break-word;
  background-color: #121c38;
  padding: 10px;
  border-radius: 5px;
  overflow: auto;
  max-height: 300px;
}

.buttons {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.api-result {
  background-color: #1f3266;
  padding: 15px;
  border-radius: 5px;
  margin-top: 20px;
  border: 1px solid rgba(73,134,255,0.3);
}
</style> 