<template>
  <div class="kb-docs-page">
    <div class="kb-docs-header">
      <span><b>AI知识库：</b>{{ knowledgeBaseName}}</span>
      <el-button type="primary" @click="showUploadDialog = true" style="margin-right:auto; margin-left:20px;" >上传文档</el-button>
    </div>
    <el-row :gutter="20" v-loading="loading">
      <el-col v-for="doc in aiKnowledgeContentList" :key="doc.knowledgeContentId" :xs="24" :sm="12" :md="8" :lg="8"
              :xl="6" style="margin-bottom:20px;">
        <div :class="['doc-card', getStatusClass(doc)]" @click.self="goPreview(doc)">
          <!-- 右上角状态 -->
          <div class="doc-card-status-top" :class="getStatusClass(doc)">
            {{ getStatusText(doc) }}
          </div>

          <div class="doc-card-title">
            <span :class="['file-icon', getFileIconClass(doc)]"/>
            <span class="title-text" :title="doc.fileName">{{ doc.fileName }}</span>
          </div>

          <!-- 左下角上传信息 -->
          <div class="doc-card-upload-info">
            <div class="upload-time">{{ doc.updateTime || doc.createTime }}</div>
            <!--            <div class="upload-user">{{ doc.createBy || doc.updateBy || '未知用户' }}</div>-->
          </div>

          <div class="doc-card-footer">
            <div class="doc-card-actions">
              <el-button size="small" type="primary" v-if="Number(doc.contentStatus) !== 1"
                         @click.stop="vectorizeDoc(doc)">向量化
              </el-button>
              <el-button size="small" type="danger" @click.stop="handleDelete(doc)">删除</el-button>
            </div>
          </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-dialog v-model="showEditDialog" title="编辑文档" width="500px">
      <el-input v-model="editDocForm.title" placeholder="标题" style="margin-bottom:12px;"/>
      <el-input v-model="editDocForm.content" type="textarea" :rows="4" placeholder="内容"/>
      <div style="margin-top:12px;text-align:right;">
        <el-button @click="showEditDialog=false">取消</el-button>
        <el-button type="primary" @click="saveEditDoc">保存</el-button>
      </div>
    </el-dialog>
    <el-dialog v-model="showUploadDialog" title="上传文档" width="80vw" :modal-append-to-body="false"
               :close-on-click-modal="false" :destroy-on-close="true" :before-close="onUploadDialogClose">
      <KnowledgeBaseUpload @confirm="onUploadSuccess" @cancel="onUploadDialogClose"/>
    </el-dialog>
    <el-dialog v-model="showPreviewDialog" title="文档预览" width="80vw" height="90vw" :modal-append-to-body="false"
               :close-on-click-modal="false" :destroy-on-close="true">
      <KnowledgeBasePreview :doc="previewDoc"/>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {ref} from 'vue'
import {useRouter} from 'vue-router'
import KnowledgeBaseUpload from './knowledgeContentUpload.vue'
import KnowledgeBasePreview from './knowledgeContentPreview.vue'
import {
  listAiKnowledgeContent,
  vectorizeKnowledgeContent,
  delAiKnowledgeContent,
  delAiKnowledgeBase
} from '@/api/ai/skill/aiKnowledgeBase';
import {
  AiKnowledgeContentVO,
  AiKnowledgeContentQuery,
  AiKnowledgeContentForm
} from '@/api/ai/skill/aiKnowledgeContent/types';
import {ElMessage} from 'element-plus'
import {AiKnowledgeBaseVO} from "@/api/ai/skill/aiKnowledgeBase/types";

const {proxy} = getCurrentInstance() as ComponentInternalInstance;

const knowledgeBaseId = ref();
const knowledgeBaseName = ref();
const modelId = ref();
const embeddingKnowledgeContentVo = ref({});

const page = ref(1)
const pageSize = 6
const showEditDialog = ref(false)
const showUploadDialog = ref(false)
const editDocForm = ref({id: 0, title: '', content: '', status: 'enabled'})
const docList = ref([
  {
    id: 1,
    title: '文档A',
    content: '内容A第一行，内容A第二行，内容A第三行，内容A第四行，内容A第五行，内容A第六行，内容A第七行，内容A第八行，内容A第九行。',
    status: 'enabled'
  },
  {
    id: 2,
    title: '文档B',
    content: '内容B第一行，内容B第二行，内容B第三行，内容B第四行，内容B第五行，内容B第六行，内容B第七行，内容B第八行，内容B第九行。',
    status: 'disabled'
  },
  {
    id: 3,
    title: '文档C',
    content: '内容C第一行，内容C第二行，内容C第三行，内容C第四行，内容C第五行，内容C第六行，内容C第七行，内容C第八行，内容C第九行。',
    status: 'enabled'
  },
  // ...更多模拟数据
])


const aiKnowledgeContentList = ref<AiKnowledgeContentVO[]>([]);
const total = ref(0);
const loading = ref(true);

const initFormData: AiKnowledgeContentForm = {
  knowledgeContentId: undefined,
  knowledgeBaseId: undefined,
  contentTitle: undefined,
  contentWay: undefined,
  description: undefined,
  fileName: undefined,
  filePath: undefined,
  fileType: undefined,
  fileSize: undefined,
  contentStatus: undefined,
  overlapCharacter: undefined,
  totalChunk: undefined,
  createTime: undefined,
  updateTime: undefined,
  createBy: undefined,
  updateBy: undefined,
}
const data = reactive<PageData<AiKnowledgeContentForm, AiKnowledgeContentQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    knowledgeContentId: undefined,
    knowledgeBaseId: undefined,
    contentTitle: undefined,
    contentWay: undefined,
    description: undefined,
    fileName: undefined,
    filePath: undefined,
    fileType: undefined,
    fileSize: undefined,
    contentStatus: undefined,
    overlapCharacter: undefined,
    totalChunk: undefined,
    params: {}
  },
  rules: {
    knowledgeContentId: [
      {required: true, message: "主键不能为空", trigger: "blur"}
    ],

  }
});

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

/** 查询AI知识库内容列表 */
const getList = async () => {
  loading.value = true;
  const res = await listAiKnowledgeContent(queryParams.value);
  aiKnowledgeContentList.value = res.rows;
  total.value = res.total;
  loading.value = false;
  if (!aiKnowledgeContentList.value || aiKnowledgeContentList.value.length <= 0) {
    proxy.$modal.msgWarning('未查询到数据')
  }
}

// 根据文件名或fileType返回图标class
function getFileIconClass(doc: any) {
  // alert(JSON.stringify(doc))
  const name: string = doc.fileName || doc.contentTitle || ''
  const type: string = (doc.fileType || '').toString().toLowerCase()
  const ext = (name.split('.').pop() || '').toLowerCase()
  const t = type || ext
  if ([
    'doc', 'docx', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
  ].includes(t)) return 'icon-word'
  if ([
    'pdf', 'application/pdf'
  ].includes(t)) return 'icon-pdf'
  if ([
    'xls', 'xlsx', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  ].includes(t)) return 'icon-excel'
  if ([
    'ppt', 'pptx', 'application/vnd.ms-powerpoint', 'application/vnd.openxmlformats-officedocument.presentationml.presentation'
  ].includes(t)) return 'icon-ppt'
  if ([
    'txt', 'text/plain', 'md', 'markdown'
  ].includes(t)) return 'icon-txt'
  return 'icon-file'
}

function getStatusText(doc: any) {
  const v = Number(doc.contentStatus)
  if (v === 1) return '成功'
  if (v === 2) return '解析失败'
  if (v === 3) return '待解析'
  return '失败'
}

function getStatusClass(doc: any) {
  const v = Number(doc.contentStatus)
  if (v === 1) return 'enabled'
  if (v === 0) return 'pending'
  return 'disabled'
}

async function vectorizeDoc(doc) {
  try {
    proxy?.$modal.loading('正在向量化文档，请稍候...')

    // 如果有可用的向量化参数，则调用后端处理（可选）
    embeddingKnowledgeContentVo.value.knowledgeContentId = doc.knowledgeContentId
    embeddingKnowledgeContentVo.value.knowledgeBaseId = knowledgeBaseId.value
    embeddingKnowledgeContentVo.value.modelId = modelId.value
    await vectorizeKnowledgeContent(embeddingKnowledgeContentVo.value)
    ElMessage.success('向量化完成')
    doc.contentStatus = 1

  } catch (err) {
    console.error(err)
  } finally {
    proxy?.$modal.closeLoading()
  }
}

function formatTime(timestamp: string | number) {
  if (!timestamp) return '未知时间';
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}`;
}


const pagedList = computed(() => {
  const start = (page.value - 1) * pageSize
  return docList.value.slice(start, start + pageSize)
})

const showPreviewDialog = ref(false)
const previewDoc = ref(null)

function goPreview(doc: any) {
  previewDoc.value = doc
  showPreviewDialog.value = true
}

function editDoc(doc: any) {
  editDocForm.value = {...doc}
  showEditDialog.value = true
}

function saveEditDoc() {
  // TODO: 保存编辑逻辑
  const idx = docList.value.findIndex(d => d.id === editDocForm.value.id)
  if (idx !== -1) docList.value[idx] = {...editDocForm.value}
  showEditDialog.value = false
}


const handleDelete = async (row?: AiKnowledgeContentVO) => {
  const knowledgeBaseId = row?.knowledgeBaseId;
  await proxy?.$modal.confirm('是否确认删除知识库内容["' + row.fileName + '"]的数据项？').finally(() => loading.value = false);
  await delAiKnowledgeContent(knowledgeBaseId, row.knowledgeContentId);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

function handleFileChange(file) {
  // TODO: 处理文件选择
}

function confirmUpload() {
  // TODO: 上传逻辑
  showUploadDialog.value = false
}

function onUploadSuccess() {
  showUploadDialog.value = false
  // 可选：刷新文档列表
}

function onUploadDialogClose() {
  showUploadDialog.value = false
  getList();
}

onMounted(() => {
  let paramKnowledgeBaseId = proxy.$route.params?.knowledgeBaseId
  let paramModelId = proxy.$route.params?.modelId
  if (paramModelId === undefined || paramKnowledgeBaseId === undefined) {
    proxy?.$modal.msgWarning("请选择知识库和模型");
    return;
  }

  knowledgeBaseId.value = paramKnowledgeBaseId
  queryParams.value.knowledgeBaseId = paramKnowledgeBaseId
  modelId.value = paramModelId;
  knowledgeBaseName.value = decodeURIComponent(proxy.$route.params?.knowledgeBaseName)
  getList();
});

</script>

<style scoped>
.kb-docs-page {
  padding: 24px;
  height: 100%;
}

.kb-docs-header {
  display: flex;
  justify-content: flex-start;
  margin-bottom: 24px;
}

.doc-card {
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.06);
  padding: 16px 16px 48px 16px;
  cursor: pointer;
  position: relative;
  transition: box-shadow .2s, transform .2s;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  height: 160px;
}

.doc-card:hover {
  box-shadow: 0 10px 24px rgba(0, 0, 0, 0.10);
  transform: translateY(-2px);
}

.doc-card-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 0;
  display: flex;
  align-items: center;
  gap: 10px;
}

.title-text {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 隐藏内容区（仅标题卡片） */
.doc-card-content {
  display: none;
}

.doc-card-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  position: absolute;
  bottom: 12px;
  left: 16px;
  right: 16px;
}

.doc-card-status {
  margin-right: auto;
  font-size: 16px;
  font-weight: 600;
  color: #909399;
}

.doc-card-status.enabled {
  color: #67c23a;
}

.doc-card-status.pending {
  color: #e6a23c;
}

.doc-card-status.disabled {
  color: #f56c6c;
}

.doc-card.enabled {
  background: #f6ffed;
}

.doc-card.disabled {
  background: #fff1f0;
}

.doc-card-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  align-items: center;
}

.doc-card-status-top {
  position: absolute;
  top: 12px;
  right: 16px;
  font-size: 14px;
  font-weight: 600;
  color: #fff;
  padding: 4px 8px;
  border-radius: 6px;
  background-color: #409eff; /* 默认蓝色 */
}

.doc-card-status-top.enabled {
  background-color: #67c23a;
}

.doc-card-status-top.pending {
  background-color: #e6a23c;
}

.doc-card-status-top.disabled {
  background-color: #f56c6c;
}

.doc-card-upload-info {
  position: absolute;
  bottom: 12px;
  left: 16px;
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}

.upload-time {
  margin-bottom: 2px;
  font-weight: 500;
  color: #606266;
  font-size: 14px;
}

.upload-user {
  opacity: 0.8;
  color: #909399;
}

/* 文件类型图标 */
.file-icon {
  width: 50px;
  height: 50px;
  border-radius: 4px;
  display: inline-block;
}

.icon-word {
  background-image: url('@/assets/docx.png');
  background-size: 50px 50px;
}

.icon-pdf {
  background-image: url('@/assets/PDF.png');
  background-size: 50px 50px;
}

.icon-excel {
  background-image: url('@/assets/docx.png');
  background-size: 50px 50px;
}

.icon-ppt {
  background-image: url('@/assets/docx.png');
  background-size: 50px 50px;
}

.icon-txt {
  background-image: url('@/assets/docx.png');
  background-size: 50px 50px;
}

.icon-file {
  background-image: url('@/assets/document.png');
  background-size: 50px 50px;
}
</style>
