<template>
    <div>
        <el-drawer v-model="drawerVisible" direction="rtl" title="文件列表" size="40%">
        <template #header>
            <h4>文件列表</h4>
        </template>
        
        <div class="drawer-content">
            <!-- 上传按钮 -->
            <div class="upload-section">
            <el-button type="primary" size="small" @click="handleUpload">
                <el-icon><Upload /></el-icon>
                上传文件
            </el-button>
            </div>
            
            <!-- 文件列表 -->
            <div class="file-list" v-loading="loading"> 
            <!-- 文件列表内容 -->
                <div v-for="item in fileList" :key="item.id || item.fileKey" class="file-item">
                <div class="file-info">
                    <div class="file-icon">
                    <img :src="getFileIcon(item.file_name)" alt="文件图标" class="file-icon-img">
                    </div>
                    <div class="file-details">
                    <div class="file-name" :title="item.file_name">{{ item.file_name }}</div>
                    <!-- <div class="file-meta">
                        <span class="file-size">{{ formatFileSize(item.fileSize) }}</span>
                    </div> -->
                    </div>
                </div>
                <div class="file-actions">
                    <el-button type="primary" size="small" :disabled="!item.preview_url" @click="handlePreview(item)">预览</el-button>
                    <el-button type="success" size="small" @click="handleDownload(item)">下载</el-button>
                </div>
                </div>
                
                <!-- 空状态 -->
                <div v-if="fileList.length === 0" class="empty-state">
                <el-empty description="暂无文件" />
                </div>
            </div>
        </div>
        </el-drawer>
        <!-- 文件上传 -->
        <UpLoadFile 
            ref="uploadRef" 
            :fileType='["pdf", "png", "jpg", "jpeg","gif","doc","docx","xls","xlsx","ppt","pptx","txt","mp4","mp3"]' 
            :roomId="roomId" 
            @upload-success="handleUploadSuccess"
        />
        <!-- 文件预览 -->
        <BrowseFile ref="browseFileRef" :roomId="roomId"/>
    </div>
</template>
  
<script setup>
import { 
  getFileListApi, 
} from '@/api/conferencingRoom.js'
import { ElMessage } from 'element-plus';
import { ref } from "vue";
import { Upload } from '@element-plus/icons-vue'
import UpLoadFile from './upLoadFile.vue'
import BrowseFile from './browseFile.vue'
import fileLogo from '@/assets/images/file-logo.png';
import { emitter } from "@/utils/bus.js";
// 定义 emit
const emit = defineEmits([""]);

// 接收 props
const props = defineProps({
  roomId: {
    type: String,
    default: '',
  },
});

emitter.on('fileUploadStatus',async ()=>{ 
    if(drawerVisible.value){  
        await getFileList()
    }
})

const drawerVisible = ref(false);
const fileList = ref([]);
const loading = ref(false);
const uploadRef = ref(null);

//文件预览
const browseFileRef = ref(null);

// 根据文件扩展名获取文件图标
function getFileIcon(fileName) {
  return fileLogo;
}

// 格式化文件大小
function formatFileSize(size) {
  if (!size) return '未知大小';
  
  if (size < 1024) {
    return size + ' B';
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(2) + ' KB';
  } else {
    return (size / (1024 * 1024)).toFixed(2) + ' MB';
  }
}

// 文件下载功能
function handleDownload(file) {
  try {
    const iframe = document.createElement('iframe');
    iframe.style.display = 'none';
    iframe.src = file.source_url;
    document.body.appendChild(iframe);
    
    setTimeout(() => {
      document.body.removeChild(iframe);
    }, 5000); // 5秒后清理iframe
    
    ElMessage.success('开始下载文件');
  } catch (error) {
    console.error('iframe下载失败:', error);
    ElMessage.error('下载失败，请检查浏览器设置');
  }
}

// 文件预览功能
function handlePreview(file) {
  if (!file.preview_url) {
    ElMessage.error('文件链接无效');
    return;
  }
  browseFileRef.value.showEdit(file) 
}

// 上传文件
function handleUpload() {
    uploadRef.value.showEdit()
  // 这里可以添加文件上传逻辑
}

// 显示抽屉
async function show() {
  drawerVisible.value = true; 
  await getFileList()
}

//获取文件列表
async function getFileList(){
    loading.value = true; 
  try {
    // xsy
    const res = await getFileListApi(props.roomId);
    if (res.meta.code !== 200) {
      ElMessage.error(res.meta.msg);
      return;
    }
    fileList.value = res.data.files || [];
  } catch (error) {
    // console.error('获取文件列表失败:', error);
    ElMessage.error('获取文件列表失败');
  } finally {
    loading.value = false;
  }
}

//文件上传成功
async function handleUploadSuccess(){
    if(drawerVisible.value){ 
        await getFileList()
    } 
}

// 暴露方法给父组件
defineExpose({
  show,
});
</script>

<style lang="scss" scoped>
.drawer-content {
  padding: 0 10px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.upload-section {
  padding: 15px 0;
  border-bottom: 1px solid #e8e8e8;
  margin-bottom: 15px;
}

.file-list {
  flex: 1;
  overflow-y: auto;
}

.file-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
}

.file-info {
  display: flex;
  align-items: center;
  flex: 1;
  min-width: 0; /* 防止内容溢出 */
}

.file-icon {
  margin-right: 12px;
  flex-shrink: 0; /* 防止图标被压缩 */
}

.file-icon-img {
  width: 40px;
  height: 40px;
  object-fit: contain;
}

.file-details {
  flex: 1;
  min-width: 0; /* 防止文本溢出 */
  overflow: hidden; /* 隐藏溢出内容 */
}

.file-name {
  font-weight: 500;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.file-meta {
  font-size: 12px;
  color: #909399;
}

.file-actions {
  display: flex;
  gap: 8px;
  flex-shrink: 0; /* 防止按钮被压缩 */
  margin-left: 10px; /* 添加左边距，与文件信息保持距离 */
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.loading-state {
  padding: 10px 0;
}
</style>