<template>
  <el-dialog v-model="props.visible" title="AI模型配置" width="600px" :close-on-click-modal="false"
             @update:model-value="val => emit('update:visible', val)">
    <el-form :model="form" label-width="120px" :rules="rules" ref="formRef">
      <!-- 基本信息：模型名称 -->
      <el-form-item label="模型名称" prop="modelName">
        <el-input v-model="form.modelName" placeholder="请输入AI模型名称"/>
      </el-form-item>

      <!-- AI平台选择 -->
      <el-form-item label="AI平台" prop="platformId">
        <el-select v-model="form.platformId" placeholder="请选择AI平台" @change="onPlatformChange"
                   :disabled="form.modelId">
          <el-option v-for="item in aiPlatformList" :key="item.platformId" :label="item.platformName"
                     :value="item.platformId"/>
        </el-select>
      </el-form-item>
      <!-- 基础模型选择 -->
      <el-form-item label="基础模型" prop="baseModelId">
        <el-select v-model="form.baseModelId" placeholder="请选择基础模型" @change="onBaseModelChange">
          <el-option v-for="item in baseModelList || []" :key="item.baseModelId" :label="item.baseModelName"
                     :value="item.baseModelId"/>
        </el-select>
      </el-form-item>

      <!-- 模型类型选择 -->
      <el-form-item label="模型类型" prop="modelTypeName">
        <el-input v-model="form.modelTypeName" disabled/>
      </el-form-item>

      <!-- API端点自动赋值 -->
      <el-form-item label="API端点" prop="apiEndpoint">
        <el-select v-model="form.apiEndpoint" placeholder="请选择API端点">
          <el-option v-for="item in apiEndpointList || []" :key="item.apiEndpointId" :label="item.apiEndpointName"
                     :value="item.apiEndpointId"/>
        </el-select>

      </el-form-item>

      <!-- API Key -->
      <el-form-item label="API Key" prop="apiKey">
        <el-input v-model="form.apiKey" placeholder="请输入API Key"/>
      </el-form-item>

      <!-- API Secret -->
      <el-form-item label="API Secret" prop="apiSecret">
        <el-input v-model="form.apiSecret" placeholder="请输入API Secret"/>
      </el-form-item>


      <!-- 高级信息 -->
      <el-card v-if="false">
        <el-divider>高级信息</el-divider>
        <!-- 预设加载放在高级信息最上面 -->
        <el-form-item label="加载预设">
          <el-radio-group v-model="preset" @change="applyPreset">
            <el-radio-button label="创意"/>
            <el-radio-button label="平衡"/>
            <el-radio-button label="精确"/>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="模型温度" prop="temperature">
          <div class="slider-input-group">
            <el-slider :model-value="form.temperature" @update:model-value="val => form.temperature = val" :min="0"
                       :max="1" :step="0.01" style="width: 120px;"/>
            <el-input-number v-model="form.temperature" :min="0" :max="1" :step="0.01"
                             style="width: 120px; margin-left: 8px;"/>
          </div>
        </el-form-item>
        <el-form-item label="词汇属性" prop="top_p">
          <div class="slider-input-group">
            <el-slider :model-value="form.top_p" @update:model-value="val => form.top_p = val" :min="0" :max="1"
                       :step="0.01" style="width: 120px;"/>
            <el-input-number v-model="form.top_p" :min="0" :max="1" :step="0.01"
                             style="width: 120px; margin-left: 8px;"/>
          </div>
        </el-form-item>
        <el-form-item label="话题属性" prop="presence_penalty">
          <div class="slider-input-group">
            <el-slider :model-value="form.presence_penalty" @update:model-value="val => form.presence_penalty = val"
                       :min="-2" :max="2" :step="0.01" style="width: 120px;"/>
            <el-input-number v-model="form.presence_penalty" :min="-2" :max="2" :step="0.01"
                             style="width: 120px; margin-left: 8px;"/>
          </div>
        </el-form-item>
        <el-form-item label="重复属性" prop="frequency_penalty">
          <div class="slider-input-group">
            <el-slider :model-value="form.frequency_penalty" @update:model-value="val => form.frequency_penalty = val"
                       :min="-2" :max="2" :step="0.01" style="width: 120px;"/>
            <el-input-number v-model="form.frequency_penalty" :min="-2" :max="2" :step="0.01"
                             style="width: 120px; margin-left: 8px;"/>
          </div>
        </el-form-item>
        <el-form-item label="最大回复" prop="max_tokens">
          <el-input-number v-model="form.max_tokens" :min="1" :max="16000"/>
        </el-form-item>
        '
      </el-card>
    </el-form>
    <template #footer>
      <el-button @click="onTest" :loading="buttonLoading">测试</el-button>
      <el-button type="primary" :loading="buttonLoading" @click="onSave">保存</el-button>
      <el-button @click="onClose">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {ref, reactive, watch, computed} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {getAiPlatformList, listAiBaseModels} from '@/api/ai/base/aiPlatform';
import {AiPlatformVO, AiPlatformQuery, AiPlatformForm} from '@/api/ai/base/aiPlatform/types';
import {listAiModel, getAiModel, delAiModel, addAiModel, updateAiModel, testAIModel} from '@/api/ai/base/aiModel';
import {AiModelVO, AiModelQuery, AiModelForm} from '@/api/ai/base/aiModel/types';

const {proxy} = getCurrentInstance() as ComponentInternalInstance;

const props = defineProps<{
  visible: boolean
  model: any
}>()

const emit = defineEmits(['update:visible', 'update:model'])

const formRef = ref()
const testing = ref(false)
const preset = ref('')

const aiPlatformList = ref<AiPlatformVO[]>([]);
const baseModelList = ref([]);
const apiEndpointList = ref([]);
const baseModelId = ref();

const displayApiKey = ref('********');
const displayApiSecret = ref('********');

const currentApiKey = ref('');
const currentApiSecret = ref('');

const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);

// 平台、模型类型、基础模型、API端点映射
const platforms = [
  {label: 'OpenAI', value: 'openai'},
  {label: 'DeepSeek', value: 'deepseek'},
  {label: '文心一言', value: 'wenxin'},
  {label: '通义千问', value: 'qianwen'},
]
const modelTypes: Record<string, any[]> = {
  openai: [
    {label: 'GPT-3.5', value: 'gpt-3.5'},
    {label: 'GPT-4', value: 'gpt-4'},
  ],
  deepseek: [
    {label: 'R1', value: 'r1'},
  ],
  wenxin: [
    {label: 'ERNIE-Bot', value: 'ernie-bot'},
  ],
  qianwen: [
    {label: 'Qwen-7B', value: 'qwen-7b'},
  ],
}
const baseModels: Record<string, any[]> = {
  'gpt-3.5': [
    {label: 'gpt-3.5-turbo', value: 'gpt-3.5-turbo'},
    {label: 'gpt-3.5-turbo-16k', value: 'gpt-3.5-turbo-16k'},
  ],
  'gpt-4': [
    {label: 'gpt-4', value: 'gpt-4'},
    {label: 'gpt-4-32k', value: 'gpt-4-32k'},
  ],
  'r1': [
    {label: 'deepseek-r1', value: 'deepseek-r1'},
  ],
  'ernie-bot': [
    {label: 'ERNIE-Bot', value: 'ernie-bot'},
  ],
  'qwen-7b': [
    {label: 'Qwen-7B', value: 'qwen-7b'},
  ],
}
const apiEndpoints: Record<string, string> = {
  'gpt-3.5-turbo': 'https://api.openai.com/v1/chat/completions',
  'gpt-3.5-turbo-16k': 'https://api.openai.com/v1/chat/completions',
  'gpt-4': 'https://api.openai.com/v1/chat/completions',
  'gpt-4-32k': 'https://api.openai.com/v1/chat/completions',
  'deepseek-r1': 'https://api.deepseek.com/v1/chat/completions',
  'ernie-bot': 'https://wenxin.baidu.com/moduleApi/portal/api/rest/1.0/ernie_bot',
  'Qwen-7B': 'https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation',
}

const form = reactive({
  modelId: undefined,
  platformId: undefined,
  modelTypeId: undefined,
  modelTypeCode: '',
  modelTypeName: '',
  baseModelId: undefined,
  apiEndpoint: '',
  modelName: '',
  apiKey: '',
  apiSecret: '',
  temperature: 0.7,
  top_p: 1,
  presence_penalty: 0,
  frequency_penalty: 0,
  max_tokens: 2048,
})

const rules = {
  platformId: [{required: true, message: '请选择AI平台', trigger: 'change'}],
  baseModelId: [{required: true, message: '请选择基础模型', trigger: 'change'}],
  modelName: [{required: true, message: '请输入模型名称', trigger: 'blur'}],
}

// 监听对话框显示状态，当打开时填充表单数据
watch(() => props.visible, async (newVal) => {
  console.log('visible changed:', newVal, 'model:', props.model)
  resetForm()
  currentApiKey.value = '';
  currentApiSecret.value = '';

  if (newVal && props.model) {
    // 编辑模式：填充现有数据
    Object.assign(form, props.model)
    currentApiKey.value = props.model.apiKey;
    currentApiSecret.value = props.model.apiSecret;
    form.apiKey = displayApiKey.value;
    form.apiSecret = displayApiSecret.value;

    await getBaseModelList();
    await getEndPointAndModelType();

    // 根据当前值设置预设
    // setPresetByValues()
  } else if (newVal && !props.model) {
    // 新增模式：重置表单
    // resetForm()
  }
}, {immediate: true})

// 重置表单
function resetForm() {
  Object.assign(form, {
    modelId: undefined,
    platformId: undefined,
    modelTypeId: undefined,
    modelTypeName: '',
    baseModelId: undefined,
    apiEndpoint: '',
    modelName: '',
    apiKey: '',
    apiSecret: '',
    temperature: 0.7,
    top_p: 1,
    presence_penalty: 0,
    frequency_penalty: 0,
    max_tokens: 2048,
  })

  baseModelList.value = [];
  apiEndpointList.value = [];

  preset.value = ''
}


function onPlatformChange(newPlatformId) {
  form.modelTypeId = ''
  form.modelTypeCode = '';
  form.modelTypeName = '';
  form.baseModelId = ''
  form.apiEndpoint = ''
  getBaseModelList()
}


function onModelTypeChange() {
  form.baseModelId = ''
  form.apiEndpoint = ''
}

function onBaseModelChange(newBaseModelId) {
  // form.apiEndpoint = apiEndpoints[form.baseModel] || ''
  form.modelTypeId = '';
  form.modelTypeCode = '';
  form.modelTypeName = '';
  form.apiEndpoint = ''
  getEndPointAndModelType();
}

function applyPreset(val: string) {
  if (val === '创意') {
    form.temperature = 0.95
    form.top_p = 1
    form.presence_penalty = 1.2
    form.frequency_penalty = 0.8
    form.max_tokens = 4096
  } else if (val === '平衡') {
    form.temperature = 0.7
    form.top_p = 0.9
    form.presence_penalty = 0.5
    form.frequency_penalty = 0.5
    form.max_tokens = 2048
  } else if (val === '精确') {
    form.temperature = 0.2
    form.top_p = 0.7
    form.presence_penalty = 0
    form.frequency_penalty = 0
    form.max_tokens = 1024
  }
}

function onTest() {
  let platformCode = getAiPlatformCode();

  formRef.value?.validate(async (valid: boolean) => {
    if (!valid) return
    buttonLoading.value = true;
    // 这里应调用后端API进行测试
    let apiKey = '';
    let apiKeyEncryptFlag = '';
    let apiSecret = '';
    let apiSecretEncryptFlag = '';
    if (form.modelId) {
      if (form.apiKey === displayApiKey.value) {
        apiKey = currentApiKey.value;
        apiKeyEncryptFlag = '1';
      } else {
        apiKey = form.apiKey;
        apiKeyEncryptFlag = '0';
      }

      if (form.apiSecret === displayApiSecret.value) {
        apiSecret = currentApiSecret.value;
        apiSecretEncryptFlag = '1';
      } else {
        apiSecret = form.apiSecret;
        apiSecretEncryptFlag = '0';
      }

    } else {
      apiKey = form.apiKey;
      apiKeyEncryptFlag = '0';
      apiSecret = form.apiSecret;
      apiSecretEncryptFlag = '0';
    }

    const paramsData = {
      apiKey: apiKey,
      apiKeyEncryptFlag: apiKeyEncryptFlag,
      apiSecret: apiSecret,
      apiSecretEncryptFlag: apiSecretEncryptFlag,
      modelType: form.modelTypeCode
    }

    await testAIModel(platformCode, paramsData).finally(() => buttonLoading.value = false);

    // await new Promise(r => setTimeout(r, 1000))
    proxy?.$modal.msgSuccess("测试成功");

  })
}

function onSave() {
  // alert(JSON.stringify(form))
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.modelId) {
        if (form.apiKey === displayApiKey.value) {
          form.apiKey = undefined;
        }
        if (form.apiSecret === displayApiSecret.value) {
          form.apiSecret = undefined;
        }
        await updateAiModel(form).finally(() => buttonLoading.value = false);
      } else {
        await addAiModel(form).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      // 发送更新事件给父组件
      emit('update:model', {...form})
      emit('update:visible', false)
      // await getList();
    }
  })


}

function onClose() {
  emit('update:visible', false)
}

/** 查询AI平台列表 */
const getPlatformList = async () => {
  const res = await getAiPlatformList({});
  console.log(res);
  aiPlatformList.value = res.data;

}

/** 查询基础模型列表 */
const getBaseModelList = async () => {
  const res = await listAiBaseModels({platformId: form.platformId});
  console.log(res);
  baseModelList.value = res.data;
}

const getEndPointAndModelType = async () => {
  baseModelList.value.forEach((item: any) => {
    if (item.baseModelId === form.baseModelId) {
      // alert(JSON.stringify(item))
      apiEndpointList.value = item.aiApiEndpointList;
      if (apiEndpointList.value && apiEndpointList.value.length > 0) {
        apiEndpointList.value.forEach((endpoint: any) => {
          if (endpoint.defaultFlag === '1') {
            form.apiEndpoint = endpoint.apiEndpointPath;
          }
        })
      }

      form.modelTypeId = item.modelTypeId;
      form.modelTypeCode = item.modelTypeCode;
      form.modelTypeName = item.modelTypeName;
    }
  })
}


const getAiPlatformCode = () => {
  const selectedOption = aiPlatformList.value.find(opt => opt.platformId === form.platformId);
  return selectedOption ? selectedOption.platformCode : '';
  // this.selectedCode = selectedOption ? selectedOption.code : '';
}


onMounted(() => {
  getPlatformList();
});

</script>

<style scoped>
.slider-value {
  margin-left: 8px;
  color: #888;
  font-size: 14px;
  min-width: 40px;
  display: inline-block;
}

.slider-input-group {
  display: flex;
  align-items: center;
}
</style>
