<template>
  <div class="app-container">
    <el-card shadow="never">
      <div slot="header"><span>文本模型配置</span></div>
      <el-table :data="models" border size="small" style="width: 100%">
        <el-table-column label="模型名称" width="120">
          <template slot-scope="scope">
            <el-tag>{{ scope.row.name }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="API Key" min-width="200">
          <template slot-scope="scope">
            <el-input v-model="scope.row.apiKey" placeholder="请输入API Key" show-password size="small" />
          </template>
        </el-table-column>
        <el-table-column label="API URL" min-width="250">
          <template slot-scope="scope">
            <el-input v-model="scope.row.apiUrl" placeholder="请输入API地址" size="small" />
          </template>
        </el-table-column>
        <el-table-column label="模型标识" min-width="200">
          <template slot-scope="scope">
            <el-input v-model="scope.row.modelId" :placeholder="scope.row.placeholder" size="small" />
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 20px; text-align: right;">
        <el-button type="primary" :loading="saving" @click="handleSave">保存配置</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'AdminTextModel',
  data() {
    return {
      saving: false,
      models: [
        { name: '豆包', apiKey: '', apiUrl: '', modelId: '', placeholder: '如 doubao-pro-32k' },
        { name: 'DeepSeek', apiKey: '', apiUrl: '', modelId: '', placeholder: '如 deepseek-chat' },
        { name: '智谱', apiKey: '', apiUrl: '', modelId: '', placeholder: '如 glm-4' }
      ]
    }
  },
  created() {
    this.loadConfig()
  },
  methods: {
    loadConfig() {
      request({ url: '/system/config/getConfigByKey/text.model.config', method: 'get' }).then(r => {
        if (r.data && r.data.configValue) {
          try {
            const saved = JSON.parse(r.data.configValue)
            if (Array.isArray(saved) && saved.length > 0) {
              this.models = this.models.map((m, i) => {
                if (saved[i]) {
                  return { ...m, ...saved[i] }
                }
                return m
              })
            }
          } catch (e) {
            console.warn('解析文本模型配置失败:', e)
          }
        }
      }).catch(() => {})
    },
    handleSave() {
      this.saving = true
      const data = {
        configKey: 'text.model.config',
        configName: '文本模型配置',
        configValue: JSON.stringify(this.models)
      }
      request({ url: '/system/config/updateConfigByKey', method: 'post', data }).then(() => {
        this.$message.success('配置保存成功')
      }).finally(() => {
        this.saving = false
      })
    }
  }
}
</script>
