<template>
  <div class="model-config">
    <div class="config-header" @click="togglePanel">
      <img src="../../assets/svg/setting.png" alt="setting" class="config-icon" />
      <span>模型配置</span>
      <img
        :src="isPanelOpen ? upIcon : downIcon"
        alt="toggle"
        class="toggle-icon"
      />
    </div>

    <div v-show="isPanelOpen" class="config-panel">
      <div class="model-list">
        <div v-for="(model, index) in modelList" :key="index" class="model-item">
          <div class="model-header">
            <span class="model-title">模型 {{index + 1}}</span>
            <a-button type="link" danger size="small" @click="removeModel(index)">删除</a-button>
          </div>
          
          <div class="model-form">
            <div class="form-item">
              <label>选择模型</label>
              <a-select
                style="width: 200px;"
                v-model:value="model.type"
                placeholder="请选择模型"
                @change="(value) => handleModelChange(value, index)"
              >
                <a-select-opt-group v-for="group in modelGroups" :key="group.label" :label="group.label">
                  <a-select-option 
                    v-for="option in group.options" 
                    :key="option.value" 
                    :value="option.value"
                  >
                    {{ option.label }}
                  </a-select-option>
                </a-select-opt-group>
              </a-select>
            </div>

            <template v-if="model.type">
              <div class="form-item">
                <label>API Key</label>
                <a-input-password
                  v-model:value="model.key"
                  :placeholder="getKeyPlaceholder(model.type)"
                />
              </div>
              
              <template v-if="model.type === 'ollama'">
                <div class="form-item">
                  <label>服务器地址</label>
                  <a-input
                    v-model:value="model.endpoint"
                    placeholder="例如: http://localhost:11434"
                  />
                </div>
              </template>

              <template v-if="model.type === 'custom'">
                <div class="form-item">
                  <label>模型名称</label>
                  <a-input
                    v-model:value="model.name"
                    placeholder="请输入自定义模型名称"
                  />
                </div>
                <div class="form-item">
                  <label>服务器地址</label>
                  <a-input
                    v-model:value="model.endpoint"
                    placeholder="请输入API地址"
                  />
                </div>
              </template>
            </template>
          </div>
        </div>
      </div>

      <a-button 
        type="dashed" 
        block 
        class="add-model-btn"
        @click="addModel"
      >
        <PlusOutlined /> 添加模型
      </a-button>

      <div class="action-buttons">
        <a-button type="primary" :loading="saving" @click="saveConfig">
          保存配置
        </a-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import axios from "axios";

import upIcon from '@/assets/svg/ups.svg';
import downIcon from '@/assets/svg/down.svg';

const MODEL_GROUPS = [
  {
    label: '主流模型',
    options: [
      { label: 'ChatGPT', value: 'chatgpt', endpoint: 'https://api.openai.com/v1' },
      { label: 'Claude', value: 'claude', endpoint: 'https://api.anthropic.com' },
      { label: 'GPT-4', value: 'gpt4', endpoint: 'https://api.openai.com/v1' }
    ]
  },
  {
    label: '开源模型',
    options: [
      { label: 'DeepSeek', value: 'deepseek', endpoint: 'https://api.deepseek.com/v1' },
      { label: 'Ollama', value: 'ollama', endpoint: 'http://localhost:11434' },
      { label: 'ChatGLM', value: 'chatglm', endpoint: 'https://api.zhipuai.cn/v1' }
    ]
  },
  {
    label: '国内模型',
    options: [
      { label: '阿里通义千问', value: 'qianwen', endpoint: 'https://dashscope.aliyuncs.com/api/v1' },
      { label: '百度文心一言', value: 'wenxin', endpoint: 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1' },
      { label: '讯飞星火', value: 'spark', endpoint: 'https://spark-api.xf-yun.com/v1' }
    ]
  },
  {
    label: '其他',
    options: [
      { label: '自定义模型', value: 'custom', endpoint: '' }
    ]
  }
];

const isPanelOpen = ref(false);
const saving = ref(false);
const loading = ref(false);
const modelList = ref([
  { type: '', key: '', endpoint: '', name: '' }
]);

const modelGroups = ref([]);

// 获取模型列表
const fetchModels = async () => {
  loading.value = true;
  try {
    const response = await axios.get(`${import.meta.env.VITE_BASE_AI_API}/api/models`);
    const data = response.data;
    console.log(data);
    if (data.code === 2000) {
      
    // 将API返回的模型数据转换为组件需要的格式
    const apiModels = data.data.models.map(model => ({
      label: model.name,
      value: model.type,
      /* endpoint: model.endpoint || '', */
      description: model.description || ''
    }));

    // 更新模型组
    modelGroups.value = [
      {
        label: 'API模型',
        options: apiModels
      },
      ...MODEL_GROUPS // 保留原有的模型组
      ];
    }
  } catch (error) {
    console.error('获取模型列表失败:', error);
    message.error('获取模型列表失败');
  } finally {
    loading.value = false;
  }
};

const getKeyPlaceholder = (type) => {
  const placeholders = {
    'chatgpt': '请输入 OpenAI API Key',
    'gpt4': '请输入 OpenAI API Key',
    'claude': '请输入 Anthropic API Key',
    'deepseek': '请输入 DeepSeek API Key',
    'qianwen': '请输入阿里云 API Key',
    'wenxin': '请输入百度 API Key',
    'spark': '请输入讯飞 API Key',
    'chatglm': '请输入智谱 API Key',
    'ollama': '可选：请输入访问密钥',
    'custom': '请输入 API Key'
  };
  return placeholders[type] || '请输入 API Key';
};

const handleModelChange = (value, index) => {
  const model = modelList.value[index];
  const selectedOption = modelGroups.value
    .flatMap(group => group.options)
    .find(option => option.value === value);
  
  if (selectedOption) {
    model.endpoint = selectedOption.endpoint;
    model.name = selectedOption.label;
  }
};

const togglePanel = () => {
  isPanelOpen.value = !isPanelOpen.value;
};

const addModel = () => {
  modelList.value.push({ type: '', key: '', endpoint: '', name: '' });
};

const removeModel = (index) => {
  if (modelList.value.length === 1) {
    message.warning('至少保留一个模型配置');
    return;
  }
  modelList.value.splice(index, 1);
};

const validateModel = (model) => {
  if (!model.type) return false;
  if (!model.key) return false;
  if (model.type === 'ollama' && !model.endpoint) return false;
  if (model.type === 'custom' && (!model.name || !model.endpoint)) return false;
  return true;
};

const saveConfig = async () => {
  const hasInvalidModel = modelList.value.some(model => !validateModel(model));
  if (hasInvalidModel) {
    message.error('请填写完整的模型信息');
    return;
  }

  saving.value = true;
  try {
    localStorage.setItem('modelConfig', JSON.stringify(modelList.value));
    message.success('配置保存成功');
  } catch (error) {
    message.error('配置保存失败');
  } finally {
    saving.value = false;
  }
};

// 初始化时从localStorage加载配置
const initConfig = () => {
  const savedConfig = localStorage.getItem('modelConfig');
  if (savedConfig) {
    modelList.value = JSON.parse(savedConfig);
  }
};

// 组件挂载时加载配置和获取模型列表
onMounted(async () => {
  initConfig();
  await fetchModels();
});
</script>

<style scoped>
.model-config {
  border-top: 1px solid rgba(0, 0, 0, 0.06);
  background: #fff;
}

.config-header {
  padding: 12px 20px;
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.config-header:hover {
  background: rgba(0, 0, 0, 0.02);
}

.config-icon {
  width: 16px;
  height: 16px;
}

.toggle-icon {
  width: 12px;
  height: 12px;
  margin-left: auto;
}

.config-panel {
  padding: 12px 20px;
  border-top: 1px solid rgba(0, 0, 0, 0.06);
}

.model-list {
  margin-bottom: 16px;
}

.model-item {
  margin-bottom: 16px;
  padding: 12px;
  background: #fafafa;
  border-radius: 4px;
}

.model-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.model-title {
  font-size: 13px;
  color: rgba(0, 0, 0, 0.85);
}

.model-form {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.form-item {
  margin-bottom: 12px;
}

.form-item label {
  display: block;
  font-size: 12px;
  color: rgba(0, 0, 0, 0.45);
  margin-bottom: 8px;
}

.add-model-btn {
  margin-bottom: 16px;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
}

:deep(.ant-select),
:deep(.ant-input),
:deep(.ant-input-password) {
  font-size: 14px;
}

:deep(.ant-select-selector) {
  border-radius: 4px !important;
}

:deep(.ant-input),
:deep(.ant-input-password) {
  border-radius: 4px;
}
</style> 