<template>
  <div class="api-management admin-theme">
    <AdminSidebar active="apiManagement" />

    <!-- 主内容区域 -->
    <main class="main-content">
      <AdminHeader :title="$t('nav.apiManagement')" />

      <!-- API密钥输入内容 -->
      <section class="api-content">
        <div class="content-header">
          <h2>{{ $t('apiManagement.title') }}</h2>
        </div>

        <!-- 当前配置展示 -->
        <div class="current-config">
          <h3>{{ $t('apiManagement.currentConfig') }}</h3>
          <div class="config-item">
            <span class="config-label">{{ $t('apiManagement.apiKey') }}：</span>
            <span class="config-value">{{ currentMaskedKey || $t('common.notConfigured') }}</span>
          </div>
          <div class="config-item">
            <span class="config-label">{{ $t('apiManagement.apiEndpoint') }}：</span>
            <span class="config-value">{{ currentApiBaseUrl || $t('common.notConfigured') }}</span>
          </div>
          <div class="config-item">
            <span class="config-label">{{ $t('apiManagement.tokenExpiration') }}：</span>
            <span class="config-value">{{ apiForm.tokenExpireHours ? apiForm.tokenExpireHours + ' ' + $t('apiManagement.hours') : $t('common.notConfigured') }}</span>
          </div>
        </div>

        <div class="api-form-container">
          <h3 style="margin-bottom: 16px; color: var(--text-primary);">{{ $t('apiManagement.modifyConfig') }}</h3>
          <a-form :model="apiForm" label-width="120px" class="api-form">
            <a-form-item :label="$t('apiManagement.apiKey')">
              <a-input
                v-model="apiForm.apiKey"
                type="password"
                :placeholder="$t('apiManagement.apiKeyPlaceholder')"
                show-password
                style="width: 100%; max-width: 600px;"
              />
            </a-form-item>
            <a-form-item :label="$t('apiManagement.apiBaseUrl')">
              <a-input
                v-model="apiForm.apiBaseUrl"
                :placeholder="$t('apiManagement.apiBaseUrlPlaceholder')"
                style="width: 100%; max-width: 600px;"
              />
              <div style="margin-top: 8px; color: var(--text-tertiary); font-size: 12px;">
                {{ $t('apiManagement.apiBaseUrlHint') }}: {{ currentApiBaseUrl || $t('common.notConfigured') }}
              </div>
            </a-form-item>
            <a-form-item :label="$t('apiManagement.tokenExpiration')">
              <div style="display: flex; align-items: center; gap: 12px; width: 100%; max-width: 600px;">
                <a-input
                  v-model.number="apiForm.tokenExpireHours"
                  type="number"
                  :placeholder="$t('apiManagement.tokenPlaceholder')"
                  style="flex: 1;"
                  :min="1"
                  :max="720"
                />
                <span style="color: var(--text-tertiary); font-size: 14px;">{{ $t('apiManagement.hours') }}</span>
              </div>
              <div style="margin-top: 8px; color: var(--text-tertiary); font-size: 12px;">
                {{ $t('apiManagement.rangeHint') }}
              </div>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="saveApiKey" :loading="saving">{{ $t('common.save') }}</a-button>
              <a-button @click="resetForm">{{ $t('common.reset') }}</a-button>
            </a-form-item>
          </a-form>
        </div>
      </section>
    </main>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { useI18n } from 'vue-i18n'
import api from '@/api/request'
import AdminSidebar from '@/components/AdminSidebar.vue'
import AdminHeader from '@/components/AdminHeader.vue'

const { t } = useI18n()

const saving = ref(false)
const loading = ref(false)

const apiForm = reactive({
  apiKey: '',
  apiBaseUrl: '',
  tokenExpireHours: null  // 从数据库加载
})
const currentApiBaseUrl = ref('')
const currentMaskedKey = ref('')

// 格式化JWT过期时间显示
const formatJwtExpiration = (hours) => {
  if (!hours) return ''
  if (hours < 24) {
    return `${hours}${t('apiManagement.hours')}`
  } else if (hours < 720) {
    const days = Math.floor(hours / 24)
    const remainingHours = hours % 24
    if (remainingHours === 0) {
      return `${days}${t('apiManagement.days')}`
    }
    return `${days}${t('apiManagement.days')}${remainingHours}${t('apiManagement.hours')}`
  } else {
    return `30${t('apiManagement.days')}`
  }
}

// 加载当前API配置
const loadApiKey = async () => {
  loading.value = true
  try {
    const response = await api.get('/api-key')
    if (response.data?.maskedKey) {
      currentMaskedKey.value = response.data.maskedKey
      console.log('当前API密钥已配置')
    }
    // 加载当前API基础URL
    if (response.data?.apiBaseUrl) {
      currentApiBaseUrl.value = response.data.apiBaseUrl
    }
    // 加载当前Token过期时间
    if (response.data?.tokenExpireHours) {
      apiForm.tokenExpireHours = response.data.tokenExpireHours
    }
  } catch (error) {
    console.error('加载配置失败:', error)
  } finally {
    loading.value = false
  }
}

// 保存API配置到数据库
const saveApiKey = async () => {
  // 检查是否有任何输入
  const hasApiKey = apiForm.apiKey && apiForm.apiKey.trim() !== ''
  const hasApiBaseUrl = apiForm.apiBaseUrl && apiForm.apiBaseUrl.trim() !== ''
  const hasTokenExpire = apiForm.tokenExpireHours && apiForm.tokenExpireHours >= 1 && apiForm.tokenExpireHours <= 720
  
  // 验证输入：至少需要提供一个配置项
  if (!hasApiKey && !hasApiBaseUrl && !hasTokenExpire) {
    message.warning(t('apiManagement.atLeastOneRequired'))
    return
  }
  
  saving.value = true
  try {
    const requestData = {}
    
    // 如果提供了API密钥，添加到请求中
    if (hasApiKey) {
      requestData.apiKey = apiForm.apiKey.trim()
    }
    
    // 如果提供了API基础URL，添加到请求中
    if (hasApiBaseUrl) {
      requestData.apiBaseUrl = apiForm.apiBaseUrl.trim()
    }
    
    // 如果提供了Token过期时间，添加到请求中
    if (hasTokenExpire) {
      requestData.tokenExpireHours = apiForm.tokenExpireHours
    }
    
    const response = await api.put('/api-key', requestData)
    
    if (response.data?.success) {
      message.success(response.data.message || t('common.configSavedToDb'))
      // 清空输入框
      apiForm.apiKey = ''
      apiForm.apiBaseUrl = ''
      // 重新加载当前配置
      loadApiKey()
    } else {
      message.error(response.data?.error || t('common.saveFailed'))
    }
  } catch (error) {
    console.error('保存配置失败:', error)
    message.error(t('common.saveFailed') + ': ' + (error.response?.data?.message || error.message || ''))
  } finally {
    saving.value = false
  }
}

// 重置表单
const resetForm = () => {
  apiForm.apiKey = ''
  apiForm.apiBaseUrl = ''
  loadApiKey()
}

// 页面加载时获取当前API密钥状态
onMounted(() => {
  loadApiKey()
})
</script>

<style scoped>
.api-management {
  display: flex;
  min-height: 100vh;
  background: var(--bg-base);
  font-family: var(--font-sans);
}

/* 主内容区域 */
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: var(--bg-base);
}

/* API内容区域 */
.api-content {
  padding: var(--space-6);
  flex: 1;
  background: var(--bg-surface);
  margin: var(--space-6);
  border-radius: var(--radius-md);
  box-shadow: var(--shadow-sm);
}

.content-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: var(--space-8);
}

.content-header h2 {
  font-size: var(--text-2xl);
  font-weight: var(--font-semibold);
  color: var(--text-primary);
  margin: 0;
}

.api-form-container {
  max-width: 800px;
}

.current-config {
  background: var(--primary-glow-subtle);
  border: 1px solid var(--border-default);
  border-radius: var(--radius-lg);
  padding: var(--space-6);
  margin-bottom: var(--space-8);
}

.current-config h3 {
  margin: 0 0 var(--space-4) 0;
  font-size: var(--text-base);
  font-weight: var(--font-semibold);
  color: var(--primary-500);
}

.config-item {
  display: flex;
  align-items: center;
  padding: var(--space-3) 0;
  border-bottom: 1px solid var(--border-subtle);
}

.config-item:last-child {
  border-bottom: none;
}

.config-label {
  font-size: var(--text-sm);
  color: var(--text-tertiary);
  width: 120px;
  flex-shrink: 0;
}

.config-value {
  font-size: var(--text-sm);
  color: var(--text-primary);
  font-weight: var(--font-medium);
  font-family: var(--font-mono);
  background: var(--bg-glass);
  padding: var(--space-1) var(--space-3);
  border-radius: var(--radius-sm);
}

.api-form {
  background: var(--bg-elevated);
  padding: var(--space-8);
  border-radius: var(--radius-md);
}

/* ========================================
   Ant Design 暗底白字覆盖
   ======================================== */

/* 表单标签 */
:deep(.ant-form-item-label > label) {
  color: var(--text-secondary, #94A3B8) !important;
}

/* 输入框 */
:deep(.ant-input),
:deep(.ant-input-number),
:deep(.ant-input-password .ant-input) {
  background: var(--bg-base, #0F1219) !important;
  border-color: var(--border-default, rgba(255, 255, 255, 0.12)) !important;
  color: var(--text-primary, #E2E8F0) !important;
}

:deep(.ant-input:focus),
:deep(.ant-input-focused),
:deep(.ant-input-affix-wrapper-focused) {
  border-color: var(--primary-400, #60A5FA) !important;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.15) !important;
}

:deep(.ant-input::placeholder),
:deep(.ant-input-number-input::placeholder) {
  color: var(--text-tertiary, #64748B) !important;
}

/* 密码输入框 */
:deep(.ant-input-password) {
  background: var(--bg-base, #0F1219) !important;
  border-color: var(--border-default, rgba(255, 255, 255, 0.12)) !important;
}

:deep(.ant-input-password .ant-input) {
  background: transparent !important;
}

:deep(.ant-input-suffix) {
  color: var(--text-tertiary, #64748B) !important;
}

/* 按钮 */
:deep(.ant-btn-default) {
  background: var(--bg-elevated, #1A1D2E) !important;
  border-color: var(--border-default, rgba(255, 255, 255, 0.12)) !important;
  color: var(--text-primary, #E2E8F0) !important;
}

:deep(.ant-btn-default:hover) {
  border-color: var(--primary-400, #60A5FA) !important;
  color: var(--primary-400, #60A5FA) !important;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .api-management {
    flex-direction: column;
  }
  
  .api-content {
    padding: 16px;
  }
}
</style>
