<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="模型名称" prop="modelName">
              <el-input v-model="queryParams.modelName" placeholder="请输入模型名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="AI平台" prop="platformId">
              <el-select v-model="queryParams.platformId" placeholder="请选择AI平台" clearable @keyup.enter="handleQuery">
                <el-option v-for="item in aiPlatformList" :key="item.platformId" :label="item.platformName"
                           :value="item.platformId"/>
              </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-button type="success" plain icon="Plus" @click="handleAdd" v-hasPermi="['ai:aiModel:add']">新增</el-button>

            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
<!--      <template #header>-->
<!--        <el-row :gutter="10" class="mb8">-->
<!--          <el-col :span="1.5">-->
<!--            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['ai:aiModel:add']">新增</el-button>-->
<!--          </el-col>-->
<!--          <el-col :span="1.5">-->
<!--            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['ai:aiModel:edit']">修改</el-button>-->
<!--          </el-col>-->
<!--          <el-col :span="1.5">-->
<!--            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['ai:aiModel:remove']">删除</el-button>-->
<!--          </el-col>-->
<!--          <el-col :span="1.5">-->
<!--            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['ai:aiModel:export']">导出</el-button>-->
<!--          </el-col>-->
<!--          <right-toolbar v-model:showSearch="showSearch" :columns="columns" :search="true" @queryTable="getList"></right-toolbar>-->
<!--        </el-row>-->
<!--      </template>-->

      <div class="model-card-scroll" v-loading="loading">
        <el-empty v-if="aiModelList.length === 0" description="暂无模型" />
        <div v-else class="card-row-scroll">
          <el-card v-for="item in aiModelList" :key="item.modelId" class="model-card" shadow="hover">
            <div class="card-header">
              <div class="platform-icon">
                <img v-if="item.platformIcon" :src="item.platformIcon" :alt="item.platformIcon" class="icon-img" />
                <span v-else class="icon-emoji">🤖</span>
              </div>
              <span class="model-name">{{ item.modelName }}</span>
            </div>
            <div class="card-body">
              <div class="card-row"><span class="label">AI平台：</span>{{ item.platformName }}</div>
              <div class="card-row"><span class="label">模型类型：</span>{{ item.modelTypeName }}</div>
              <div class="card-row"><span class="label">基础模型：</span>{{ item.baseModelName }}</div>
            </div>
            <div class="card-actions-bottom">
              <el-button size="small" @click="onEdit(item)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(item)">删除</el-button>
            </div>
          </el-card>
        </div>
      </div>

<!--      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />-->
    </el-card>
    <!-- 添加或修改AI模型对话框 -->
    <ModelSettings :visible="showDialog" :model="editModel" @update:visible="showDialog = $event" @update:model="onDialogSave" />
  </div>
</template>

<script setup name="AiModel" lang="ts">
import { listAiModel, getAiModel, delAiModel, addAiModel, updateAiModel } from '@/api/ai/base/aiModel';
import { AiModelVO, AiModelQuery, AiModelForm } from '@/api/ai/base/aiModel/types';
import ModelSettings from './ModelSettings.vue'
import {ref} from "vue";
import {AiPlatformVO} from "@/api/ai/base/aiPlatform/types";
import {getAiPlatformList} from '@/api/ai/base/aiPlatform';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const aiModelList = ref<AiModelVO[]>([]);
const aiPlatformList = ref<AiPlatformVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const aiModelFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 列显隐信息
const columns = ref<FieldOption[]>([
  { key: 0, label: `主键`, visible: true },
  { key: 1, label: `租户ID`, visible: true },
  { key: 2, label: `模型名称`, visible: true },
  { key: 3, label: `AI平台ID，关联ai_platform`, visible: true },
  { key: 4, label: `模型类型ID，关联ai_model_type`, visible: true },
  { key: 5, label: `基础模型ID，关联ai_base_model`, visible: true },
  { key: 6, label: `计费类型(1token计费，2次数计费)`, visible: true },
  { key: 7, label: `模型价格`, visible: true },
  { key: 8, label: `请求地址`, visible: true },
  { key: 9, label: `秘钥`, visible: true },
  { key: 10, label: `密钥`, visible: true },
  { key: 11, label: `向量库(1milvus，2weaviate,)`, visible: true },
  { key: 12, label: `描述`, visible: true },
  { key: 13, label: `高级配置—模型温度(0-1);值越大，回复内容越赋有多样性创造性、随机性；设为0根据事实回答，希望得到精准答案应该降低该参数；日常聊天建议0.5-0.8`, visible: true },
  { key: 14, label: `高级配置—词汇属性(0-1);值越小，AI生成的内容越单调也越容易理解；值越大，AI回复的词汇范围越大，越多样化`, visible: true },
  { key: 15, label: `高级配置—话题属性(-2.0-2.0);值越大，越能够让AI更好的控制新话题的引入，建议微调或不变`, visible: true },
  { key: 16, label: `高级配置—重复属性(-2.0-2.0);值越大，越能够让AI更好的避免重复之前说过的话，建议微调或不变`, visible: true },
  { key: 17, label: `高级配置—最大回复(1-16000);设置AI最大回复内容大小，会影响返回结果内容的长度；普通聊天建议500-800；短文生成建议800-2000；代码生成建议2000-3600；长文生成建议4000左右`, visible: true },
  { key: 18, label: `激活标识(1是，0否)`, visible: true },
  { key: 19, label: `创建时间`, visible: true },
  { key: 20, label: `更新时间`, visible: true },
  { key: 21, label: `创建人`, visible: true },
  { key: 22, label: `更新人`, visible: true },
  { key: 23, label: `创建部门`, visible: true },
  { key: 24, label: `删除标志`, visible: true },
]);

const initFormData: AiModelForm = {
  modelId: undefined,
  modelName: undefined,
  platformId: undefined,
  modelTypeId: undefined,
  baseModelId: undefined,
  chargeType: undefined,
  modelPrice: undefined,
  apiEndpoint: undefined,
  apiKey: undefined,
  apiSecret: undefined,
  vectorLibrary: undefined,
  description: undefined,
  modelTemperature: undefined,
  vocabularyAttribute: undefined,
  topicAttribute: undefined,
  duplicateAttribute: undefined,
  maxReply: undefined,
  activeFlag: undefined,
}
const data = reactive<PageData<AiModelForm, AiModelQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    modelId: undefined,
    modelName: undefined,
    platformId: undefined,
    modelTypeId: undefined,
    baseModelId: undefined,
    chargeType: undefined,
    modelPrice: undefined,
    apiEndpoint: undefined,
    apiKey: undefined,
    apiSecret: undefined,
    vectorLibrary: undefined,
    description: undefined,
    modelTemperature: undefined,
    vocabularyAttribute: undefined,
    topicAttribute: undefined,
    duplicateAttribute: undefined,
    maxReply: undefined,
    activeFlag: undefined,
    params: {
    }
  },
  rules: {
    modelId: [
      { required: true, message: "主键不能为空", trigger: "blur" }
    ],
    modelName: [
      { required: true, message: "模型名称不能为空", trigger: "blur" }
    ],
    platformId: [
      { required: true, message: "AI平台ID，关联ai_platform不能为空", trigger: "blur" }
    ],
    modelTypeId: [
      { required: true, message: "模型类型ID，关联ai_model_type不能为空", trigger: "blur" }
    ],
    baseModelId: [
      { required: true, message: "基础模型ID，关联ai_base_model不能为空", trigger: "blur" }
    ],
    chargeType: [
      { required: true, message: "计费类型(1token计费，2次数计费)不能为空", trigger: "change" }
    ],
    modelPrice: [
      { required: true, message: "模型价格不能为空", trigger: "blur" }
    ],
    apiEndpoint: [
      { required: true, message: "请求地址不能为空", trigger: "blur" }
    ],
    apiKey: [
      { required: true, message: "秘钥不能为空", trigger: "blur" }
    ],
    apiSecret: [
      { required: true, message: "密钥不能为空", trigger: "blur" }
    ],
    vectorLibrary: [
      { required: true, message: "向量库(1milvus，2weaviate,)不能为空", trigger: "blur" }
    ],
    description: [
      { required: true, message: "描述不能为空", trigger: "blur" }
    ],
    modelTemperature: [
      { required: true, message: "高级配置—模型温度(0-1);值越大，回复内容越赋有多样性创造性、随机性；设为0根据事实回答，希望得到精准答案应该降低该参数；日常聊天建议0.5-0.8不能为空", trigger: "blur" }
    ],
    vocabularyAttribute: [
      { required: true, message: "高级配置—词汇属性(0-1);值越小，AI生成的内容越单调也越容易理解；值越大，AI回复的词汇范围越大，越多样化不能为空", trigger: "blur" }
    ],
    topicAttribute: [
      { required: true, message: "高级配置—话题属性(-2.0-2.0);值越大，越能够让AI更好的控制新话题的引入，建议微调或不变不能为空", trigger: "blur" }
    ],
    duplicateAttribute: [
      { required: true, message: "高级配置—重复属性(-2.0-2.0);值越大，越能够让AI更好的避免重复之前说过的话，建议微调或不变不能为空", trigger: "blur" }
    ],
    maxReply: [
      { required: true, message: "高级配置—最大回复(1-16000);设置AI最大回复内容大小，会影响返回结果内容的长度；普通聊天建议500-800；短文生成建议800-2000；代码生成建议2000-3600；长文生成建议4000左右不能为空", trigger: "blur" }
    ],
    activeFlag: [
      { required: true, message: "激活标识(1是，0否)不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询AI模型列表 */
const getList = async () => {
  loading.value = true;
  const res = await listAiModel(queryParams.value);
  aiModelList.value = res.data;
  // total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  aiModelFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: AiModelVO[]) => {
  ids.value = selection.map(item => item.modelId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  editModel.value = null
  showDialog.value = true
  dialog.title = "添加AI模型";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: AiModelVO) => {
  reset();
  const _modelId = row?.modelId || ids.value[0]
  const res = await getAiModel(_modelId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改AI模型";
}

/** 提交按钮 */
const submitForm = () => {
  aiModelFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.modelId) {
        await updateAiModel(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addAiModel(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: AiModelVO) => {
  const _modelIds = row?.modelId || ids.value;
  const _modelNames = row?.modelName || ids.value;
  await proxy?.$modal.confirm('是否确认删除AI模型名称为"' + _modelNames + '"的数据项？').finally(() => loading.value = false);
  await delAiModel(_modelIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('ai/aiModel/export', {
    ...queryParams.value
  }, `aiModel_${new Date().getTime()}.xlsx`)
}

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

}


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














const showDialog = ref(false)
const editModel = ref<any | null>(null)

function onAdd() {
  editModel.value = null
  showDialog.value = true
}
function onEdit(row: any) {
  editModel.value = { ...row }
  showDialog.value = true
}
function onDialogSave(model: any) {
  getList();
  // if (editModel.value && editModel.value.id) {
  //   // 修改
  //   const idx = allModels.value.findIndex(m => m.id === editModel.value.id)
  //   if (idx !== -1) allModels.value[idx] = { ...model, id: editModel.value.id }
  //   ElMessage.success('修改成功')
  // } else {
  //   // 新增
  //   const newId = Math.max(...allModels.value.map(m => m.id), 0) + 1
  //   allModels.value.push({ ...model, id: newId })
  //   ElMessage.success('新增成功')
  // }
  // showDialog.value = false
  // fetchList()
}
function onDelete(row: any) {
  ElMessageBox.confirm('确定要删除该模型吗？', '提示', { type: 'warning' })
    .then(() => {
      // allModels.value = allModels.value.filter(m => m.id !== row.id)
      // fetchList()
      ElMessage.success('删除成功')
    })
}
</script>

<style scoped>
.model-manage-fullscreen {
  /* position: fixed; */
  /* inset: 0; */
  /* width: 100vw; */
  /* height: 100vh; */
  background: #f7f8fa;
  overflow-y: auto;
  padding: 0 0 32px 0;
  display: flex;
  flex-direction: column;
  min-height: 100%;
}
.toolbar {
  display: flex;
  align-items: center;
  flex-direction: row;
  gap: 16px;
  margin: 32px 0 16px 0;
  max-width: 1200px;
  width: 100%;
  padding: 0 16px;
  justify-content: flex-start;
}
.toolbar-input {
  width: 200px;
}
.toolbar-select {
  width: 160px;
}
.toolbar-btn {
  min-width: 80px;
}
.model-card-scroll {
  /* width: 100vw; */
  padding: 0 0 0 16px;
  overflow-x: unset;
}
.card-row-scroll {
  display: flex;
  flex-wrap: wrap;
  gap: 24px;
  min-height: 180px;
  padding-bottom: 16px;
}
.model-card {
  position: relative;
  border-radius: 16px;
  width: 360px;
  height: 220px;
  min-width: 360px;
  max-width: 360px;
  min-height: 220px;
  max-height: 220px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  transition: box-shadow 0.2s;
  word-break: break-all;
}
.card-header {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 12px;
  margin-bottom: 12px;
}
.platform-icon {
  width: 50px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f4f4f4;
  border-radius: 8px;
  overflow: hidden;
}
.icon-img {
  width: 50px;
  height: 40px;
  object-fit: contain;
}
.icon-emoji {
  font-size: 22px;
}
.model-name {
  font-size: 20px;
  font-weight: 700;
  color: #222;
  flex: 1;
  word-break: break-all;
  white-space: normal;
}
.card-actions {
  display: flex;
  gap: 8px;
}
.card-body {
  font-size: 15px;
  color: #555;
  display: flex;
  flex-direction: column;
  gap: 6px;
}
.card-row {
  color: #555;
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  gap: 4px;
  flex-wrap: wrap;
  word-break: break-all;
  white-space: normal;
  line-height: 1.7;
}
.card-row .label {
  color: #888;
  min-width: 70px;
  display: inline-block;
  word-break: keep-all;
}
/* 新增右下角按钮样式 */
.card-actions-bottom {
  position: absolute;
  right: 16px;
  bottom: 10px;
  display: flex;
  gap: 8px;
}
</style>
