<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>AI配置管理</span>
          <el-button type="primary" @click="handleSave" v-hasPermi="['talk:config:edit']">保存配置</el-button>
        </div>
      </template>

      <el-form :model="configForm" ref="configFormRef" :rules="rules" label-width="150px" v-loading="loading">
        <el-divider content-position="left">讯飞TTS配置</el-divider>
        <el-form-item label="AppID" prop="xunfeiAppId">
          <el-input v-model="configForm.xunfeiAppId" placeholder="请输入讯飞TTS AppID" />
        </el-form-item>
        <el-form-item label="APIKey" prop="xunfeiApiKey">
          <el-input v-model="configForm.xunfeiApiKey" placeholder="请输入讯飞TTS APIKey" />
        </el-form-item>
        <el-form-item label="APISecret" prop="xunfeiApiSecret">
          <el-input v-model="configForm.xunfeiApiSecret" placeholder="请输入讯飞TTS APISecret" />
        </el-form-item>

        <el-divider content-position="left">Dify配置</el-divider>
        <el-form-item label="APIKey" prop="difyApiKey">
          <el-input v-model="configForm.difyApiKey" placeholder="请输入Dify APIKey" />
        </el-form-item>
        <el-form-item label="API地址" prop="difyApiUrl">
          <el-input v-model="configForm.difyApiUrl" placeholder="请输入Dify API地址" />
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup name="TalkConfig" lang="ts">
import { listConfig, updateConfig } from '@/api/system/config';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const loading = ref(true);
const configFormRef = ref();

const configForm = reactive({
  xunfeiAppId: '',
  xunfeiApiKey: '',
  xunfeiApiSecret: '',
  difyApiKey: '',
  difyApiUrl: ''
});

const configMap = ref(new Map());

const rules = {
  difyApiKey: [{ required: true, message: 'Dify APIKey不能为空', trigger: 'blur' }],
  difyApiUrl: [{ required: true, message: 'Dify API地址不能为空', trigger: 'blur' }]
};

/** 查询配置列表 */
function getList() {
  loading.value = true;
  listConfig({
    configType: 'N',
    pageNum: 1,
    pageSize: 100,
    configName: undefined,
    configKey: undefined
  }).then((response: any) => {
    const configs = response.rows.filter((item: any) =>
      item.configKey.startsWith('xunfei.') || item.configKey.startsWith('dify.')
    );

    configs.forEach((config: any) => {
      configMap.value.set(config.configKey, config);

      switch (config.configKey) {
        case 'xunfei.tts.appId':
          configForm.xunfeiAppId = config.configValue;
          break;
        case 'xunfei.tts.apiKey':
          configForm.xunfeiApiKey = config.configValue;
          break;
        case 'xunfei.tts.apiSecret':
          configForm.xunfeiApiSecret = config.configValue;
          break;
        case 'dify.apiKey':
          configForm.difyApiKey = config.configValue;
          break;
        case 'dify.apiUrl':
          configForm.difyApiUrl = config.configValue;
          break;
      }
    });

    loading.value = false;
  });
}

/** 保存配置 */
function handleSave() {
  configFormRef.value.validate((valid: boolean) => {
    if (valid) {
      const updates = [
        { key: 'xunfei.tts.appId', value: configForm.xunfeiAppId },
        { key: 'xunfei.tts.apiKey', value: configForm.xunfeiApiKey },
        { key: 'xunfei.tts.apiSecret', value: configForm.xunfeiApiSecret },
        { key: 'dify.apiKey', value: configForm.difyApiKey },
        { key: 'dify.apiUrl', value: configForm.difyApiUrl }
      ];

      const promises = updates.map(item => {
        const config = configMap.value.get(item.key);
        if (config) {
          return updateConfig({
            ...config,
            configValue: item.value
          });
        }
      }).filter(p => p !== undefined);

      Promise.all(promises).then(() => {
        proxy?.$modal.msgSuccess('配置已保存到 sys_config 表');
        getList();
      }).catch((error: any) => {
        console.error('保存配置失败:', error);
        proxy?.$modal.msgError('保存配置失败，请检查后端服务');
      });
    }
  });
}

getList();
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
