<template>
  <div>
    <div class="gva-search-box">
      <el-form :inline="true" :model="searchInfo" class="demo-form-inline">
        <el-form-item label="密钥名称">
          <el-input v-model="searchInfo.name" placeholder="搜索密钥名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
          <el-button @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button type="primary" @click="openDialog">新增</el-button>
      </div>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column type="selection" width="55" />
        <el-table-column label="ID" prop="ID" width="80" />
        <el-table-column label="名称" prop="name" width="200" />
        <el-table-column label="API Key" prop="key" min-width="300" show-overflow-tooltip>
          <template #default="scope">
            <span class="key-text">{{ maskKey(scope.row.key) }}</span>
            <el-button type="primary" link size="small" @click="copyKey(scope.row.key)">
              复制
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="允许的模型" width="150">
          <template #default="scope">
            <el-tag v-if="scope.row.allowed_models?.length > 0" type="info">
              {{ scope.row.allowed_models.length }} 个
            </el-tag>
            <el-tag v-else type="success">全部</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="速率限制" width="120">
          <template #default="scope">
            {{ scope.row.rate_limit || '无限制' }}
          </template>
        </el-table-column>
        <el-table-column label="过期时间" width="180">
          <template #default="scope">
            {{ scope.row.expires_at ? formatDate(scope.row.expires_at * 1000) : '永不过期' }}
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="enabled" width="80">
          <template #default="scope">
            <el-switch v-model="scope.row.enabled" @change="handleStatusChange(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="CreatedAt" width="180">
          <template #default="scope">{{ formatDate(scope.row.CreatedAt) }}</template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="scope">
            <el-button type="primary" link @click="updateApiKey(scope.row)">编辑</el-button>
            <el-button type="danger" link @click="deleteApiKey(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
          :current-page="page"
          :page-size="pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>

    <el-dialog
      v-model="dialogFormVisible"
      :title="type === 'create' ? '新增API密钥' : '编辑API密钥'"
      width="700px"
    >
      <el-form ref="apiKeyForm" :model="formData" :rules="rules" label-width="120px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入密钥名称" clearable />
        </el-form-item>
        <el-form-item v-if="type === 'create'" label="API Key" prop="key">
          <el-input v-model="formData.key" placeholder="留空自动生成" clearable />
        </el-form-item>
        <el-form-item label="允许的模型">
          <el-select
            v-model="formData.allowed_models"
            multiple
            filterable
            allow-create
            placeholder="留空表示允许所有模型"
            style="width: 100%"
          >
            <el-option
              v-for="model in availableModels"
              :key="model"
              :label="model"
              :value="model"
            />
          </el-select>
          <div style="margin-top: 5px; color: #909399; font-size: 12px">
            模型列表来自提供商配置，也可手动输入其他模型名称
          </div>
        </el-form-item>
        <el-form-item label="允许的预设">
          <el-select
            v-model="formData.allowed_presets"
            multiple
            filterable
            allow-create
            placeholder="留空表示允许所有预设"
            style="width: 100%"
          >
            <el-option
              v-for="preset in presetList"
              :key="preset.name"
              :label="preset.name"
              :value="preset.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="速率限制">
          <el-input-number
            v-model="formData.rate_limit"
            :min="0"
            placeholder="每分钟请求数，0表示不限制"
          />
          <span style="margin-left: 10px; color: #909399">次/分钟</span>
        </el-form-item>
        <el-form-item label="过期时间">
          <el-date-picker
            v-model="expiresDate"
            type="datetime"
            placeholder="选择过期时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="启用" prop="enabled">
          <el-switch v-model="formData.enabled" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="enterDialog">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getAiApiKeyList,
  createAiApiKey,
  updateAiApiKey,
  deleteAiApiKey
} from '@/api/aiApiKey'
import { getAiPresetList } from '@/api/aiPreset'
import { getAiProviderList } from '@/api/aiProvider'

const page = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableData = ref([])
const searchInfo = reactive({ name: '' })
const presetList = ref([])
const providerList = ref([])
const availableModels = computed(() => {
  const models = new Set()
  providerList.value.forEach(provider => {
    if (provider.model) {
      models.add(provider.model)
    }
  })
  return Array.from(models)
})

const dialogFormVisible = ref(false)
const type = ref('')
const apiKeyForm = ref(null)
const expiresDate = ref(null)

const formData = ref({
  name: '',
  key: '',
  allowed_models: [],
  allowed_presets: [],
  rate_limit: 0,
  expires_at: null,
  enabled: true
})

const rules = reactive({
  name: [{ required: true, message: '请输入密钥名称', trigger: 'blur' }]
})

const maskKey = (key) => {
  if (!key) return ''
  if (key.length <= 12) return key
  return key.substring(0, 8) + '...' + key.substring(key.length - 4)
}

const copyKey = (key) => {
  navigator.clipboard.writeText(key)
  ElMessage.success('已复制到剪贴板')
}

const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString('zh-CN')
}

const getTableData = async () => {
  const table = await getAiApiKeyList({
    page: page.value,
    pageSize: pageSize.value,
    ...searchInfo
  })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}

const loadPresets = async () => {
  const res = await getAiPresetList({ page: 1, pageSize: 100 })
  if (res.code === 0) {
    presetList.value = res.data.list
  }
}

const loadProviders = async () => {
  const res = await getAiProviderList({ page: 1, pageSize: 100 })
  if (res.code === 0) {
    providerList.value = res.data.list
  }
}

const onSubmit = () => {
  page.value = 1
  getTableData()
}

const onReset = () => {
  searchInfo.name = ''
  getTableData()
}

const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

const handleStatusChange = async (row) => {
  const res = await updateAiApiKey(row)
  if (res.code === 0) {
    ElMessage.success('状态更新成功')
  } else {
    row.enabled = !row.enabled
    ElMessage.error('状态更新失败')
  }
}

const openDialog = () => {
  type.value = 'create'
  dialogFormVisible.value = true
}

const closeDialog = () => {
  dialogFormVisible.value = false
  expiresDate.value = null
  formData.value = {
    name: '',
    key: '',
    allowed_models: [],
    allowed_presets: [],
    rate_limit: 0,
    expires_at: null,
    enabled: true
  }
}

const enterDialog = async () => {
  apiKeyForm.value.validate(async (valid) => {
    if (valid) {
      // 处理过期时间
      if (expiresDate.value) {
        formData.value.expires_at = Math.floor(new Date(expiresDate.value).getTime() / 1000)
      } else {
        formData.value.expires_at = null
      }

      let res
      if (type.value === 'create') {
        res = await createAiApiKey(formData.value)
        if (res.code === 0) {
          ElMessage.success('创建成功')
          if (res.data?.key) {
            ElMessageBox.alert(
              `API Key: ${res.data.key}`,
              '请保存您的API密钥',
              {
                confirmButtonText: '复制',
                callback: () => {
                  copyKey(res.data.key)
                }
              }
            )
          }
        }
      } else {
        res = await updateAiApiKey(formData.value)
        if (res.code === 0) {
          ElMessage.success('更新成功')
        }
      }
      if (res.code === 0) {
        closeDialog()
        getTableData()
      }
    }
  })
}

const updateApiKey = (row) => {
  type.value = 'update'
  formData.value = { ...row }
  if (row.expires_at) {
    expiresDate.value = new Date(row.expires_at * 1000)
  }
  dialogFormVisible.value = true
}

const deleteApiKey = (row) => {
  ElMessageBox.confirm('确定要删除该API密钥吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const res = await deleteAiApiKey({ ID: row.ID })
    if (res.code === 0) {
      ElMessage.success('删除成功')
      getTableData()
    }
  })
}

getTableData()
loadPresets()
loadProviders()
</script>

<style scoped>
.gva-search-box {
  padding: 20px;
  background: #fff;
  margin-bottom: 10px;
}

.gva-table-box {
  padding: 20px;
  background: #fff;
}

.gva-btn-list {
  margin-bottom: 10px;
}

.gva-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.key-text {
  font-family: monospace;
  color: #606266;
}
</style>
