<template>
  <div class="knowledge-file">
    <el-card class="file-list">
      <template #header>
        <div class="card-header">
          <span>文件列表</span>
        </div>
      </template>
      
      <!-- 添加搜索表单 -->
      <div class="search-form">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="文件名称">
            <el-input v-model="searchForm.fileName" placeholder="请输入文件名称" clearable @keyup.enter="handleSearch" />
          </el-form-item>
          <el-form-item label="文件类型">
            <el-select v-model="searchForm.fileType" placeholder="请选择文件类型" clearable>
              <el-option v-for="item in fileTypes" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <el-table :data="fileList" style="width: 100%">
        <el-table-column prop="fileName" label="文件名称" />
        <el-table-column prop="createBy" label="上传人" />
        <el-table-column prop="createTime" label="上传时间">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button
              type="primary"
              link
              @click="handleDownload(scope.row)"
            >
              下载
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { get,post } from '../utils/request'

const route = useRoute()

const fileList = ref([])
// 添加搜索表单数据
const searchForm = ref({
  fileName: '',
  fileType: ''
})

// 添加分页数据
const pagination = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 文件类型选项
const fileTypes = ref(['pdf', 'doc', 'docx', 'xls', 'xlsx', 'md', 'sql', 'txt'])

// 获取文件列表
const getFileList = async () => {
  try {
    const konwInfoId = route.query.konwInfoId
    if (!konwInfoId) {
      ElMessage.error('知识库ID不能为空')
      return
    }
    console.log('route.query', route.query);
    const params = {
      konwInfoId: konwInfoId,
      fileName: searchForm.value.fileName,
      fileType: searchForm.value.fileType,
      pageNum: pagination.value.pageNum,
      pageSize: pagination.value.pageSize
    }
    const res = await get('/admin/knowInfo/getFlieList', params)
    if (res.code === 0) {
      fileList.value = res.data.rows || []
      pagination.value.total = Number(res.data.total) || 0
    } else {
      ElMessage.error(res.msg || '获取文件列表失败')
    }
  } catch (error) {
    console.error('获取文件列表失败:', error)
    ElMessage.error('获取文件列表失败')
  }
}

// 下载文件
const handleDownload = async (item) => {
  try {
    window.open(item.fileUrl, '_blank')
    // 添加文件下载记录
    await post('/admin/userHistoryLog/saveFileDownloadLog', {
      relatedId: item.id
    })
  } catch (error) {
    console.log('error', error);
    ElMessage.error('下载失败，请重试文件地址:'+item.fileUrl)
  }
}

// 搜索
const handleSearch = () => {
  pagination.value.pageNum = 1 // 搜索时重置到第一页
  getFileList()
}

// 重置
const handleReset = () => {
  searchForm.value = {
    fileName: '',
    fileType: ''
  }
  pagination.value.pageNum = 1 // 重置时回到第一页
  getFileList()
}

// 处理每页条数变化
const handleSizeChange = (val) => {
  pagination.value.pageSize = val
  getFileList()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  pagination.value.pageNum = val
  getFileList()
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

onMounted(() => {
  getFileList()
})
</script>

<style scoped lang="scss">
.knowledge-file {
  padding: 20px;

  .file-list {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .search-form {
      margin-bottom: 20px;
      .el-select{
        width: 120px;
      }
    }

    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>
