<template>
  <div class="kb-list-page">
    <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" label-width="120px">
            <el-form-item label="知识库名称" prop="knowledgeBaseName">
              <el-input v-model="queryParams.knowledgeBaseName" placeholder="请输入知识库名称" clearable
                        @keyup.enter="handleQuery"/>
            </el-form-item>
            <el-form-item label="AI模型" prop="modelId">
              <el-select v-model="queryParams.modelId" placeholder="请选择AI模型" clearable @keyup.enter="handleQuery">
                <el-option
                  v-for="model in aiModelList"
                  :key="model.modelId"
                  :label="model.modelName"
                  :value="model.modelId"
                />
              </el-select>

            </el-form-item>
            <el-form-item label="知识库类型" prop="knowledgeBaseTypeId">
              <el-select v-model="queryParams.knowledgeBaseTypeId" placeholder="请选择知识库类型" clearable
                         @keyup.enter="handleQuery">
                <el-option
                  v-for="model in aiKnowledgeBaseTypeList"
                  :key="model.knowledgeBaseTypeId"
                  :label="model.knowledgeBaseTypeName"
                  :value="model.knowledgeBaseTypeId"
                />
              </el-select>
            </el-form-item>


            <!--            <el-form-item label="状态(1启用，0禁用)" prop="knowledgeBaseStatus">-->
            <!--              <el-select v-model="queryParams.knowledgeBaseStatus" placeholder="请选择状态(1启用，0禁用)" clearable >-->
            <!--                <el-option v-for="dict in ${dictType}" :key="dict.value" :label="dict.label" :value="dict.value"/>-->
            <!--              </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-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:aiKnowledgeBase:add']">
              创建知识库
            </el-button>
          </el-col>
        </el-row>
      </template>

      <el-row :gutter="20" v-loading="loading">

        <el-col v-for="kb in aiKnowledgeBaseList" :key="kb.knowledgeBaseId" :span="8" style="margin-bottom:20px;">
          <div class="kb-card" :class="kb.knowledgeBaseStatus === '1' ? 'enabled' : 'disabled'" @click="goDetail(kb)">
            <div class="kb-card-header">
              <img :src="kb.knowledgeBaseIcon ? kb.knowledgeBaseIcon : knowledgeBaseIcon" alt="knowledgeBaseIcon"
                   class="knowledge-base-icon"/>
              <!--            <svg-icon class-name="search-icon" icon-class="knowledge-base"/>-->
              <div class="kb-card-title-container">
                <div class="kb-card-title">{{ kb.knowledgeBaseName }}</div>
                <div class="kb-card-knowledge-type">{{ kb.knowledgeBaseTypeName }}</div>
              </div>
            </div>
            <div class="kb-card-desc" :title="kb.knowledgeBaseDesc">{{ kb.knowledgeBaseDesc }}</div>
            <div class="kb-card-footer">
              <div class="kb-card-info">
                <span>向量模型：{{ kb.modelName }}</span>
              </div>
              <div class="kb-card-actions">
                <el-button size="small" type="primary" @click.stop="handleUpdate(kb)">编辑</el-button>
                <el-button size="small" type="danger" @click.stop="handleDelete(kb)">删除</el-button>
<!--                <el-button size="small" type="primary" @click.stop="openArrangeDialog(kb)">编排</el-button>-->
                <el-button size="small" type="success" @click.stop="goQA(kb)" v-if="kb.knowledgeBaseStatus === '1'">检索</el-button>
              </div>
            </div>
            <div class="kb-card-status-switch">
              <span v-if="kb.knowledgeBaseStatus === '1'">启用</span>
              <span v-else>禁用</span>
              <el-switch
                v-model="switchStatusMap[String(kb.knowledgeBaseId)]"
                :active-value="'1'"
                :inactive-value="'0'"
                @change="(val: string) => handleStatusChange(kb, val)"
                @click.stop
                style="margin-left: 8px;"
              />
            </div>
          </div>
        </el-col>
      </el-row>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                  v-model:limit="queryParams.pageSize" @pagination="getList"/>
    </el-card>

    <!-- 添加或修改AI知识库对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="aiKnowledgeBaseFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="知识库名称" prop="knowledgeBaseName">
          <el-input v-model="form.knowledgeBaseName" placeholder="请输入知识库名称"/>
        </el-form-item>
        <el-form-item label="AI模型" prop="modelId">
          <el-select v-model="form.modelId" placeholder="请选择AI模型">
            <el-option
              v-for="model in aiModelList"
              :key="model.modelId"
              :label="model.modelName"
              :value="model.modelId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="知识库类型" prop="knowledgeBaseTypeId">
          <el-select v-model="form.knowledgeBaseTypeId" placeholder="请选择知识库类型">
            <el-option
              v-for="model in aiKnowledgeBaseTypeList"
              :key="model.knowledgeBaseTypeId"
              :label="model.knowledgeBaseTypeName"
              :value="model.knowledgeBaseTypeId"
            />
          </el-select>
        </el-form-item>
<!--        <el-form-item label="分隔符" prop="knowledgeBaseSeparator">-->
<!--          <el-input v-model="form.knowledgeBaseSeparator" placeholder="请输入分隔符"/>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="检索条数" prop="retrieveLimit">-->
<!--          <el-input v-model="form.retrieveLimit" placeholder="请输入知识库中检索的条数"/>-->
<!--        </el-form-item>-->
        <el-form-item label="文本块大小" prop="textBlockSize">
          <el-input v-model="form.textBlockSize" placeholder="请输入文本块大小"/>
        </el-form-item>
        <el-form-item label="重叠字符数" prop="overlapCharacter">
          <el-input v-model="form.overlapCharacter" placeholder="请输入重叠字符数"/>
        </el-form-item>
        <el-form-item label="知识库描述" prop="knowledgeBaseDesc">
          <el-input type="textarea" v-model="form.knowledgeBaseDesc" placeholder="请输入知识库描述"/>
        </el-form-item>
        <el-form-item label="状态" prop="knowledgeBaseStatus">
          <el-radio-group v-model="form.knowledgeBaseStatus">
            <el-radio
              v-for="dict in ai_knowledge_base_status"
              :key="dict.value"
              :value="dict.value"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>


        </el-form-item>
        <el-form-item label="向量库" prop="vector" v-if="false">
          <el-input v-model="form.vector" placeholder="请输入向量库"/>
        </el-form-item>
        <el-form-item label="是否公开(1是，0否)" prop="openFlag" v-if="false">
          <el-input v-model="form.openFlag" placeholder="请输入是否公开(1是，0否)"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <el-dialog v-model="showArrangeDialog" title="AI问答编排设置" width="900px" top="5vh" :close-on-click-modal="false">
      <AiChatSettings v-if="showArrangeDialog"/>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {ref, computed} from 'vue'
import {useRouter} from 'vue-router'
import {ElMessageBox} from 'element-plus'
import KnowledgeBaseCreate from './knowledgeBaseCreate.vue'
import AiChatSettings from '../../base/aiApp/aiAppConfig.vue'

import {
  listAiKnowledgeBase,
  getAiKnowledgeBase,
  delAiKnowledgeBase,
  addAiKnowledgeBase,
  updateAiKnowledgeBase
} from '@/api/ai/skill/aiKnowledgeBase';
import {AiKnowledgeBaseVO, AiKnowledgeBaseQuery, AiKnowledgeBaseForm} from '@/api/ai/skill/aiKnowledgeBase/types';

import {getAiKnowledgeBaseTypeList} from '@/api/ai/base/aiKnowledgeBaseType';
import {AiKnowledgeBaseTypeVO} from '@/api/ai/base//aiKnowledgeBaseType/types';

import {getAiModelList} from '@/api/ai/base/aiModel';
import {AiModelVO} from '@/api/ai/base/aiModel/types';

import knowledgeBaseIcon from '@/assets/knowledge-base.png'

const {proxy} = getCurrentInstance() as ComponentInternalInstance;

const {ai_knowledge_base_status} = toRefs<any>(proxy?.useDict('ai_knowledge_base_status'));

const aiKnowledgeBaseList = ref<AiKnowledgeBaseVO[]>([]);
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 aiKnowledgeBaseFormRef = ref<ElFormInstance>();

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

const aiKnowledgeBaseTypeList = ref<AiKnowledgeBaseTypeVO[]>([]);
const aiModelList = ref<AiModelVO[]>([]);


const initFormData: AiKnowledgeBaseForm = {
  knowledgeBaseId: undefined,
  knowledgeBaseName: undefined,
  modelId: undefined,
  knowledgeBaseTypeId: undefined,
  knowledgeBaseSeparator: undefined,
  retrieveLimit: undefined,
  textBlockSize: undefined,
  overlapCharacter: undefined,
  questionSeparator: undefined,
  knowledgeBaseDesc: undefined,
  knowledgeBaseStatus: undefined,
  vector: 'milvus',
  openFlag: undefined,
}
const data = reactive<PageData<AiKnowledgeBaseForm, AiKnowledgeBaseQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    knowledgeBaseId: undefined,
    knowledgeBaseName: undefined,
    modelId: undefined,
    knowledgeBaseTypeId: undefined,
    knowledgeBaseSeparator: undefined,
    retrieveLimit: undefined,
    textBlockSize: undefined,
    overlapCharacter: undefined,
    questionSeparator: undefined,
    knowledgeBaseDesc: undefined,
    knowledgeBaseStatus: undefined,
    vector: undefined,
    openFlag: undefined,
    params: {}
  },
  rules: {
    knowledgeBaseName: [
      {required: true, message: "知识库名称不能为空", trigger: "blur"}
    ],
    modelId: [
      {required: true, message: "AI模型不能为空", trigger: "blur"}
    ],
    knowledgeBaseTypeId: [
      {required: true, message: "知识库类型不能为空", trigger: "blur"}
    ],
    knowledgeBaseStatus: [
      {required: true, message: "状态不能为空", trigger: "change"}
    ],
  }
});

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

/** 查询AI知识库类型下拉列表 */
const getAiKnowledgeBaseTypes = async () => {
  const res = await getAiKnowledgeBaseTypeList({});
  aiKnowledgeBaseTypeList.value = res.data;
}

/** 查询AI模型下来列表 */
const getAiModels = async () => {
  const res = await getAiModelList({modelTypeId: 2});
  aiModelList.value = res.data;
}


/** 查询AI知识库列表 */
const getList = async () => {
  loading.value = true;
  const res = await listAiKnowledgeBase(queryParams.value);
  aiKnowledgeBaseList.value = res.rows;
  // 初始化switchStatusMap
  aiKnowledgeBaseList.value.forEach(kb => {
    switchStatusMap.value[String(kb.knowledgeBaseId)] = kb.knowledgeBaseStatus
  })
  total.value = res.total;
  loading.value = false;
}

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

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

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

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

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

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加AI知识库";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: AiKnowledgeBaseVO) => {
  reset();
  const _knowledgeBaseId = row?.knowledgeBaseId || ids.value[0]
  const res = await getAiKnowledgeBase(_knowledgeBaseId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改AI知识库";
}

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

/** 删除按钮操作 */
const handleDelete = async (row?: AiKnowledgeBaseVO) => {
  const _knowledgeBaseIds = row?.knowledgeBaseId || ids.value;
  await proxy?.$modal.confirm('是否确认删除AI知识库["' + row.knowledgeBaseName + '"]的数据项？').finally(() => loading.value = false);
  await delAiKnowledgeBase(_knowledgeBaseIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

onMounted(() => {
  getList();
  getAiKnowledgeBaseTypes();
  getAiModels();
});


const router = useRouter()
const searchName = ref('')
const page = ref(1)
const pageSize = 6
const showCreateDialog = ref(false)
const showArrangeDialog = ref(false)

const kbList = ref([
  {
    id: 1,
    icon: '',
    name: '产品知识库',
    description: '产品相关知识',
    vectorModel: 'text-embedding-ada-002',
    status: 'enabled'
  },
  {id: 2, icon: '', name: '技术文档库', description: '技术文档集合', vectorModel: 'bge-large-zh', status: 'disabled'},
  {
    id: 3,
    icon: '',
    name: '运营知识库',
    description: '运营相关知识',
    vectorModel: 'text-embedding-ada-002',
    status: 'enabled'
  },
  // ...更多模拟数据
])

const filteredList = computed(() => {
  if (!searchName.value) return kbList.value
  return kbList.value.filter(kb => kb.name.includes(searchName.value))
})
const pagedList = computed(() => {
  const start = (page.value - 1) * pageSize
  return filteredList.value.slice(start, start + pageSize)
})

// 新增：用于受控切换的临时状态
const switchStatusMap = ref<Record<string, string>>({})

const handleStatusChange = async (kb: any, val: string) => {
  try {
    loading.value = true;
    await proxy?.$modal.confirm(`确定要将知识库“${kb.knowledgeBaseName}”${val === '1' ? '启用' : '禁用'}吗？`);
    let statusChangeForm = ref<AiKnowledgeBaseVO>();
    Object.assign(statusChangeForm, kb);
    statusChangeForm.knowledgeBaseStatus = val
    await updateAiKnowledgeBase(statusChangeForm)
      .then(() => {
        proxy?.$modal.msgSuccess("操作成功");
        kb.knowledgeBaseStatus = val
        switchStatusMap.value[String(kb.knowledgeBaseId)] = val
      }).catch(() => {
        // 还原switch
        switchStatusMap.value[String(kb.knowledgeBaseId)] = kb.knowledgeBaseStatus
      })
  } catch {
    switchStatusMap.value[String(kb.knowledgeBaseId)] = kb.knowledgeBaseStatus
  }finally {
    loading.value = false;
    console.log(kb)
  }
}

function goCreate() {
  router.push({name: 'KnowledgeBaseCreate'})
}

function goDetail(kb: any) {
  router.push({name: 'KnowledgeContent', params: {knowledgeBaseId: kb.knowledgeBaseId,modelId:kb.modelId,knowledgeBaseName: encodeURIComponent(kb.knowledgeBaseName)}})
}

function editKb(kb: any) {
  router.push({name: 'KnowledgeBaseEdit', params: {id: kb.id}})
}

function deleteKb(kb: any) {
  // TODO: 删除逻辑
  kbList.value = kbList.value.filter(item => item.id !== kb.id)
}

function goQA(kb: any) {
  router.push({name: 'KnowledgeBaseQA', params: {knowledgeBaseId: kb.knowledgeBaseId,embeddingModelId:kb.modelId,retrieveLimit:kb.retrieveLimit ? kb.retrieveLimit:5}})
}

function openArrangeDialog(kb: any) {
  showArrangeDialog.value = true
}

function onCreated(newKb) {
  // 可选：将新建的知识库添加到kbList
  showCreateDialog.value = false
}

function onCreateDialogClose() {
  showCreateDialog.value = false
}
</script>

<style scoped>
.kb-list-page {
  padding: 24px;
}

.kb-list-header {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
}

.kb-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px #f0f1f2;
  padding: 20px;
  cursor: pointer;
  position: relative;
  transition: box-shadow .2s;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 200px;
}

.kb-card.enabled {
  border-left: 6px solid #67c23a;
}

.kb-card.disabled {
  border-left: 6px solid #dcdfe6;
  background: #f5f7fa;
}

.kb-card-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.knowledge-base-icon {
  width: 40px;
  height: 40px;
  margin-right: 10px;
}

.kb-card-title-container {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  flex: 1;
}

.kb-card-title {
  font-size: 18px;
  font-weight: bold;

}

.kb-card-knowledge-type {
  font-size: 14px;
  color: #666;
  margin-top: 2px;
}

.kb-card-desc {
  color: #888;
  margin-bottom: 8px;
  min-height: 32px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.kb-card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 16px;
}

.kb-card-info {
  font-size: 13px;
  color: #666;
  margin-bottom: 0;
}

.kb-card-actions {
  display: flex;
  gap: 8px;
  margin-bottom: 0;
  justify-content: flex-end;
  align-items: center;
}

.kb-card-status {
  display: none;
}

.kb-card-status-switch {
  position: absolute;
  top: 18px;
  right: 18px;
  display: flex;
  align-items: center;
  font-size: 13px;
  font-weight: bold;
  color: #222;
  border-radius: 4px;
  padding: 0;
  z-index: 2;
  gap: 8px;
}

.kb-card-status-switch span {
  color: #fff;
  background: #67c23a;
  border-radius: 4px;
  padding: 2px 10px;
  display: inline-block;
}

.kb-card.disabled .kb-card-status-switch span {
  background: #bfbfbf;
}


</style>
