<template>
  <div class="app-container">
    <el-card>
      <div slot="header" class="card-header">
        <span>大模型管理</span>
        <el-button type="primary" size="small" @click="handleAdd">
          <i class="el-icon-plus"></i>新增模型
        </el-button>
      </div>

      <el-alert
        title="大模型管理说明"
        description="统一管理大模型配置，固定支持豆包(Doubao)、通义千问(Qwen)、DeepSeek、智谱(Zhipu) 四种国产模型。所有模型均使用OpenAI兼容协议，配置后全局生效。"
        type="info"
        show-icon
        :closable="false"
        style="margin-bottom: 20px"
      />

      <el-table :data="tableData" v-loading="loading" border size="small" style="width:100%">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="providerName" label="供应商名称" min-width="120" />
        <el-table-column prop="providerCode" label="供应商编码" width="100" />
        <el-table-column prop="modelName" label="模型名称" width="150" />
        <el-table-column prop="apiEndpoint" label="API地址" min-width="200" show-overflow-tooltip />
        <el-table-column prop="maxTokens" label="最大Token" width="100" align="center" />
        <el-table-column prop="temperature" label="温度" width="80" align="center" />
        <el-table-column prop="isDefault" label="默认" width="80" align="center">
          <template slot-scope="{ row }">
            <el-tag :type="row.isDefault === 1 ? 'success' : 'info'" size="small">
              {{ row.isDefault === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="enabled" label="状态" width="80" align="center">
          <template slot-scope="{ row }">
            <el-tag :type="row.enabled === 1 ? 'success' : 'danger'" size="small">
              {{ row.enabled === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template slot-scope="{ row }">
            <el-button type="primary" size="mini" @click="handleEdit(row)">编辑</el-button>
            <el-button type="success" size="mini" @click="handleTest(row)">测试</el-button>
            <el-button v-if="row.isDefault !== 1" type="warning" size="mini" @click="handleSetDefault(row)">设为默认</el-button>
            <el-button type="danger" size="mini" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <el-form-item label="供应商名称" prop="providerName">
          <el-input v-model="form.providerName" placeholder="如：豆包、GPT-4o" />
        </el-form-item>
        <el-form-item label="供应商编码" prop="providerCode">
          <el-select v-model="form.providerCode" placeholder="请选择" style="width: 100%" @change="handleProviderChange">
            <el-option label="豆包(Doubao)" value="doubao" />
            <el-option label="通义千问(Qwen)" value="qwen" />
            <el-option label="DeepSeek" value="deepseek" />
            <el-option label="智谱(Zhipu)" value="zhipu" />
          </el-select>
        </el-form-item>
        <el-form-item label="模型名称" prop="modelName">
          <el-input v-model="form.modelName" placeholder="如：doubao-pro-4k" />
        </el-form-item>
        <el-form-item label="API地址" prop="apiEndpoint">
          <el-input v-model="form.apiEndpoint" placeholder="API Endpoint" />
        </el-form-item>
        <el-form-item label="API Key" prop="apiKey">
          <el-input v-model="form.apiKey" placeholder="API Key" show-password />
        </el-form-item>
        <el-form-item label="启用">
          <el-switch v-model="form.enabled" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAiProvider, getAiProvider, addAiProvider, updateAiProvider, deleteAiProvider, setDefaultAiProvider, testAiProvider } from '@/api/admin/aiProvider'

export default {
  name: 'AiProvider',
  data() {
    return {
      loading: false,
      tableData: [],
      dialogVisible: false,
      dialogTitle: '',
      form: {
        id: null, providerName: '', providerCode: '', modelName: '',
        apiEndpoint: '', apiKey: '', isDefault: 0, enabled: 1
      },
      rules: {
        providerName: [{ required: true, message: '请输入供应商名称', trigger: 'blur' }],
        providerCode: [{ required: true, message: '请选择供应商编码', trigger: 'change' }],
        modelName: [{ required: true, message: '请输入模型名称', trigger: 'blur' }],
        apiEndpoint: [{ required: true, message: '请输入API地址', trigger: 'blur' }],
        apiKey: [{ required: true, message: '请输入API Key', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    async getList() {
      this.loading = true
      try {
        const res = await listAiProvider()
        this.tableData = res.data || []
      } catch (error) {
        this.$message.error('获取列表失败')
      } finally {
        this.loading = false
      }
    },
    handleAdd() {
      this.dialogTitle = '新增模型'
      this.form = { id: null, providerName: '', providerCode: '', modelName: '', apiEndpoint: '', apiKey: '', isDefault: 0, enabled: 1 }
      this.dialogVisible = true
      this.$nextTick(() => { this.$refs.formRef && this.$refs.formRef.resetFields() })
    },
    handleEdit(row) {
      this.dialogTitle = '编辑模型'
      this.form = { ...row }
      this.dialogVisible = true
    },
    handleProviderChange(code) {
      const defaults = {
        doubao: { apiEndpoint: 'https://ark.cn-beijing.volces.com/api/v3/chat/completions', modelName: 'doubao-pro-4k' },
        qwen:   { apiEndpoint: 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions', modelName: 'qwen-plus' },
        deepseek:{ apiEndpoint: 'https://api.deepseek.com/v1/chat/completions', modelName: 'deepseek-chat' },
        zhipu:  { apiEndpoint: 'https://open.bigmodel.cn/api/paas/v4/chat/completions', modelName: 'glm-4-flash' }
      }
      if (defaults[code]) {
        this.form.apiEndpoint = defaults[code].apiEndpoint
        this.form.modelName = defaults[code].modelName
      }
    },
    async handleSubmit() {
      try {
        await this.$refs.formRef.validate()
        if (this.form.id) {
          await updateAiProvider(this.form.id, this.form)
          this.$message.success('修改成功')
        } else {
          await addAiProvider(this.form)
          this.$message.success('新增成功')
        }
        this.dialogVisible = false
        this.getList()
      } catch (error) {
        if (error !== false) this.$message.error('操作失败')
      }
    },
    async handleTest(row) {
      try {
        const res = await testAiProvider(row)
        if (res.code === 200) {
          this.$message.success('连接测试成功：' + (res.data || ''))
        } else {
          this.$message.error('连接测试失败：' + (res.msg || ''))
        }
      } catch (error) {
        this.$message.error('连接测试失败')
      }
    },
    async handleSetDefault(row) {
      try {
        await setDefaultAiProvider(row.id)
        this.$message.success('设置成功')
        this.getList()
      } catch (error) {
        this.$message.error('设置失败')
      }
    },
    async handleDelete(row) {
      try {
        await this.$confirm('确定要删除该供应商配置吗？', '提示', { type: 'warning' })
        await deleteAiProvider(row.id)
        this.$message.success('删除成功')
        this.getList()
      } catch (error) {
        if (error !== 'cancel') this.$message.error('删除失败')
      }
    }
  }
}
</script>

<style scoped>
.card-header { display: flex; justify-content: space-between; align-items: center; }
.mb16 { margin-bottom: 16px; }
.filter-card { padding-bottom: 0; }
</style>
