<template>
  <div class="document-page">
    <div class="page-header">
      <h1>河湖长制</h1>
      <p>文档管理：目录树浏览 + 文件上传下载</p>
    </div>
    
    <div class="page-content">
      <div class="sidebar">
        <div class="sidebar-header">
          <span class="sidebar-title">目录树</span>
        </div>
        
        <div class="tree-container">
          <el-tree
            :data="directoryTree"
            :props="treeProps"
            :default-expand-all="true"
            @node-click="handleNodeClick"
            highlight-current
            class="directory-tree"
          >
            <template #default="{ node }">
              <span class="tree-node">
                <el-icon v-if="node.children && node.children.length > 0">
                  <FolderOpened />
                </el-icon>
                <el-icon v-else>
                  <Folder />
                </el-icon>
                <span class="node-label">{{ node.label }}</span>
                <span v-if="getDirFileCount(node.data.id) > 0" class="file-count">
                  {{ getDirFileCount(node.data.id) }}
                </span>
              </span>
            </template>
          </el-tree>
        </div>
      </div>
      
      <div class="main-content">
        <div class="content-header">
          <div class="current-dir">
            <el-breadcrumb separator="/">
              <el-breadcrumb-item v-for="(item, index) in breadcrumb" :key="item.id">
                <span @click="goToDir(item.id)">{{ item.name }}</span>
              </el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          <div class="action-buttons">
            <el-upload
              class="upload-btn"
              :action="uploadUrl"
              :data="{ dirId: selectedDirId }"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              :show-file-list="false"
              accept=".doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf,.txt,.zip,.rar"
            >
              <el-button type="primary" icon="Upload">上传文件</el-button>
            </el-upload>
          </div>
        </div>
        
        <div class="file-list-container">
          <div v-if="fileList.length > 0" class="file-grid">
            <div 
              v-for="file in fileList" 
              :key="file.id" 
              class="file-card"
              @click="previewFile(file)"
            >
              <div class="file-icon">
                <el-icon :size="48">
                  <component :is="getFileIcon(file.fileExt)" />
                </el-icon>
              </div>
              <div class="file-info">
                <div class="file-name">{{ file.fileName }}</div>
                <div class="file-meta">
                  <span>{{ formatFileSize(file.fileSize) }}</span>
                  <span>{{ formatDate(file.uploadTime) }}</span>
                </div>
              </div>
              <div class="file-actions">
                <el-button 
                  type="text" 
                  icon="Download" 
                  @click.stop="handleDownload(file.id)"
                >下载</el-button>
                <el-button 
                  type="text" 
                  icon="Delete" 
                  @click.stop="handleDelete(file.id)"
                >删除</el-button>
              </div>
            </div>
          </div>
          
          <div v-else class="empty-state">
            <el-icon class="empty-icon"><Folder /></el-icon>
            <p>该目录下暂无文件</p>
            <p class="hint">点击上方"上传文件"按钮添加文档</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { 
  Folder, FolderOpened, Upload, Download, Delete,
  Document
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getDirectoryTree, getFileList, downloadFile, deleteFile } from '@/api/gx/document'

const directoryTree = ref([])
const fileList = ref([])
const selectedDirId = ref(1)
const breadcrumb = ref([{ id: 1, name: '河湖长制' }])
const uploadUrl = '/gx/file/upload'

const treeProps = {
  children: 'children',
  label: 'dirName',
  id: 'id'
}

const dirFileCount = ref({})

onMounted(() => {
  loadDirectoryTree()
})

function loadDirectoryTree() {
  getDirectoryTree().then(res => {
    directoryTree.value = res.data || []
    if (directoryTree.value.length > 0) {
      selectedDirId.value = directoryTree.value[0].id
      loadFileList(selectedDirId.value)
    }
  })
}

function handleNodeClick(data) {
  selectedDirId.value = data.id
  loadFileList(data.id)
  updateBreadcrumb(data)
}

function updateBreadcrumb(node) {
  const path = []
  findPath(directoryTree.value, node.id, path)
  breadcrumb.value = path.reverse()
}

function findPath(nodes, targetId, path) {
  for (const node of nodes) {
    if (node.id === targetId) {
      path.push({ id: node.id, name: node.dirName })
      return true
    }
    if (node.children && node.children.length > 0) {
      if (findPath(node.children, targetId, path)) {
        path.push({ id: node.id, name: node.dirName })
        return true
      }
    }
  }
  return false
}

function goToDir(dirId) {
  selectedDirId.value = dirId
  loadFileList(dirId)
  
  const index = breadcrumb.value.findIndex(item => item.id === dirId)
  breadcrumb.value = breadcrumb.value.slice(0, index + 1)
}

function loadFileList(dirId) {
  getFileList(dirId).then(res => {
    fileList.value = res.data || []
    updateDirFileCount()
  })
}

function updateDirFileCount() {
  dirFileCount.value = {}
}

function getDirFileCount(dirId) {
  return fileList.value.filter(f => f.dirId === dirId).length
}

function handleUploadSuccess(response) {
  if (response.code === 200) {
    ElMessage.success('文件上传成功')
    loadFileList(selectedDirId.value)
  } else {
    ElMessage.error(response.msg || '上传失败')
  }
}

function handleUploadError(error) {
  ElMessage.error('文件上传失败')
}

function handleDownload(fileId) {
  downloadFile(fileId).then(response => {
    const blob = new Blob([response.data])
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = getFileName(fileId)
    document.body.appendChild(a)
    a.click()
    window.URL.revokeObjectURL(url)
    document.body.removeChild(a)
  }).catch(() => {
    ElMessage.error('下载失败')
  })
}

function getFileName(fileId) {
  const file = fileList.value.find(f => f.id === fileId)
  return file ? file.fileName : 'download'
}

function handleDelete(fileId) {
  ElMessageBox.confirm('确定删除该文件吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteFile(fileId).then(res => {
      if (res.code === 200) {
        ElMessage.success('删除成功')
        loadFileList(selectedDirId.value)
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    })
  }).catch(() => {})
}

function previewFile(file) {
}

function getFileIcon(ext) {
  return Document
}

function formatFileSize(size) {
  if (!size) return '0 B'
  const units = ['B', 'KB', 'MB', 'GB']
  let result = size
  let unitIndex = 0
  while (result >= 1024 && unitIndex < units.length - 1) {
    result /= 1024
    unitIndex++
  }
  return result.toFixed(2) + ' ' + units[unitIndex]
}

function formatDate(dateStr) {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}
</script>

<style scoped>
.document-page {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.page-header {
  padding: 20px;
  background: #fff;
  border-radius: 12px;
  margin-bottom: 20px;
}

.page-header h1 {
  font-size: 24px;
  font-weight: bold;
  margin: 0 0 10px 0;
}

.page-header p {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.page-content {
  flex: 1;
  display: flex;
  gap: 20px;
  overflow: hidden;
}

.sidebar {
  width: 280px;
  background: #fff;
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.sidebar-header {
  padding: 15px;
  border-bottom: 1px solid #e4e7ed;
}

.sidebar-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.tree-container {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.directory-tree {
  font-size: 14px;
}

.tree-node {
  display: flex;
  align-items: center;
  gap: 6px;
}

.node-label {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-count {
  font-size: 12px;
  color: #909399;
  background: #f5f7fa;
  padding: 2px 6px;
  border-radius: 10px;
}

.main-content {
  flex: 1;
  background: #fff;
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.content-header {
  padding: 15px 20px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.current-dir {
  flex: 1;
}

.action-buttons {
  flex-shrink: 0;
}

.upload-btn {
  margin-left: 10px;
}

.file-list-container {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.file-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 20px;
}

.file-card {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}

.file-card:hover {
  border-color: #1c97e7;
  box-shadow: 0 2px 12px rgba(28, 151, 231, 0.15);
}

.file-icon {
  margin-bottom: 12px;
  color: #1c97e7;
}

.file-info {
  text-align: center;
  width: 100%;
}

.file-name {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-meta {
  font-size: 12px;
  color: #909399;
  display: flex;
  justify-content: center;
  gap: 15px;
}

.file-actions {
  position: absolute;
  top: 10px;
  right: 10px;
  display: none;
  gap: 5px;
}

.file-card:hover .file-actions {
  display: flex;
}

.file-actions .el-button {
  padding: 2px 8px;
  font-size: 12px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  color: #909399;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 16px;
  opacity: 0.5;
}

.empty-state p {
  font-size: 16px;
  margin: 0 0 8px 0;
}

.empty-state .hint {
  font-size: 13px;
}
</style>
