<template>
  <div class="key-management-page">
    <div class="key-management-container">
      <!-- 标题 -->
      <div class="section-title">
        <div class="title-bar"></div>
        <h2 class="title-text">密钥管理</h2>
      </div>
      
    <!-- API密钥管理区域 -->
    <div class="api-key-section">
      <div class="section-title">插件API密钥 (api_token)</div>
      <div class="input-container">
        <!-- 有API密钥时显示输入框 -->
        <div v-if="apiKeyValue" class="input-wrapper">
          <el-input
            v-model="apiKeyValue"
            placeholder="请输入API密钥"
            readonly
            class="api-input"
          >
            <template #append>
              <div class="action-buttons">
                <el-tooltip content="复制API密钥" placement="top">
                  <el-button 
                    type="text" 
                    @click="copyApiKey" 
                    class="action-btn"
                    :icon="CopyDocument"
                  />
                </el-tooltip>
                <el-tooltip content="刷新API密钥" placement="top">
                  <el-button 
                    type="text" 
                    @click="refreshApiKey" 
                    class="action-btn"
                    :loading="refreshing"
                    :icon="Refresh"
                  />
                </el-tooltip>
                <el-tooltip content="删除API密钥" placement="top">
                  <el-button 
                    type="text" 
                    @click="deleteApiKey" 
                    class="action-btn"
                    :loading="deleting"
                    :icon="Delete"
                  />
                </el-tooltip>
              </div>
            </template>
          </el-input>
        </div>
        
        <!-- 没有API密钥时显示生成按钮 -->
        <el-button
          v-else
          type="primary"
          class="generate-btn"
          @click="generateApiKey"
          :loading="generating"
        >
          点击生成插件API密钥
        </el-button>
      </div>
    </div>

    <!-- 礼品码兑换区域 -->
    <div class="gift-code-section">
      <div class="section-title">礼品码兑换</div>
      <div class="input-container">
        <div class="input-wrapper">
          <el-input
            v-model="giftCode"
            placeholder="请输入兑换码"
            class="gift-input"
          >
            <template #append>
              <el-tooltip content="兑换礼品码" placement="top">
                <el-button 
                  type="primary" 
                  @click="redeemGiftCode"
                  :loading="redeeming"
                  class="redeem-btn"
                >
                  兑换
                </el-button>
              </el-tooltip>
            </template>
          </el-input>
        </div>
      </div>
      <div class="hint-text">输入有效的充值兑换卡或者会员兑换卡</div>
    </div>

    <!-- 取消会员限制提示：非会员也可查看/生成API密钥 -->
    
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { CopyDocument, Refresh, Delete } from '@element-plus/icons-vue'
import { useUserStore } from '../../store/user'
import { 
  generateApiKey as generateApiKeyApi, 
  refreshApiKey as refreshApiKeyApi, 
  deleteApiKey as deleteApiKeyApi, 
  getApiKeyInfo,
  redeemGiftCode as redeemGiftCodeApi,
  getCurrentUser
} from '../../api/user'

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const apiKeyInfo = ref(null)
const apiKeyValue = ref('')
const giftCode = ref('')
const generating = ref(false)
const refreshing = ref(false)
const deleting = ref(false)
const loading = ref(false)
const redeeming = ref(false)

// 计算属性
const isVipUser = computed(() => {
  const userInfo = userStore.getUserInfo
  return userInfo && (userInfo.role === 2 || userInfo.role === 3)
})

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString('zh-CN')
}

// 获取API密钥信息
const fetchApiKeyInfo = async () => {
  try {
    loading.value = true
    const response = await getApiKeyInfo()
    if (response.code === 200) {
      apiKeyInfo.value = response.data
      apiKeyValue.value = response.data.keyValue || ''
    } else if (response.code === 404) {
      // 用户没有API密钥
      apiKeyInfo.value = null
      apiKeyValue.value = ''
    } else {
      ElMessage.error(response.message || '获取密钥信息失败')
    }
  } catch (error) {
    // 如果是认证错误（401/403），拦截器已经处理了，不需要再显示错误提示
    if (error.isAuthError || error.status === 401 || error.status === 403) {
      console.log('认证错误已由拦截器处理，跳过组件错误提示')
      return
    }
    // 其他错误才显示错误提示
    console.error('获取API密钥信息失败:', error)
    ElMessage.error('获取密钥信息失败')
  } finally {
    loading.value = false
  }
}

// 生成API密钥
const generateApiKey = async () => {
  try {
    generating.value = true
    const response = await generateApiKeyApi()
    if (response.code === 200) {
      ElMessage.success('API密钥生成成功')
      await fetchApiKeyInfo()
    } else {
      ElMessage.error(response.message || '生成API密钥失败')
    }
  } catch (error) {
    console.error('生成API密钥失败:', error)
    ElMessage.error('生成API密钥失败')
  } finally {
    generating.value = false
  }
}

// 刷新API密钥
const refreshApiKey = async () => {
  if (!apiKeyValue.value) {
    ElMessage.warning('暂无API密钥')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      '刷新密钥会生成新的密钥值，旧密钥将立即失效。确定要刷新吗？',
      '确认刷新',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    refreshing.value = true
    const response = await refreshApiKeyApi()
    if (response.code === 200) {
      ElMessage.success('API密钥刷新成功')
      await fetchApiKeyInfo()
    } else {
      ElMessage.error(response.message || '刷新API密钥失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('刷新API密钥失败:', error)
      ElMessage.error('刷新API密钥失败')
    }
  } finally {
    refreshing.value = false
  }
}

// 删除API密钥
const deleteApiKey = async () => {
  if (!apiKeyValue.value) {
    ElMessage.warning('暂无API密钥')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      '删除密钥后，您将无法使用API接口。确定要删除吗？',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    deleting.value = true
    const response = await deleteApiKeyApi()
    if (response.code === 200) {
      ElMessage.success('API密钥删除成功')
      apiKeyInfo.value = null
      apiKeyValue.value = ''
    } else {
      ElMessage.error(response.message || '删除API密钥失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除API密钥失败:', error)
      ElMessage.error('删除API密钥失败')
    }
  } finally {
    deleting.value = false
  }
}

// 复制API密钥
const copyApiKey = async () => {
  if (!apiKeyValue.value) {
    ElMessage.warning('暂无API密钥')
    return
  }
  
  try {
    await navigator.clipboard.writeText(apiKeyValue.value)
    ElMessage.success('API密钥已复制到剪贴板')
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败')
  }
}

// 礼品码兑换
const redeemGiftCode = async () => {
  if (!giftCode.value.trim()) {
    ElMessage.warning('请输入兑换码')
    return
  }
  
  try {
    redeeming.value = true
    const response = await redeemGiftCodeApi(giftCode.value.trim())
    
    if (response.code === 200) {
      ElMessage.success('兑换成功')
      giftCode.value = ''
      
      // 兑换成功后更新用户信息
      try {
        const userResponse = await getCurrentUser()
        if (userResponse.code === 200) {
          userStore.updateUserInfo(userResponse.data)
          ElMessage.success('用户信息已更新')
        }
      } catch (updateError) {
        console.error('更新用户信息失败:', updateError)
        // 即使更新用户信息失败，也不影响兑换成功的提示
      }
    } else {
      // 显示接口返回的具体错误信息
      ElMessage.error(response.message || '兑换失败')
    }
  } catch (error) {
    console.error('兑换失败:', error)
    // 如果是网络错误或其他异常，显示通用错误信息
    // 如果是API返回的错误，error.response中可能包含错误信息
    if (error.response && error.response.data && error.response.data.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error('兑换失败，请检查兑换码是否正确')
    }
  } finally {
    redeeming.value = false
  }
}

// 跳转到会员页面
const goToMembership = () => {
  router.push('/membership')
}

// 更新用户信息
const updateUserInfo = async () => {
  try {
    const response = await getCurrentUser()
    if (response.code === 200) {
      userStore.updateUserInfo(response.data)
      console.log('用户信息已更新')
    } else {
      console.error('获取用户信息失败:', response.message)
    }
  } catch (error) {
    console.error('更新用户信息失败:', error)
  }
}

// 组件挂载时更新用户信息并获取密钥信息（非会员也允许）
onMounted(async () => {
  await updateUserInfo()
  fetchApiKeyInfo()
})
</script>

<style scoped>
.key-management-page {
  width: 100%;
  min-height: 800px;
  padding: 0;
  margin: 0;
  overflow: hidden;
  box-sizing: border-box;
}

.key-management-container {
  width: 100%;
  box-sizing: border-box;
}

.section-title {
  width: 100%;
  max-width: 312px;
  display: flex;
  align-items: center;
  gap: 12px;
  margin-top: 0;
  margin-bottom: 20px;
}

.title-bar {
  width: 4px;
  height: 24px;
  background: #333;
  border-radius: 2px;
}

.title-text {
  font-family: Arial, sans-serif;
  font-weight: 600;
  font-size: 24px;
  line-height: 28px;
  letter-spacing: 0px;
  color: #333;
  margin: 0;
  text-align: left;
}

/* API密钥管理区域 */
.api-key-section {
  margin-bottom: 70px;
}

.api-key-section .section-title {
  font-family: Arial, sans-serif;
  font-weight: 500;
  font-size: 16px;
  line-height: 18px;
  letter-spacing: 0px;
  text-align: left;
  color: #333;
  margin-bottom: 20px;
}

.input-container {
  display: flex;
  align-items: center;
  gap: 12px;
}

.input-wrapper {
  width: 100%;
  max-width: 600px;
  height: 50px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  background-color: #fff;
  display: flex;
  align-items: center;
}

.api-input {
  width: 100%;
  height: 50px;
}

.api-input :deep(.el-input__wrapper) {
  height: 50px;
  border: none;
  background-color: transparent;
  box-shadow: none;
}

.api-input :deep(.el-input__inner) {
  height: 50px;
  font-family: Arial, sans-serif;
  font-weight: 500;
  font-size: 16px;
  line-height: 18px;
  letter-spacing: 0px;
  color: #333;
}

.api-input :deep(.el-input__inner::placeholder) {
  color: #999;
  font-family: Arial, sans-serif;
  font-weight: 500;
  font-size: 16px;
  line-height: 18px;
  letter-spacing: 0px;
}

.api-input :deep(.el-input-group__append) {
  padding: 0;
  border: none;
  background: transparent;
  width: 120px;
  height: 50px;
  box-shadow: none;
}

@media (max-width: 480px) {
  .api-input :deep(.el-input-group__append) {
    width: 100px;
  }
}

.action-buttons {
  display: flex;
  gap: 16px;
  width: 120px;
  height: 50px;
  justify-content: center;
  align-items: center;
  border: none;
  background: transparent;
}

@media (max-width: 480px) {
  .action-buttons {
    width: 100px;
    gap: 12px;
  }
}

.action-btn {
  width: 26px;
  height: 26px;
  padding: 0;
  color: #666;
  border: none;
  background: transparent;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 26px;
  min-height: 26px;
  margin: 0;
}

.action-btn:hover {
  color: #409eff;
  background-color: #f5f5f5;
}

.action-btn :deep(.el-icon) {
  width: 16px;
  height: 16px;
  font-size: 16px;
}

.action-btn :deep(svg) {
  width: 16px;
  height: 16px;
}

/* 生成按钮样式 */
.generate-btn {
  width: 100%;
  max-width: 600px;
  height: 50px;
  font-family: Arial, sans-serif;
  font-weight: 500;
  font-size: 16px;
  line-height: 18px;
  letter-spacing: 0px;
  background-color: #333;
  border: 1px solid #333;
  border-radius: 4px;
  color: #fff;
}

.generate-btn:hover {
  background-color: #555;
  border-color: #555;
}

/* 礼品码兑换区域 */
.gift-code-section {
  margin-bottom: 70px;
}

.gift-code-section .section-title {
  font-family: Arial, sans-serif;
  font-weight: 500;
  font-size: 16px;
  line-height: 18px;
  letter-spacing: 0px;
  text-align: left;
  color: #333;
  margin-bottom: 20px;
}

.gift-input {
  width: 100%;
  height: 50px;
}

.gift-input :deep(.el-input__wrapper) {
  height: 50px;
  border: none;
  background-color: transparent;
  box-shadow: none;
}

.gift-input :deep(.el-input__inner) {
  height: 50px;
  font-family: Arial, sans-serif;
  font-weight: 500;
  font-size: 16px;
  line-height: 18px;
  letter-spacing: 0px;
  color: #333;
}

.gift-input :deep(.el-input__inner::placeholder) {
  color: #999;
  font-family: Arial, sans-serif;
  font-weight: 500;
  font-size: 16px;
  line-height: 18px;
  letter-spacing: 0px;
}

.gift-input :deep(.el-input-group__append) {
  padding: 0;
  border: none;
  background: transparent;
  width: 120px;
  height: 50px;
  box-shadow: none;
}

@media (max-width: 480px) {
  .gift-input :deep(.el-input-group__append) {
    width: 80px;
  }
}

.redeem-btn {
  width: 120px;
  height: 50px;
  padding: 0;
  font-family: Arial, sans-serif;
  font-weight: 500;
  font-size: 16px;
  line-height: 18px;
  letter-spacing: 0px;
  background-color: rgba(107, 107, 107, 1) !important;
  border: 1px solid rgba(107, 107, 107, 1) !important;
  border-radius: 0 4px 4px 0;
  color: #fff !important;
  margin: 0;
}

@media (max-width: 480px) {
  .redeem-btn {
    width: 80px;
    font-size: 14px;
  }
}

.redeem-btn:hover {
  background-color: rgba(87, 87, 87, 1) !important;
  border-color: rgba(87, 87, 87, 1) !important;
}

.redeem-btn:deep(.el-button) {
  background-color: rgba(107, 107, 107, 1) !important;
  border-color: rgba(107, 107, 107, 1) !important;
  color: #fff !important;
}

.redeem-btn:deep(.el-button:hover) {
  background-color: rgba(87, 87, 87, 1) !important;
  border-color: rgba(87, 87, 87, 1) !important;
}

.hint-text {
  margin-top: 8px;
  font-family: Arial, sans-serif;
  font-weight: 500;
  font-size: 16px;
  line-height: 18px;
  letter-spacing: 0px;
  color: #999;
  text-align: left;
}

/* 会员状态检查 */
.vip-notice {
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 992px) {
  .section-title {
    max-width: 280px;
  }
  
  .title-text {
    font-size: 22px;
  }
}

@media (max-width: 768px) {
  .input-container {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .input-wrapper {
    width: 100%;
  }
  
  .api-input,
  .gift-input,
  .generate-btn {
    width: 100%;
  }
  
  .action-buttons {
    width: 120px;
  }
  
  .redeem-btn {
    width: 120px;
  }
  
  .section-title {
    max-width: 250px;
  }
  
  .title-text {
    font-size: 20px;
  }
  
  .api-key-section,
  .gift-code-section {
    margin-bottom: 50px;
  }
}

@media (max-width: 480px) {
  .section-title {
    max-width: 220px;
  }
  
  .title-text {
    font-size: 18px;
    line-height: 24px;
  }
  
  .api-key-section .section-title,
  .gift-code-section .section-title {
    font-size: 14px;
  }
  
  .api-input :deep(.el-input__inner),
  .gift-input :deep(.el-input__inner),
  .api-input :deep(.el-input__inner::placeholder),
  .gift-input :deep(.el-input__inner::placeholder) {
    font-size: 14px;
  }
  
  .redeem-btn {
    font-size: 14px;
  }
  
  .hint-text {
    font-size: 14px;
  }
  
  .api-key-section,
  .gift-code-section {
    margin-bottom: 40px;
  }
}
</style>

 