/**
 * 网盘主布局组件 - 参考百度网盘设计
 */
(function() {
    'use strict';
    
    const { ref, computed, watch, onMounted, onUnmounted, toRefs } = typeof Vue !== 'undefined' ? Vue : {};
    
    if (!Vue) {
        console.error('Vue is not loaded');
        return;
    }
    
    window.DiskLayout = {
        components: {
            Sidebar: window.Sidebar,
            TopBar: window.TopBar,
            FileToolbar: window.FileToolbar,
            FileList: window.FileList,
            FileDetails: window.FileDetails
        },
        props: {
            files: {
                type: Array,
                default: () => []
            },
            loading: {
                type: Boolean,
                default: false
            },
            storageInfo: {
                type: Object,
                default: () => ({ used: 0, total: 0 })
            },
            showNewFolderInput: {
                type: Boolean,
                default: false
            },
            folderName: {
                type: String,
                default: ''
            },
            currentPathInfo: {
                type: Object,
                default: () => ({
                    path: '/',
                    pinid: '',
                    parentInfo: null
                })
            },
            imageFiles: {
                type: Array,
                default: () => []
            },
            videoFiles: {
                type: Array,
                default: () => []
            },
            audioFiles: {
                type: Array,
                default: () => []
            },
            documentFiles: {
                type: Array,
                default: () => []
            },
            spreadsheetFiles: {
                type: Array,
                default: () => []
            },
            pdfFiles: {
                type: Array,
                default: () => []
            },
            archiveFiles: {
                type: Array,
                default: () => []
            },
            codeFiles: {
                type: Array,
                default: () => []
            },
            hasMore: {
                type: Boolean,
                default: false
            },
            isLoadingMore: {
                type: Boolean,
                default: false
            }
        },
        emits: ['upload', 'refresh', 'file-click', 'file-download', 'file-preview', 'file-delete', 'search', 'new-folder', 'new-note', 'create-folder', 'cancel-new-folder', 'update:folder-name', 'path-change', 'load-more'],
        template: `
            <div class="disk-layout" :class="{ 'is-mobile': isMobile }">
                <!-- 顶部导航栏 -->
                <TopBar
                    :current-path="currentPath"
                    :storage-info="storageInfo"
                    @search="handleSearch"
                    @new-folder="handleNewFolder"
                    @upload="handleUpload">
                    <template #user-operate>
                        <slot name="user-operate"></slot>
                    </template>
                </TopBar>
                
                <div class="disk-main-container">
                    <!-- 桌面端：侧边栏 -->
                    <Sidebar
                        v-if="!isMobile"
                        :selected-category="selectedCategory"
                        @update:selectedCategory="selectedCategory = $event"
                        @category-change="handleCategoryChange" />
                    
                    <!-- 主内容区 -->
                    <div class="disk-main-content">
                        <!-- 工具栏 -->
                        <div class="disk-toolbar-wrapper">
                            <FileToolbar
                                v-model:selectedFileType="selectedFileType"
                                v-model:sortBy="sortBy"
                                v-model:viewMode="viewMode"
                                :selected-count="selectedFileCount"
                                :is-selection-mode="isSelectionMode"
                                @upload="handleUpload"
                                @refresh="handleRefresh"
                                @new-folder="handleNewFolder"
                                @new-note="handleNewNote"
                                @search="handleToolbarSearch"
                                @share="handleShare"
                                @download-selected="handleDownloadSelected"
                                @more-actions="handleMoreActions"
                                @cancel-selection="handleCancelSelection" />
                        </div>
                        
                        <!-- 移动端：横向滚动的侧边栏菜单 -->
                        <div v-if="isMobile" class="mobile-sidebar-menu-wrapper">
                            <el-scrollbar>
                                <div class="mobile-sidebar-menu">
                                    <div 
                                        v-for="item in allMenuItems" 
                                        :key="item.value"
                                        :class="['mobile-sidebar-menu-item', { 'is-active': selectedCategory === item.value }]"
                                        @click="handleCategoryChange(item.value)">
                                        <el-icon class="mobile-sidebar-menu-icon" :size="20" :color="item.color">
                                            <component :is="item.icon" />
                                        </el-icon>
                                        <span class="mobile-sidebar-menu-label">{{ item.label }}</span>
                                    </div>
                                </div>
                            </el-scrollbar>
                        </div>
                        
                        <!-- 文件列表和详情 -->
                        <div class="disk-content-wrapper">
                            <!-- 固定栏 -->
                            <div class="file-list-header-bar">
                                <div class="file-list-header-left">
                                    <div class="file-list-title">
                                        <!-- 当 currentPath == '全部文件' 且 currentPathInfo 不是根目录时，显示面包屑导航 -->
                                        <template v-if="currentPath === '全部文件' && currentFullPath.length > 0 && !isRootPath">
                                            <!-- 返回上一级按钮 -->
                                            <span 
                                                class="breadcrumb-item breadcrumb-back"
                                                @click="handleGoBack">
                                                返回上一级
                                            </span>
                                            <span class="breadcrumb-separator">|</span>
                                            
                                            <!-- 面包屑导航 -->
                                            <template v-for="(item, index) in currentFullPath" :key="item.pinid">
                                                <span 
                                                    class="breadcrumb-item"
                                                    :class="{ 'breadcrumb-active': index === currentFullPath.length - 1 }"
                                                    @click="handlePathClick(item, index)">
                                                    {{ item.path }}
                                                </span>
                                                <span 
                                                    v-if="index < currentFullPath.length - 1" 
                                                    class="breadcrumb-separator">
                                                    >
                                                </span>
                                            </template>
                                        </template>
                                        <!-- 其他情况直接显示 currentPath -->
                                        <template v-else>
                                            {{ currentPath }}
                                        </template>
                                    </div>
                                </div>
                                <div class="file-list-header-right" v-if="!isMobile">
                                    <button 
                                        class="file-details-toggle-btn"
                                        @click="toggleFileDetails"
                                        :title="fileDetailsExpanded ? '收起' : '展开'">
                                        <el-icon class="toggle-icon"><Grid /></el-icon>
                                        <el-icon class="toggle-arrow"><ArrowLeft /></el-icon>
                                        <span class="toggle-text">{{ fileDetailsExpanded ? '收起' : '展开' }}</span>
                                    </button>
                                </div>
                            </div>
                            
                            <!-- 文件列表容器 -->
                            <div class="file-list-wrapper">
                                <FileList
                                    ref="fileListRef"
                                    :files="displayedFiles"
                                    :selected-file-type="selectedFileType"
                                    :sort-by="sortBy"
                                    :view-mode="viewMode"
                                    :loading="loading"
                                    :current-path="currentPath"
                                    :show-new-folder-input="showNewFolderInput"
                                    :folder-name="folderName"
                                    :has-more="hasMore"
                                    :is-loading-more="isLoadingMore"
                                    @file-click="handleFileClick"
                                    @file-download="handleFileDownload"
                                    @file-preview="handleFilePreview"
                                    @file-delete="handleFileDelete"
                                    @upload="handleUpload"
                                    @create-folder="handleCreateFolder"
                                    @cancel-new-folder="handleCancelNewFolder"
                                    @update:folder-name="handleUpdateFolderName"
                                    @load-more="handleLoadMore"
                                    @selection-change="handleSelectionChange"
                                    :clear-selection-trigger="clearSelectionTrigger" />
                                
                                <!-- 文件详情组件（移动端隐藏） -->
                                <FileDetails
                                    v-if="!isMobile"
                                    :selected-file="selectedFile"
                                    :files="displayedFiles"
                                    :expanded="fileDetailsExpanded"
                                    :current-path="currentPath"
                                    @close="toggleFileDetails"
                                    @preview="handleFilePreview(selectedFile)"
                                    @download="handleFileDownload(selectedFile)"
                                    @delete="handleFileDelete(selectedFile)"
                                    @path-click="handleDetailsPathClick" />
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 移动端：底部Tab栏 -->
                <div v-if="isMobile" class="mobile-bottom-tabs">
                    <div 
                        class="mobile-tab-item"
                        :class="{ 'is-active': currentTab === 'home' }"
                        @click="handleTabChange('home')">
                        <el-icon :size="24"><House /></el-icon>
                        <span class="mobile-tab-label">首页</span>
                    </div>
                    <div 
                        class="mobile-tab-item"
                        :class="{ 'is-active': currentTab === 'files' }"
                        @click="handleTabChange('files')">
                        <el-icon :size="24"><Folder /></el-icon>
                        <span class="mobile-tab-label">文件</span>
                    </div>
                    <div 
                        class="mobile-tab-item"
                        :class="{ 'is-active': currentTab === 'share' }"
                        @click="handleTabChange('share')">
                        <el-icon :size="24"><Share /></el-icon>
                        <span class="mobile-tab-label">共享</span>
                    </div>
                    <div 
                        class="mobile-tab-item"
                        :class="{ 'is-active': currentTab === 'mine' }"
                        @click="handleTabChange('mine')">
                        <el-icon :size="24"><User /></el-icon>
                        <span class="mobile-tab-label">我的</span>
                    </div>
                </div>
            </div>
        `,
        setup(props, { emit }) {
            // 使用 toRefs 解构 props，保持响应式
            const { hasMore, isLoadingMore } = toRefs(props);
            
            // 获取 showToast 函数
            let showToast = null;
            if (typeof useToast === 'function') {
                const { showToast: toastFn } = useToast();
                showToast = toastFn;
            }
            
            // 监听 props.hasMore 的变化，用于调试
            watch(
                () => props.hasMore,
                (newVal) => {
                    
                    console.log('DiskLayout: props.hasMore changed to:', newVal);
                },
                { immediate: false }
            );
            
            const selectedCategory = ref('all');
            const selectedFileType = ref('all');
            const sortBy = ref('date-desc');
            const viewMode = ref('grid');
            const currentPath = ref('全部文件');
            const selectedFile = ref(null);
            const fileDetailsExpanded = ref(false);
            const isMobile = ref(false);
            const currentTab = ref('home');
            const selectedFileCount = ref(0);
            const isSelectionMode = ref(false);
            const clearSelectionTrigger = ref(0);
            const selectedFileIds = ref([]); // 存储选中的文件ID列表
            const fileListRef = ref(null); // FileList 组件引用
            
            // 检查是否为移动端
            const checkMobile = () => {
                isMobile.value = window.innerWidth < 500;
            };
            
            // 移动端菜单项（合并所有菜单）
            const allMenuItems = computed(() => {
                const menuItems = [
                    { value: 'all', label: '全部文件', icon: 'Folder', color: '#409EFF' },
                    { value: 'image', label: '图片', icon: 'Picture', color: '#67C23A' },
                    { value: 'video', label: '视频', icon: 'VideoPlay', color: '#409EFF' },
                    { value: 'recent', label: '最近', icon: 'Clock', color: '#409EFF' },
                    { value: 'starred', label: '收藏', icon: 'Star', color: '#409EFF' },
                    { value: 'shared', label: '分享', icon: 'Share', color: '#409EFF' },
                    // { value: 'trash', label: '回收站', icon: 'Delete', color: '#409EFF' },
                    { value: 'audio', label: '音频', icon: 'Headset', color: '#E6A23C' },
                    { value: 'document', label: '文档', icon: 'Document', color: '#F56C6C' },
                    { value: 'spreadsheet', label: '表格', icon: 'Grid', color: '#67C23A' },
                    { value: 'presentation', label: '演示文稿', icon: 'DataBoard', color: '#E6A23C' },
                    { value: 'archive', label: '压缩包', icon: 'Box', color: '#909399' },
                    { value: 'code', label: '代码', icon: 'Document', color: '#606266' }
                ];
                return menuItems;
            });
            
            // 处理Tab切换
            const handleTabChange = (tab) => {
                currentTab.value = tab;
                if (tab === 'home') {
                    // 首页就是全部文件，不需要额外操作
                } else {
                    // 其他tab暂时提示功能开发中
                    if (showToast) {
                        showToast('功能开发中', 'info');
                    }
                }
            };
            
            // 切换文件详情面板
            const toggleFileDetails = () => {
                fileDetailsExpanded.value = !fileDetailsExpanded.value;
            };
            
            // 初始化移动端检查
            onMounted(() => {
                checkMobile();
                window.addEventListener('resize', checkMobile);
            });
            
            onUnmounted(() => {
                window.removeEventListener('resize', checkMobile);
            });
            
            // 当选择"全部文件"时，自动切换到列表视图
            watch(() => selectedCategory.value, (newVal) => {
                if (newVal === 'all') {
                    viewMode.value = 'list';
                }
            }, { immediate: true });

          
            
            // 根据侧边栏分类筛选文件
            const displayedFiles = computed(() => {
                if (selectedCategory.value === 'all') {
                    return props.files;
                }
                
                // 根据分类返回对应的文件数组
                const categoryMap = {
                    'image': props.imageFiles || [],
                    'video': props.videoFiles || [],
                    'audio': props.audioFiles || [],
                    'document': props.documentFiles || [],
                    'spreadsheet': props.spreadsheetFiles || [],
                    'presentation': props.pdfFiles || [],
                    'archive': props.archiveFiles || [],
                    'code': props.codeFiles || []
                };
                
                return categoryMap[selectedCategory.value] || [];
            });
            
            // 递归获取所有父级路径信息
            const buildPathArray = (pathInfo, result = []) => {
                if (!pathInfo || !pathInfo.path) {
                    return result;
                }
                
                // 如果存在 parentInfo，先递归处理父级
                if (pathInfo.parentInfo && 
                    pathInfo.parentInfo !== null && 
                    pathInfo.parentInfo !== undefined &&
                    pathInfo.parentInfo.path !== null && 
                    pathInfo.parentInfo.path !== undefined) {
                    buildPathArray(pathInfo.parentInfo, result);
                }
                
                // 将当前路径信息添加到结果数组
                result.push({
                    path: pathInfo.path,
                    pinid: pathInfo.pinid
                });
                
                return result;
            };
            
            // 计算属性：获取完整的路径数组
            const currentFullPath = computed(() => {
                if (!props.currentPathInfo || !props.currentPathInfo.path) {
                    return [];
                }
                
                // 如果是根目录（parentInfo 为 null 或 undefined），返回空数组
                if (!props.currentPathInfo.parentInfo || 
                    props.currentPathInfo.parentInfo === null ||
                    props.currentPathInfo.parentInfo === undefined) {
                    return [];
                }
                
                // 递归构建路径数组
                return buildPathArray(props.currentPathInfo);
            });
            
            // 判断是否为根目录
            const isRootPath = computed(() => {
                return !props.currentPathInfo || 
                       !props.currentPathInfo.parentInfo || 
                       props.currentPathInfo.parentInfo === null;
            });
            
            // 处理返回上一级
            const handleGoBack = () => {
                if (!props.currentPathInfo || !props.currentPathInfo.parentInfo) {
                    return;
                }
                
                // 更新 currentPathInfo 为父级信息
                const newPathInfo = { ...props.currentPathInfo.parentInfo };
                emit('path-change', newPathInfo);
            };
            
            // 处理路径点击（从面包屑导航）
            const handlePathClick = (item, index) => {
                // 如果是最后一个（当前目录），不允许点击
                if (index === currentFullPath.value.length - 1) {
                    return;
                }
                
                // 根据点击的路径，构建新的 currentPathInfo
                // 需要从根目录开始，找到到点击路径的所有父级信息
                const buildPathInfo = (targetPinid, pathArray, currentIndex) => {
                    if (currentIndex === 0) {
                        // 根目录
                        return {
                            path: pathArray[0].path,
                            pinid: pathArray[0].pinid,
                            parentInfo: null
                        };
                    }
                    
                    // 递归构建父级信息
                    const parentInfo = buildPathInfo(targetPinid, pathArray, currentIndex - 1);
                    
                    return {
                        path: pathArray[currentIndex].path,
                        pinid: pathArray[currentIndex].pinid,
                        parentInfo: parentInfo
                    };
                };
                
                // 构建新的路径信息
                const newPathInfo = buildPathInfo(item.pinid, currentFullPath.value, index);
                emit('path-change', newPathInfo);
            };
            
            // 处理文件详情中的路径点击（返回到全部文件）
            const handleDetailsPathClick = () => {
                // 返回到全部文件视图
                selectedCategory.value = 'all';
                currentPath.value = '全部文件';
                emit('refresh');
            };
            
            // 处理分类改变
            const handleCategoryChange = (category) => {
                // 更新选中的分类
                
                selectedCategory.value = category;
                selectedFileType.value = category;
                currentPath.value = getCategoryName(category);
                
                // 当选择"全部文件"时，触发刷新获取文件列表
                if (category === 'all') {
                    emit('refresh');
                }
            };
            
            // 获取分类名称
            const getCategoryName = (category) => {
                const names = {
                    'all': '全部文件',
                    'recent': '最近',
                    'starred': '收藏',
                    'shared': '分享',
                    // 'trash': '回收站',
                    'image': '图片',
                    'video': '视频',
                    'audio': '音频',
                    'document': '文档',
                    'spreadsheet': '表格',
                    'presentation': '演示文稿',
                    'archive': '压缩包',
                    'code': '代码'
                };
                return names[category] || '全部文件';
            };

             
           


            
            // 处理上传
            const handleUpload = () => {
                emit('upload');
            };
            
            // 处理刷新
            const handleRefresh = () => {
                emit('refresh');
            };
            
            // 处理搜索
            const handleSearch = (keyword) => {
                emit('search', keyword);
            };
            
            // 处理新建文件夹
            const handleNewFolder = () => {
                emit('new-folder');
            };
            
            // 处理新建笔记
            const handleNewNote = () => {
                emit('new-note');
            };
            
            // 处理工具栏搜索
            const handleToolbarSearch = (keyword) => {
                emit('search', keyword);
            };
            
            // 处理创建文件夹
            const handleCreateFolder = () => {
                emit('create-folder');
            };

            // 处理加载更多
            const handleLoadMore = () => {
                
                console.log('DiskLayout: handleLoadMore 被调用，转发 load-more 事件');
                emit('load-more');
            };
            
            // 处理取消新建文件夹
            const handleCancelNewFolder = () => {
                emit('cancel-new-folder');
            };
            
            // 处理更新文件夹名称
            const handleUpdateFolderName = (value) => {
                emit('update:folder-name', value);
            };
            
            // 处理文件点击
            const handleFileClick = (file) => {
                // 如果是新建文件夹行，不处理
                if (file && file.isNewFolder) {
                    return;
                }
                
                selectedFile.value = file;
                
                // 自动展开文件详情面板
                if (file && !fileDetailsExpanded.value) {
                    fileDetailsExpanded.value = true;
                }
                
                emit('file-click', file);
            };
            
            // 处理文件下载
            const handleFileDownload = (file) => {
                emit('file-download', file);
            };
            
            // 处理文件预览
            const handleFilePreview = (file) => {
                emit('file-preview', file);
            };
            
            // 处理文件删除
            const handleFileDelete = (file) => {
                emit('file-delete', file);
            };
            
            // 处理选择变化
            const handleSelectionChange = (selectedIds) => {
                selectedFileIds.value = selectedIds;
                selectedFileCount.value = selectedIds.length;
                isSelectionMode.value = selectedIds.length > 0;
            };
            
            // 处理分享（单选模式，只分享第一个选中的文件）
            const handleShare = () => {
                if (selectedFileIds.value.length === 0) {
                    return;
                }
                // 获取第一个选中的文件ID
                const selectedFileId = selectedFileIds.value[0];
                // 从 displayedFiles 中查找对应的文件
                const selectedFile = displayedFiles.value.find(file => {
                    const fileId = file.id || file.pin_id || file.pinId || file.file_id || file._id || file.pinid || file.file_name || file.name;
                    return String(fileId) === String(selectedFileId);
                });
                
                if (selectedFile && fileListRef.value && typeof fileListRef.value.handleShareClick === 'function') {
                    // 直接调用 FileList 的 handleShareClick 方法
                    fileListRef.value.handleShareClick(selectedFile);
                }
            };
            
            // 处理下载选中文件（单选模式，只下载第一个选中的文件）
            const handleDownloadSelected = () => {
                if (selectedFileIds.value.length === 0) {
                    return;
                }
                // 获取第一个选中的文件ID
                const selectedFileId = selectedFileIds.value[0];
                // 从 displayedFiles 中查找对应的文件
                const selectedFile = displayedFiles.value.find(file => {
                    const fileId = file.id || file.pin_id || file.pinId || file.file_id || file._id || file.pinid || file.file_name || file.name;
                    return String(fileId) === String(selectedFileId);
                });
                
                if (selectedFile && fileListRef.value && typeof fileListRef.value.handleDownloadClick === 'function') {
                    // 直接调用 FileList 的 handleDownloadClick 方法
                    fileListRef.value.handleDownloadClick(selectedFile);
                }
            };
            
            // 处理更多操作
            const handleMoreActions = () => {
                // TODO: 实现更多操作功能
                console.log('更多操作');
            };
            
            // 处理取消选择
            const handleCancelSelection = () => {
                selectedFileCount.value = 0;
                isSelectionMode.value = false;
                // 触发清除选择
                clearSelectionTrigger.value += 1;
            };
            
            return {
                selectedCategory,
                selectedFileType,
                sortBy,
                viewMode,
                currentPath,
                selectedFile,
                fileDetailsExpanded,
                displayedFiles,
                currentFullPath,
                isRootPath,
                hasMore,
                isLoadingMore,
                isMobile,
                currentTab,
                allMenuItems,
                toggleFileDetails,
                handleCategoryChange,
                handleTabChange,
                handleUpload,
                handleRefresh,
                handleSearch,
                handleNewFolder,
                handleNewNote,
                handleToolbarSearch,
                handleFileClick,
                handleFileDownload,
                handleFilePreview,
                handleFileDelete,
                handleCreateFolder,
                handleCancelNewFolder,
                handleUpdateFolderName,
                handleLoadMore,
                handleGoBack,
                handlePathClick,
                handleDetailsPathClick,
                selectedFileCount,
                isSelectionMode,
                handleSelectionChange,
                handleShare,
                handleDownloadSelected,
                handleMoreActions,
                handleCancelSelection,
                clearSelectionTrigger,
                fileListRef
            };
        }
    };
})();

