<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryFormRef" :inline="true" v-show="showSearch">
      <el-form-item label="配置名称" prop="configName">
        <el-input
          v-model="queryParams.configName"
          placeholder="请输入配置名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="配置状态" clearable>
          <el-option label="启用" value="0" />
          <el-option label="停用" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['ai:config:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['ai:config:remove']">删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="configList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="配置名称" align="center" prop="configName" min-width="150" />
      <el-table-column label="模型" align="center" prop="modelName" min-width="120">
        <template #default="scope">
          <el-tag type="primary" size="small">{{ scope.row.modelName }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="模型代码" align="center" prop="modelCode" min-width="150">
        <template #default="scope">
          <span style="font-family: monospace; font-size: 12px; color: #606266;">{{ scope.row.modelCode }}</span>
        </template>
      </el-table-column>
      <el-table-column label="温度" align="center" prop="temperature" width="80" />
      <el-table-column label="最大Token" align="center" prop="maxTokens" width="100" />
      <el-table-column label="默认配置" align="center" prop="isDefault">
        <template #default="scope">
          <el-tag v-if="scope.row.isDefault === '1'" type="success">是</el-tag>
          <el-tag v-else type="info">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['ai:config:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['ai:config:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="配置名称" prop="configName">
          <el-input v-model="form.configName" placeholder="请输入配置名称" />
        </el-form-item>
        <el-form-item label="选择厂商" prop="providerId">
          <el-select 
            v-model="form.providerId" 
            placeholder="请选择厂商" 
            style="width: 100%"
            @change="handleProviderChange"
          >
            <el-option
              v-for="provider in providerList"
              :key="provider.providerId"
              :label="provider.providerName"
              :value="provider.providerId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="选择模型" prop="modelId">
          <el-select 
            v-model="form.modelId" 
            placeholder="请先选择厂商" 
            style="width: 100%"
            :disabled="!form.providerId"
          >
            <el-option
              v-for="model in filteredModelList"
              :key="model.modelId"
              :label="model.modelName"
              :value="model.modelId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="API密钥" prop="apiKey">
          <el-input v-model="form.apiKey" type="password" placeholder="请输入API密钥" show-password />
        </el-form-item>
        <el-form-item label="温度参数" prop="temperature">
          <el-slider v-model="form.temperature" :min="0" :max="2" :step="0.1" show-input />
        </el-form-item>
        <el-form-item label="Top P" prop="topP">
          <el-slider v-model="form.topP" :min="0" :max="1" :step="0.1" show-input />
        </el-form-item>
        <el-form-item label="最大Token数" prop="maxTokens">
          <el-input-number v-model="form.maxTokens" :min="100" :max="32000" style="width: 100%" />
        </el-form-item>
        <el-form-item label="系统提示词" prop="systemPrompt">
          <el-input v-model="form.systemPrompt" type="textarea" :rows="4" placeholder="请输入系统提示词" />
        </el-form-item>
        <el-form-item label="流式输出">
          <el-switch v-model="form.enableStream" active-value="1" inactive-value="0" />
        </el-form-item>
        <el-form-item label="历史记录条数" prop="historyLength">
          <el-input-number v-model="form.historyLength" :min="0" :max="50" style="width: 100%" />
        </el-form-item>
        <el-form-item label="是否默认配置">
          <el-switch v-model="form.isDefault" active-value="1" inactive-value="0" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio value="0">启用</el-radio>
            <el-radio value="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="AiConfig">
import { listConfig, getConfig, delConfig, addConfig, updateConfig } from '@/api/system/ai/config'
import { listModel } from '@/api/system/ai/model'
import { listProvider } from '@/api/system/ai/provider'

const { proxy } = getCurrentInstance()

const loading = ref(true)
const ids = ref([])
const multiple = ref(true)
const showSearch = ref(true)
const total = ref(0)
const configList = ref([])
const modelList = ref([])
const providerList = ref([])
const title = ref('')
const open = ref(false)
const queryFormRef = ref(null)
const formRef = ref(null)

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  configName: null,
  status: null
})

const form = ref({})

const rules = {
  configName: [{ required: true, message: '配置名称不能为空', trigger: 'blur' }],
  providerId: [{ required: true, message: '厂商不能为空', trigger: 'change' }],
  modelId: [{ required: true, message: '模型不能为空', trigger: 'change' }],
  apiKey: [{ required: true, message: 'API密钥不能为空', trigger: 'blur' }]
}

const filteredModelList = computed(() => {
  if (!form.value.providerId) return []
  return modelList.value.filter(model => model.providerId === form.value.providerId)
})

function getList() {
  loading.value = true
  listConfig(queryParams.value).then(response => {
    configList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

function loadModels() {
  listModel({ status: '0' }).then(response => {
    modelList.value = response.rows
  })
}

function loadProviders() {
  listProvider({ status: '0' }).then(response => {
    providerList.value = response.rows
  })
}

function handleProviderChange() {
  form.value.modelId = null
}

function cancel() {
  open.value = false
  reset()
}

function reset() {
  form.value = {
    configId: null,
    configName: null,
    providerId: null,
    modelId: null,
    apiKey: null,
    temperature: 0.7,
    topP: 1.0,
    maxTokens: 2000,
    systemPrompt: null,
    enableStream: '1',
    historyLength: 10,
    isDefault: '0',
    status: '0',
    remark: null
  }
  proxy.resetForm('formRef')
}

function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

function resetQuery() {
  proxy.resetForm('queryFormRef')
  handleQuery()
}

function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.configId)
  multiple.value = !selection.length
}

function handleAdd() {
  reset()
  open.value = true
  title.value = '添加AI配置'
}

function handleUpdate(row) {
  reset()
  const configId = row.configId || ids.value
  getConfig(configId).then(response => {
    form.value = response.data
    if (form.value.modelId) {
      const model = modelList.value.find(m => m.modelId === form.value.modelId)
      if (model) {
        form.value.providerId = model.providerId
      }
    }
    open.value = true
    title.value = '修改AI配置'
  })
}

function submitForm() {
  formRef.value.validate(valid => {
    if (valid) {
      if (form.value.configId != null) {
        updateConfig(form.value).then(() => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          getList()
        })
      } else {
        addConfig(form.value).then(() => {
          proxy.$modal.msgSuccess('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

function handleDelete(row) {
  const configIds = row.configId || ids.value
  proxy.$modal.confirm('是否确认删除？').then(() => {
    return delConfig(configIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess('删除成功')
  }).catch(() => {})
}

function handleStatusChange(row) {
  let text = row.status === '0' ? '启用' : '停用'
  proxy.$modal.confirm('确认要"' + text + '""' + row.configName + '"配置吗？').then(() => {
    return updateConfig(row)
  }).then(() => {
    proxy.$modal.msgSuccess(text + '成功')
  }).catch(() => {
    row.status = row.status === '0' ? '1' : '0'
  })
}

getList()
loadModels()
loadProviders()
</script>
