<template>
  <div class="share-page">
    <div class="share-container">
      <div class="share-box" :class="{ 'full-width': verified && fileInfo && fileInfo.fileList }">
        <!-- 加载中 -->
        <div v-if="loading" class="loading-box">
          <el-icon class="is-loading" :size="48" color="#409EFF"><Loading /></el-icon>
          <p style="margin-top: 20px;">正在加载分享文件...</p>
        </div>
        
        <!-- 需要密码 -->
        <div v-else-if="needPassword && !verified" class="password-box">
          <div class="share-header">
            <el-icon :size="64" color="#409EFF"><FolderOpened /></el-icon>
            <h1>文件分享</h1>
            <p>请输入提取码访问，如无提取码请直接点击确定</p>
          </div>
          
          <div class="password-input-box">
            <el-input
              v-model="password"
              placeholder="请输入提取码"
              size="large"
              maxlength="4"
              class="password-input"
              @keyup.enter="verifyPassword"
            />
            <el-button type="primary" size="large" @click="verifyPassword" class="submit-btn">
              访问文件
            </el-button>
          </div>
        </div>

        <!-- 文件信息 -->
        <div v-else-if="fileInfo" class="file-info-box">
          <!-- 单文件分享 -->
          <div v-if="!fileInfo.fileList">
            <div class="file-icon">
              <el-icon :size="80" color="#409EFF"><Document /></el-icon>
            </div>
            <h2>{{ fileInfo.fileName }}</h2>
            <div class="file-meta">
              <span><el-icon><Document /></el-icon> {{ formatFileSize(fileInfo.fileSize) }}</span>
              <span style="margin-left: 20px;"><el-icon><Clock /></el-icon> {{ parseTime(fileInfo.createTime) }}</span>
            </div>
            <div class="action-buttons">
              <el-button type="primary" icon="Download" @click="downloadFile">下载文件</el-button>
            </div>
          </div>
          
          <!-- 文件夹分享 -->
          <div v-else class="folder-share">
            <div class="folder-header">
              <el-icon :size="48" color="#409EFF"><FolderOpened /></el-icon>
              <h2>{{ fileInfo.fileName }}</h2>
              <p>共 {{ folderList.length }} 个文件夹，{{ fileInfo.fileList.length }} 个文件</p>
            </div>
            
            <!-- 工具栏 -->
            <div class="toolbar">
              <div class="toolbar-left">
                <el-breadcrumb separator="/" v-if="breadcrumb.length > 0">
                  <el-breadcrumb-item @click="goToFolder(-1)" style="cursor: pointer;">根目录</el-breadcrumb-item>
                  <el-breadcrumb-item 
                    v-for="(item, index) in breadcrumb" 
                    :key="index"
                    @click="goToFolder(index)"
                    style="cursor: pointer;">
                    {{ item.folderName }}
                  </el-breadcrumb-item>
                </el-breadcrumb>
                <span v-else style="color: #909399;">根目录</span>
              </div>
              <div class="toolbar-right">
                <el-button type="primary" icon="Download" @click="downloadAll">下载全部</el-button>
                <el-button 
                  v-if="selectedItems.length > 0"
                  type="success" 
                  icon="Download"
                  @click="downloadSelected">
                  下载选中 ({{ selectedItems.length }})
                </el-button>
              </div>
            </div>
            
            <!-- 文件列表 -->
            <el-table :data="allItems" style="width: 100%; margin-top: 20px;" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" />
              <el-table-column label="名称" min-width="300">
                <template #default="scope">
                  <div v-if="scope.row.isFolder" @click="enterFolder(scope.row)" style="cursor: pointer; display: flex; align-items: center;">
                    <el-icon color="#409EFF" style="margin-right: 8px;"><Folder /></el-icon>
                    <span style="color: #409EFF;">{{ scope.row.folderName }}</span>
                  </div>
                  <div v-else style="display: flex; align-items: center;">
                    <el-icon style="margin-right: 8px;"><Document /></el-icon>
                    <span>{{ scope.row.fileName }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="大小" width="150">
                <template #default="scope">
                  <span v-if="!scope.row.isFolder">{{ formatFileSize(scope.row.fileSize) }}</span>
                  <span v-else style="color: #909399;">-</span>
                </template>
              </el-table-column>
              <el-table-column label="上传时间" width="200">
                <template #default="scope">
                  {{ parseTime(scope.row.createTime) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120">
                <template #default="scope">
                  <el-button 
                    link
                    type="primary"
                    icon="Download" 
                    @click="scope.row.isFolder ? downloadFolder(scope.row) : downloadFileById(scope.row.fileId)">
                    下载
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          
          <div class="share-info">
            <p>
              <el-icon><Warning /></el-icon> 
              分享有效期至: {{ parseTime(shareInfo.expireTime) }}
            </p>
          </div>
        </div>

        <!-- 错误提示 -->
        <div v-else class="error-box">
          <el-icon :size="64" color="#F56C6C"><Warning /></el-icon>
          <h2>{{ errorMessage }}</h2>
          <p>{{ errorDetail }}</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup name="FileShare">
import { Loading, FolderOpened, Document, Clock, Folder, Warning } from '@element-plus/icons-vue'
import { verifyFileShare, getShareFolderFiles, listFolder } from '@/api/system/file'
import { parseTime } from '@/utils/yushu'

const { proxy } = getCurrentInstance()
const route = useRoute()

const loading = ref(true)
const needPassword = ref(false)
const verified = ref(false)
const password = ref('')
const shareCode = ref('')
const shareInfo = ref(null)
const fileInfo = ref(null)
const errorMessage = ref('')
const errorDetail = ref('')
const currentFolderId = ref(null)
const folderList = ref([])
const breadcrumb = ref([])
const selectedItems = ref([])

const allItems = computed(() => {
  const folders = folderList.value.map(folder => ({ ...folder, isFolder: true }))
  const files = fileInfo.value?.fileList?.map(file => ({ ...file, isFolder: false })) || []
  return [...folders, ...files]
})

onMounted(() => {
  shareCode.value = route.params.shareCode
  if (shareCode.value) {
    const code = route.query.code
    if (code) password.value = code
    loading.value = false
    needPassword.value = true
  } else {
    showError('分享链接无效', '请检查链接是否正确')
  }
})

async function loadShare() {
  loading.value = true
  try {
    const response = await verifyFileShare(shareCode.value, password.value || '')
    
    if (response.code === 200) {
      shareInfo.value = response.data
      
      if (response.data.resourceType === '0') {
        fileInfo.value = response.data.fileInfo
      } else {
        currentFolderId.value = response.data.folderId
        fileInfo.value = {
          fileName: '文件夹分享',
          fileList: response.data.fileList || []
        }
        loadFolderList(response.data.folderId)
      }
      
      verified.value = true
      needPassword.value = false
      if (password.value) proxy.$modal.msgSuccess('验证成功')
    } else {
      proxy.$modal.msgError(response.msg || '验证失败')
      needPassword.value = true
      verified.value = false
    }
  } catch (error) {
    proxy.$modal.msgError('加载失败，请重试')
    needPassword.value = true
    verified.value = false
  } finally {
    loading.value = false
  }
}

async function verifyPassword() {
  await loadShare()
}

function downloadFile() {
  if (!fileInfo.value) return
  const link = document.createElement('a')
  link.href = `${import.meta.env.VITE_APP_BASE_API}/system/file/share/download/${shareCode.value}`
  link.download = fileInfo.value.fileName
  link.click()
  proxy.$modal.msgSuccess('开始下载')
}

function downloadFileById(fileId) {
  const link = document.createElement('a')
  link.href = `${import.meta.env.VITE_APP_BASE_API}/system/file/share/download/${shareCode.value}/${fileId}`
  link.click()
  proxy.$modal.msgSuccess('开始下载')
}

async function loadFolderList(folderId) {
  try {
    const response = await listFolder({ parentId: folderId })
    if (response.code === 200) {
      folderList.value = response.rows || []
    }
  } catch (error) {
    console.error('加载文件夹列表失败:', error)
  }
}

async function enterFolder(folder) {
  loading.value = true
  try {
    const response = await getShareFolderFiles(shareCode.value, folder.folderId)
    if (response.code === 200) {
      currentFolderId.value = folder.folderId
      fileInfo.value.fileList = response.data || []
      loadFolderList(folder.folderId)
      breadcrumb.value.push({
        folderId: folder.folderId,
        folderName: folder.folderName
      })
    }
  } catch (error) {
    proxy.$modal.msgError('加载文件夹失败')
  } finally {
    loading.value = false
  }
}

async function goToFolder(index) {
  if (index === -1) {
    breadcrumb.value = []
    await loadShare()
  } else {
    const folder = breadcrumb.value[index]
    breadcrumb.value = breadcrumb.value.slice(0, index + 1)
    await enterFolder(folder)
  }
}

function handleSelectionChange(selection) {
  selectedItems.value = selection
}

function downloadAll() {
  proxy.$modal.confirm('确定要下载全部内容吗？').then(() => {
    const files = fileInfo.value.fileList || []
    const folders = folderList.value || []
    if (files.length === 0 && folders.length === 0) {
      proxy.$modal.msgWarning('没有可下载的内容')
      return
    }
    downloadBatch(files.map(f => f.fileId), folders.map(f => f.folderId))
  }).catch(() => {})
}

function downloadSelected() {
  if (selectedItems.value.length === 0) {
    proxy.$modal.msgWarning('请选择要下载的项目')
    return
  }
  const files = selectedItems.value.filter(item => !item.isFolder)
  const folders = selectedItems.value.filter(item => item.isFolder)
  downloadBatch(files.map(f => f.fileId), folders.map(f => f.folderId))
}

async function downloadBatch(fileIds, folderIds) {
  try {
    const response = await fetch(`${import.meta.env.VITE_APP_BASE_API}/system/file/share/downloadBatch/${shareCode.value}`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ fileIds, folderIds })
    })
    
    if (response.ok) {
      const blob = await response.blob()
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = '批量下载.zip'
      link.click()
      window.URL.revokeObjectURL(url)
      proxy.$modal.msgSuccess('开始下载')
    } else {
      proxy.$modal.msgError('下载失败')
    }
  } catch (error) {
    proxy.$modal.msgError('下载失败')
  }
}

function downloadFolder(folder) {
  const link = document.createElement('a')
  link.href = `${import.meta.env.VITE_APP_BASE_API}/system/file/share/downloadFolder/${shareCode.value}/${folder.folderId}`
  link.click()
  proxy.$modal.msgSuccess(`开始下载文件夹: ${folder.folderName}`)
}

function showError(message, detail) {
  loading.value = false
  errorMessage.value = message
  errorDetail.value = detail
}

function formatFileSize(bytes) {
  if (!bytes) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i]
}
</script>

<style lang="scss" scoped>
.share-page {
  min-height: 100vh;
  background: #f0f2f5 url("data:image/svg+xml,%3Csvg width='64' height='64' viewBox='0 0 64 64' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M8 16c4.418 0 8-3.582 8-8s-3.582-8-8-8-8 3.582-8 8 3.582 8 8 8zm0-2c3.314 0 6-2.686 6-6s-2.686-6-6-6-6 2.686-6 6 2.686 6 6 6zm33.414 0c5.955 0 10.791-4.836 10.791-10.791 0-5.955-4.836-10.791-10.791-10.791-5.955 0-10.791 4.836-10.791 10.791 0 5.955 4.836 10.791 10.791 10.791zm0-2c4.85 0 8.791-3.941 8.791-8.791 0-4.85-3.941-8.791-8.791-8.791-4.85 0-8.791 3.941-8.791 8.791 0 4.85 3.941 8.791 8.791 8.791zM16 48c4.418 0 8-3.582 8-8s-3.582-8-8-8-8 3.582-8 8 3.582 8 8 8zm0-2c3.314 0 6-2.686 6-6s-2.686-6-6-6-6 2.686-6 6 2.686 6 6 6zM8 32c4.418 0 8-3.582 8-8s-3.582-8-8-8-8 3.582-8 8 3.582 8 8 8zm0-2c3.314 0 6-2.686 6-6s-2.686-6-6-6-6 2.686-6 6 2.686 6 6 6zm33.414 32c5.955 0 10.791-4.836 10.791-10.791 0-5.955-4.836-10.791-10.791-10.791-5.955 0-10.791 4.836-10.791 10.791 0 5.955 4.836 10.791 10.791 10.791zm0-2c4.85 0 8.791-3.941 8.791-8.791 0-4.85-3.941-8.791-8.791-8.791-4.85 0-8.791 3.941-8.791 8.791 0 4.85 3.941 8.791 8.791 8.791zM63.5 0h-3.2c-1.036 0-1.884.848-1.884 1.884v3.2c0 1.036.848 1.884 1.884 1.884h3.2c1.036 0 1.884-.848 1.884-1.884v-3.2c0-1.036-.848-1.884-1.884-1.884zM61 5h-2V3h2v2zm-28 0h-3.2c-1.036 0-1.884.848-1.884 1.884v3.2c0 1.036.848 1.884 1.884 1.884h3.2c1.036 0 1.884-.848 1.884-1.884v-3.2c0-1.036-.848-1.884-1.884-1.884zM33 5h-2V3h2v2zM6.5 0H3.3c-1.036 0-1.884.848-1.884 1.884v3.2c0 1.036.848 1.884 1.884 1.884h3.2c1.036 0 1.884-.848 1.884-1.884v-3.2c0-1.036-.848-1.884-1.884-1.884zM4 5H2V3h2v2z' fill='%239C92AC' fill-opacity='0.05' fill-rule='evenodd'/%3E%3C/svg%3E");
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.share-container {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.share-box {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.08);
  padding: 48px;
  max-width: 520px;
  width: 100%;
  text-align: center;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  
  &.full-width {
    max-width: 1200px;
    padding: 32px;
  }
}

.loading-box,
.password-box,
.file-info-box,
.error-box {
  padding: 20px 0;
  animation: fadeIn 0.5s ease-out;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.share-header {
  text-align: center;
  margin-bottom: 40px;
  
  .el-icon {
    margin-bottom: 16px;
    padding: 16px;
    background: #ecf5ff;
    border-radius: 50%;
    color: #409eff;
  }
  
  h1 {
    font-size: 28px;
    font-weight: 700;
    color: #303133;
    margin: 8px 0;
    letter-spacing: -0.5px;
  }
  
  p {
    color: #909399;
    font-size: 15px;
    margin-top: 8px;
  }
}

.password-input-box {
  max-width: 320px;
  margin: 0 auto;
  
  .password-input {
    :deep(.el-input__wrapper) {
      padding: 4px 12px;
      border-radius: 12px;
      box-shadow: 0 0 0 1px #dcdfe6 inset;
      transition: all 0.2s;
      
      &.is-focus {
        box-shadow: 0 0 0 2px #409eff inset;
      }
    }
    
    :deep(.el-input__inner) {
      text-align: center;
      font-size: 24px;
      font-weight: 600;
      letter-spacing: 12px;
      height: 52px;
      color: #303133;
      
      &::placeholder {
        font-size: 16px;
        letter-spacing: 1px;
        font-weight: 400;
      }
    }
  }
  
  .submit-btn {
    width: 100%;
    margin-top: 24px;
    height: 48px;
    border-radius: 12px;
    font-size: 16px;
    font-weight: 600;
    letter-spacing: 1px;
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
    transition: all 0.2s;
    
    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 6px 16px rgba(64, 158, 255, 0.4);
    }
    
    &:active {
      transform: translateY(0);
    }
  }
}

.file-icon {
  margin-bottom: 24px;
  
  .el-icon {
    padding: 24px;
    background: #f0f2f5;
    border-radius: 20px;
    box-shadow: inset 0 0 0 1px rgba(0,0,0,0.05);
  }
}

h2 {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 12px;
  color: #303133;
}

.file-meta {
  color: #606266;
  margin: 24px 0;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 24px;
  
  span {
    display: flex;
    align-items: center;
    gap: 6px;
    background: #f5f7fa;
    padding: 6px 12px;
    border-radius: 20px;
  }
}

.folder-share {
  width: 100%;
  text-align: left;
  
  .folder-header {
    text-align: center;
    padding: 20px 0 40px;
    border-bottom: 1px solid #ebeef5;
    margin-bottom: 20px;
    
    .el-icon {
      padding: 16px;
      background: #ecf5ff;
      border-radius: 16px;
      margin-bottom: 16px;
    }
    
    h2 {
      margin: 0;
      font-size: 24px;
    }
    
    p {
      color: #909399;
      margin-top: 8px;
      font-size: 14px;
    }
  }
  
  .toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;
    
    .toolbar-left {
      flex: 1;
      overflow: hidden;
      
      .el-breadcrumb {
        font-size: 14px;
      }
    }
    
    .toolbar-right {
      display: flex;
      gap: 12px;
      flex-shrink: 0;
      margin-left: 20px;
    }
  }
}

:deep(.el-table) {
  --el-table-header-bg-color: #f5f7fa;
  --el-table-row-hover-bg-color: #f0f9eb;
  border-radius: 8px;
  overflow: hidden;
  
  th.el-table__cell {
    font-weight: 600;
    color: #606266;
  }
  
  .el-button--link {
    padding: 4px 8px;
    font-size: 13px;
    
    &:hover {
      background: #ecf5ff;
      border-radius: 4px;
    }
  }
}

.action-buttons {
  margin: 40px 0;
  
  .el-button {
    padding: 12px 32px;
    font-size: 16px;
    border-radius: 8px;
    height: auto;
  }
}

.share-info {
  margin-top: 32px;
  padding-top: 24px;
  border-top: 1px solid #ebeef5;
  
  p {
    color: #909399;
    font-size: 13px;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
  }
}

.error-box {
  .el-icon {
    background: #fef0f0;
    padding: 20px;
    border-radius: 50%;
    margin-bottom: 24px;
  }
  
  h2 {
    color: #303133;
    margin: 0 0 8px;
  }
  
  p {
    color: #909399;
  }
}
</style>
