<template>
  <div class="knowledge-info-panel" v-if="knowledge">
    <!-- 顶部导航栏 -->
    <div class="panel-header">
      <el-button text @click="$emit('close')">
        <el-icon><ArrowLeft /></el-icon>
        返回列表
      </el-button>
      <div class="header-actions">
        <el-button 
          @click="handleEdit"
          :disabled="!hasWritePermission"
          :title="hasWritePermission ? '编辑知识库' : '无编辑权限'"
        >
          <el-icon><Edit /></el-icon>
          编辑
        </el-button>
        <el-button 
          type="primary" 
          @click="handleUpload"
          :disabled="!hasWritePermission"
          :title="hasWritePermission ? '上传文档' : '无上传权限'"
        >
          <el-icon><Upload /></el-icon>
          上传文档
        </el-button>
      </div>
    </div>

    <!-- 知识库信息卡片 -->
    <div class="knowledge-header">
      <div class="knowledge-avatar">
        <el-image 
          v-if="knowledge.avatar" 
          :src="FILE_DOWNLOAD_URL + knowledge.avatar" 
          fit="cover"
        />
        <el-icon v-else :size="48">📚</el-icon>
      </div>
      <div class="knowledge-details">
        <h2 class="knowledge-name">{{ knowledge.title }}</h2>
        <p class="knowledge-description">{{ knowledge.description || '暂无描述' }}</p>
        <div class="knowledge-meta">
          <el-tag :type="knowledge.status === 1 ? 'success' : 'info'" size="small">
            {{ knowledge.status === 1 ? '已启用' : '已禁用' }}
          </el-tag>
          <el-tag v-if="knowledge.canRead" type="success" size="small" effect="plain">
            可读
          </el-tag>
          <el-tag v-if="knowledge.canWrite" type="warning" size="small" effect="plain">
            可写
          </el-tag>
          <el-tag v-if="knowledge.canDelete" type="danger" size="small" effect="plain">
            可删除
          </el-tag>
          <span class="meta-item">
            <el-icon><Clock /></el-icon>
            {{ formatDate(knowledge.createTime) }}
          </span>
          <span class="meta-item" v-if="knowledge.difyDatasetId">
            <el-icon><Link /></el-icon>
            Dify: {{ knowledge.difyDatasetId }}
          </span>
        </div>
      </div>
    </div>

    <!-- 统计信息 -->
    <div class="stats-grid">
      <div class="stat-card">
        <div class="stat-icon">
          <el-icon color="#409EFF"><Document /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ documents.length }}</div>
          <div class="stat-label">总文档数</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon">
          <el-icon color="#67C23A"><Check /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ enabledDocumentsCount }}</div>
          <div class="stat-label">启用的文档</div>
        </div>
      </div>
      <!-- <div class="stat-card">
        <div class="stat-icon">
          <el-icon color="#E6A23C"><Files /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ knowledge.totalChunks || 0 }}</div>
          <div class="stat-label">总分段数</div>
        </div>
      </div> -->
    </div>

    <!-- 文档列表 -->
    <div class="documents-section">
      <div class="section-header">
        <h3 class="section-title">文档列表</h3>
        <el-input 
          v-model="searchQuery" 
          placeholder="搜索文档..." 
          clearable
          style="width: 300px;"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>

      <el-table 
        :data="filteredDocuments" 
        v-loading="loading"
        style="width: 100%"
        :empty-text="loading ? '加载中...' : '暂无文档'"
      >
        <el-table-column prop="fileName" label="文件名" min-width="200">
          <template #default="{ row }">
            <div class="file-name-cell">
              <el-icon><Document /></el-icon>
              <span>{{ row.fileName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="fileType" label="文件类型" width="100">
          <template #default="{ row }">
            <el-tag size="small">{{ row.fileType || 'unknown' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="fileSize" label="大小" width="120">
          <template #default="{ row }">
            {{ formatFileSize(row.fileSize) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="120">
          <template #default="{ row }">
            <div style="display: flex; gap: 8px;">
              <el-tag 
                :type="row.enabled ? 'success' : 'info'" 
                size="small"
              >
                {{ row.enabled ? '已启用' : '已禁用' }}
              </el-tag>
              <el-tag 
                v-if="row.displayStatus === 'indexing'"
                type="warning" 
                size="small"
              >
                索引中
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="chunkCount" label="分段数" width="100" />
        <el-table-column prop="createTime" label="上传时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-switch
              :model-value="row.enabled"
              :active-text="row.enabled ? '已启用' : '已禁用'"
              :loading="row._switching"
              :disabled="!hasWritePermission"
              @change="handleToggleEnabled(row, $event)"
              style="--el-switch-on-color: #67C23A; margin-right: 12px;"
              :title="hasWritePermission ? '' : '无修改权限'"
            />
            <el-button link type="primary" @click="handleViewSegments(row)">
              查看分段
            </el-button>
            <el-button link type="primary" @click="handleDownload(row)">
              下载
            </el-button>
            <el-button 
              link 
              type="danger" 
              @click="handleDeleteDocument(row)"
              :disabled="!hasDeletePermission"
              :title="hasDeletePermission ? '删除文档' : '无删除权限'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 上传对话框 -->
    <el-dialog
      v-model="uploadDialogVisible"
      title="上传文档到知识库"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-upload
        ref="uploadRef"
        :auto-upload="false"
        :on-change="handleFileChange"
        :file-list="fileList"
        drag
        multiple
        accept=".txt,.md,.pdf,.doc,.docx"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            支持 txt/md/pdf/doc/docx 格式文件，单个文件不超过50MB
          </div>
        </template>
      </el-upload>

      <template #footer>
        <el-button @click="uploadDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmUpload" :loading="uploading">
          确认上传
        </el-button>
      </template>
    </el-dialog>

    <!-- 文档分段对话框 -->
    <DocumentSegmentDialog
      v-if="selectedDocument && selectedDocument.difyDocumentId && props.knowledge?.difyDatasetId"
      :model-value="segmentDialogVisible"
      :dataset-id="props.knowledge.difyDatasetId"
      :document-id="selectedDocument.difyDocumentId"
      :can-write="hasWritePermission"
      :can-delete="hasDeletePermission"
      @update:model-value="segmentDialogVisible = $event"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { useStore } from 'vuex';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { UploadUserFile, UploadInstance } from 'element-plus';
import {
  ArrowLeft,
  Upload,
  Edit,
  Document,
  Clock,
  Link,
  Search,
  UploadFilled,
  Check
} from '@element-plus/icons-vue';
import type { AiKnowledge, AiUploadFile } from '@/types/ai';
import { fileUploadApi } from '@/apis/ai';
import { DocumentSegmentDialog } from './';
import { FILE_DOWNLOAD_URL } from '@/config';

defineOptions({
  name: 'KnowledgeInfo'
});

interface Props {
  knowledge: AiKnowledge | null;
}

const props = defineProps<Props>();
const emit = defineEmits<{
  close: [];
  refresh: [];
  edit: [knowledge: AiKnowledge];
}>();

const store = useStore();
const currentUserId = computed(() => store.getters['auth/user']?.id);

// 判断是否有写权限：是创建者 或 有canWrite权限
const hasWritePermission = computed(() => {
  return props.knowledge?.creator === currentUserId.value || props.knowledge?.canWrite;
});

// 判断是否有删除权限：是创建者 或 有canDelete权限
const hasDeletePermission = computed(() => {
  return props.knowledge?.creator === currentUserId.value || props.knowledge?.canDelete;
});

// 数据状态
const documents = ref<AiUploadFile[]>([]);
const loading = ref(false);
const searchQuery = ref('');
const uploadDialogVisible = ref(false);
const segmentDialogVisible = ref(false);
const selectedDocument = ref<AiUploadFile | null>(null);

// 计算启用的文档数量（从 Dify 返回的 enabled 字段）
const enabledDocumentsCount = computed(() => {
  return documents.value.filter(doc => doc.enabled === true).length;
});
const uploading = ref(false);

// 上传相关
const uploadRef = ref<UploadInstance>();
const fileList = ref<UploadUserFile[]>([]);

// 计算属性
const filteredDocuments = computed(() => {
  if (!searchQuery.value) return documents.value;
  const query = searchQuery.value.toLowerCase();
  return documents.value.filter(doc => 
    doc.fileName?.toLowerCase().includes(query)
  );
});

// 监听知识库变化
watch(() => props.knowledge, (newVal) => {
  if (newVal?.id) {
    loadDocuments();
  }
}, { immediate: true });

// 加载文档列表（从本地数据库查询，方便下载）
async function loadDocuments() {
  if (!props.knowledge?.id) return;
  
  try {
    loading.value = true;
    // 使用本地数据库的文件列表接口（包含 sys_file_id 和 file_path，方便下载）
    const result = await fileUploadApi.listFilesByKnowledge(props.knowledge.id);
    if (result.success) {
      documents.value = (result.dataList || []) as AiUploadFile[];
    } else {
      ElMessage.error(result.message || '加载文档列表失败');
    }
  } catch (error: any) {
    console.error('加载文档列表失败:', error);
    ElMessage.error('加载文档列表失败');
  } finally {
    loading.value = false;
  }
}

// 编辑知识库
function handleEdit() {
  if (props.knowledge) {
    emit('edit', props.knowledge);
  }
}

// 处理上传
function handleUpload() {
  uploadDialogVisible.value = true;
  fileList.value = [];
}

// 文件变化
function handleFileChange(file: any, fileListParam: any) {
  fileList.value = fileListParam;
}

// 确认上传
async function handleConfirmUpload() {
  if (fileList.value.length === 0) {
    ElMessage.warning('请选择要上传的文件');
    return;
  }

  if (!props.knowledge?.id) {
    ElMessage.error('知识库ID不存在');
    return;
  }

  try {
    uploading.value = true;
    const files = fileList.value
      .map(f => f.raw)
      .filter(f => f !== null && f !== undefined) as File[];
    
    // 逐个上传文件
    for (const file of files) {
      const result = await fileUploadApi.uploadFile(props.knowledge.id, file);
      if (!result.success) {
        ElMessage.error(`文件 ${file.name} 上传失败: ${result.message}`);
      }
    }
    
    ElMessage.success('文件上传成功');
    uploadDialogVisible.value = false;
    fileList.value = [];
    await loadDocuments();
    emit('refresh');
  } catch (error: any) {
    console.error('上传文件失败:', error);
    ElMessage.error('上传文件失败');
  } finally {
    uploading.value = false;
  }
}

// 查看分段
function handleViewSegments(document: AiUploadFile) {
  selectedDocument.value = document;
  segmentDialogVisible.value = true;
}

// 下载文件
function handleDownload(document: AiUploadFile) {
  if (document.sysFileId) {
    window.open(`/api/file/download/${document.sysFileId}`, '_blank');
  } else if (document.filePath) {
    window.open(`/api/file/download/${document.filePath}`, '_blank');
  } else {
    ElMessage.warning('文件路径不存在');
  }
}

// 切换文档启用/禁用状态
async function handleToggleEnabled(document: AiUploadFile, enabled: boolean) {
  if (!props.knowledge?.difyDatasetId || !document.difyDocumentId) {
    ElMessage.error('文档信息不完整');
    return;
  }

  try {
    // 添加loading状态
    (document as any)._switching = true;
    
    // 调用 Dify API 更新文档状态
    const result = await fileUploadApi.updateDocumentStatus(
      props.knowledge.difyDatasetId,
      document.difyDocumentId,
      enabled
    );
    
    if (result.success) {
      // 更新本地状态
      document.enabled = enabled;
      ElMessage.success(enabled ? '已启用文档' : '已禁用文档');
    } else {
      ElMessage.error(result.message || '更新失败');
    }
  } catch (error: any) {
    console.error('更新文档状态失败:', error);
    ElMessage.error('更新失败');
  } finally {
    (document as any)._switching = false;
  }
}

// 删除文档
async function handleDeleteDocument(document: AiUploadFile) {
  try {
    await ElMessageBox.confirm(
      `确定要删除文档"${document.fileName}"吗？此操作不可恢复。`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    if (document.id) {
      const result = await fileUploadApi.deleteFile(document.id);
      if (result.success) {
        ElMessage.success('删除成功');
        await loadDocuments();
        emit('refresh');
      } else {
        ElMessage.error(result.message || '删除失败');
      }
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除文档失败:', error);
      ElMessage.error('删除失败');
    }
  }
}

// 工具函数
function formatDate(date: string | Date | undefined): string {
  if (!date) return '-';
  const d = new Date(date);
  if (isNaN(d.getTime())) return '-';
  return d.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
}

function formatFileSize(bytes: number | undefined): string {
  if (!bytes || bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i];
}

</script>

<style scoped lang="scss">
.knowledge-info-panel {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: #FFFFFF;
  border-radius: 14px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  z-index: 10;
  box-sizing: border-box;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid #F3F3F5;
  background: #FFFFFF;

  .header-actions {
    display: flex;
    gap: 12px;
  }

  :deep(.el-button) {
    border-radius: 8px;
    font-weight: 500;

    &.el-button--primary {
      background: #E7000B;
      border-color: #E7000B;

      &:hover {
        background: #C90009;
      }
    }
  }
}

.knowledge-header {
  display: flex;
  gap: 20px;
  padding: 24px;
  background: linear-gradient(135deg, #F8F9FA 0%, #FFFFFF 100%);
  border-bottom: 1px solid #F3F3F5;

  .knowledge-avatar {
    width: 80px;
    height: 80px;
    border-radius: 12px;
    background: #FFFFFF;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    flex-shrink: 0;

    :deep(.el-image) {
      width: 100%;
      height: 100%;
      border-radius: 12px;
    }

    .el-icon {
      color: #E7000B;
    }
  }

  .knowledge-details {
    flex: 1;
    min-width: 0;

    .knowledge-name {
      font-size: 24px;
      font-weight: 600;
      color: #101828;
      margin: 0 0 8px 0;
      letter-spacing: -0.02em;
    }

    .knowledge-description {
      font-size: 14px;
      color: #667085;
      margin: 0 0 12px 0;
      line-height: 1.5;
    }

    .knowledge-meta {
      display: flex;
      align-items: center;
      gap: 16px;
      flex-wrap: wrap;

      .meta-item {
        display: flex;
        align-items: center;
        gap: 4px;
        font-size: 13px;
        color: #667085;

        .el-icon {
          font-size: 14px;
        }
      }
    }
  }
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  padding: 24px;
  border-bottom: 1px solid #F3F3F5;

  .stat-card {
    background: #F8F9FA;
    border-radius: 12px;
    padding: 20px;
    display: flex;
    align-items: center;
    gap: 16px;

    .stat-icon {
      width: 48px;
      height: 48px;
      border-radius: 10px;
      background: #FFFFFF;
      display: flex;
      align-items: center;
      justify-content: center;

      .el-icon {
        font-size: 24px;
      }
    }

    .stat-content {
      flex: 1;

      .stat-value {
        font-size: 24px;
        font-weight: 600;
        color: #101828;
        line-height: 1.2;
        margin-bottom: 4px;
      }

      .stat-label {
        font-size: 13px;
        color: #667085;
      }
    }
  }
}

.documents-section {
  flex: 1;
  padding: 24px;
  overflow-y: auto;

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .section-title {
      font-size: 16px;
      font-weight: 600;
      color: #101828;
      margin: 0;
    }
  }

  .file-name-cell {
    display: flex;
    align-items: center;
    gap: 8px;

    .el-icon {
      color: #E7000B;
      font-size: 16px;
    }
  }
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;

  .el-table__header th {
    background: #F8F9FA;
    color: #667085;
    font-weight: 500;
  }
}

:deep(.el-dialog) {
  border-radius: 12px;

  .el-dialog__header {
    border-bottom: 1px solid #F3F3F5;
    padding: 20px 24px;
  }

  .el-dialog__body {
    padding: 24px;
  }

  .el-upload-dragger {
    border-radius: 8px;
  }
}
</style>
