<template>
  <el-dialog
    :model-value="props.visible"
    @update:model-value="emit('update:visible', $event)"
    :title="isEdit ? '编辑大模型配置' : '新增大模型配置'"
    width="800px"
    :before-close="handleClose">
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px" class="llm-config-form">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="配置名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入配置名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="提供商" prop="provider">
            <el-select v-model="formData.provider" placeholder="请选择提供商" @change="handleProviderChange">
              <el-option
                v-for="provider in providerOptions"
                :key="provider.value"
                :label="provider.label"
                :value="provider.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="模型名称" prop="model_name">
            <el-select v-model="formData.model_name" placeholder="请选择模型" filterable>
              <el-option v-for="model in modelOptions" :key="model.value" :label="model.label" :value="model.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="API地址" prop="api_url">
            <el-input v-model="formData.api_url" placeholder="请输入API地址" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="API密钥" prop="api_key">
        <el-input v-model="formData.api_key" type="password" placeholder="请输入API密钥" show-password />
      </el-form-item>

      <el-form-item label="描述" prop="description">
        <el-input v-model="formData.description" type="textarea" :rows="3" placeholder="请输入配置描述" />
      </el-form-item>

      <el-divider content-position="left">高级参数配置</el-divider>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="最大令牌数" prop="max_tokens">
            <el-input-number
              v-model="formData.max_tokens"
              :min="1"
              :max="100000"
              controls-position="right"
              style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="温度" prop="temperature">
            <el-input-number
              v-model="formData.temperature"
              :min="0"
              :max="2"
              :step="0.1"
              controls-position="right"
              style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="Top P" prop="top_p">
            <el-input-number
              v-model="formData.top_p"
              :min="0"
              :max="1"
              :step="0.1"
              controls-position="right"
              style="width: 100%" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="频率惩罚" prop="frequency_penalty">
            <el-input-number
              v-model="formData.frequency_penalty"
              :min="-2"
              :max="2"
              :step="0.1"
              controls-position="right"
              style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="存在惩罚" prop="presence_penalty">
            <el-input-number
              v-model="formData.presence_penalty"
              :min="-2"
              :max="2"
              :step="0.1"
              controls-position="right"
              style="width: 100%" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="启用状态" prop="is_enabled">
        <el-switch v-model="formData.is_enabled" />
        <span class="form-tip">启用后该配置将可用于文本处理</span>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { llmConfigStorage } from '@/utils/llmStorage'

interface Props {
  visible: boolean
  editData?: any
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const formRef = ref<FormInstance>()
const submitting = ref(false)

// 提供商选项
const providerOptions = [
  { label: 'DeepSeek', value: 'deepseek' },
  { label: '通义千问 (Qwen)', value: 'qwen' },
  { label: '自定义', value: 'custom' },
]

// 模型选项（根据提供商动态加载）
const modelOptions = ref<Array<{ label: string; value: string }>>([])

// 表单数据
const formData = reactive({
  name: '',
  provider: '',
  model_name: '',
  api_key: '',
  api_url: '',
  max_tokens: 4000,
  temperature: 0.7,
  top_p: 0.9,
  frequency_penalty: 0,
  presence_penalty: 0,
  is_enabled: true,
  description: '',
})

// 表单验证规则
const rules: FormRules = {
  name: [
    { required: true, message: '请输入配置名称', trigger: 'blur' },
    { min: 2, max: 50, message: '配置名称长度在 2 到 50 个字符', trigger: 'blur' },
  ],
  provider: [{ required: true, message: '请选择提供商', trigger: 'change' }],
  model_name: [{ required: true, message: '请选择模型名称', trigger: 'change' }],
  api_key: [{ required: true, message: '请输入API密钥', trigger: 'blur' }],
  api_url: [
    { required: true, message: '请输入API地址', trigger: 'blur' },
    { type: 'url', message: '请输入正确的URL格式', trigger: 'blur' },
  ],
  max_tokens: [{ required: true, message: '请输入最大令牌数', trigger: 'blur' }],
}

// 计算属性
const isEdit = computed(() => !!props.editData)

// 监听对话框显示状态
watch(
  () => props.visible,
  (visible) => {
    if (visible) {
      if (props.editData) {
        Object.assign(formData, props.editData)
      } else {
        resetForm()
      }
      loadModelOptions()
    }
  }
)

// 监听提供商变化
watch(
  () => formData.provider,
  () => {
    loadModelOptions()
    formData.model_name = ''
  }
)

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    name: '',
    provider: '',
    model_name: '',
    api_key: '',
    api_url: '',
    max_tokens: 4000,
    temperature: 0.7,
    top_p: 0.9,
    frequency_penalty: 0,
    presence_penalty: 0,
    is_enabled: true,
    description: '',
  })
  formRef.value?.clearValidate()
}

// 加载模型选项
const loadModelOptions = () => {
  modelOptions.value = getDefaultModels(formData.provider)
}

// 获取默认模型列表
const getDefaultModels = (provider: string) => {
  const modelMap: Record<string, Array<{ label: string; value: string }>> = {
    deepseek: [
      { label: 'DeepSeek-V2', value: 'deepseek-chat' },
      { label: 'DeepSeek-Coder', value: 'deepseek-coder' },
    ],
    qwen: [
      { label: 'Qwen2.5-72B-Instruct', value: 'qwen2.5-72b-instruct' },
      { label: 'Qwen2.5-32B-Instruct', value: 'qwen2.5-32b-instruct' },
      { label: 'Qwen2.5-14B-Instruct', value: 'qwen2.5-14b-instruct' },
      { label: 'Qwen2.5-7B-Instruct', value: 'qwen2.5-7b-instruct' },
    ],
    custom: [{ label: '自定义模型', value: 'custom' }],
  }
  return modelMap[provider] || []
}

// 处理提供商变化
const handleProviderChange = () => {
  // 根据提供商设置默认API地址
  const defaultUrls: Record<string, string> = {
    deepseek: 'https://api.deepseek.com/v1/chat/completions',
    qwen: 'https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation',
    custom: '',
  }
  formData.api_url = defaultUrls[formData.provider] || ''
}

// 移除测试连接功能

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  const valid = await formRef.value.validate()
  if (!valid) return

  submitting.value = true
  try {
    if (isEdit.value && props.editData?.id) {
      llmConfigStorage.update(props.editData.id, formData)
      ElMessage.success('更新成功')
    } else {
      llmConfigStorage.create(formData)
      ElMessage.success('创建成功')
    }
    emit('success')
    handleClose()
  } catch (error: any) {
    ElMessage.error(error.message || '操作失败')
  } finally {
    submitting.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  emit('update:visible', false)
  resetForm()
}
</script>

<style lang="scss" scoped>
.llm-config-form {
  .form-tip {
    margin-left: 10px;
    color: #909399;
    font-size: 12px;
  }
}

.dialog-footer {
  text-align: right;
}
</style>
