<template>
	<view class="status-bar"></view>
	<view class="workspace-container page-container">

		<view class="workspace-header">
			<view class="custom-navbar">
				<view class="navbar-left" @click="handleBackOrCheck ">
					<view class="iconfont icon-fanhui custom-navbar-icon"></view>
					<view class="navbar-before-title workspace-text">{{isSelectFolder?'全选':navbarBeforeTitle}}</view>
				</view>

				<view class="navbar-title workspace-text">{{navbarTitle}}</view>
				<view class="navbar-right">
					<view v-if="isSelectFolder" class="navbar-right-text workspace-text" @click="handleSelectFolder()">
						完成</view>
					<view v-else class="iconfont icon-gengduo" :class="isMenuOpen ?'menu-open':'custom-navbar-icon'"
						@click="handleMenu"></view>
				</view>
				<view v-if="isMenuOpen" class="menu-card">
					<view class="menu-card-item" @click="handleSelectFolder();handleMenu()">选择</view>
					<view class="solid-line"></view>
					<view class="menu-card-item">新建文件夹</view>
				</view>
			</view>
			<view class="search-file-warpper">
				<view class="search-file">
					<view class="iconfont icon-sousuo"></view>
					<input class="search-file-input" placeholder="搜索" @focus="handleSearchFocus"
						v-model="searchKeyword" />
				</view>
				<view v-if="isSearchFocus" class="cancel-search" @click="handleSearchFocus">取消</view>
			</view>

		</view>
		<view class="workspace-content">
			<view class="folder-null" v-if="currentFolderList.length===0">
				<view class="iconfont icon-wenjianjia"></view>
				文件夹为空
			</view>
			<view class="folder-grid" v-if="currentFolderList.length>0">
				<view class="folder-item" :class="{'select-folder':selectFileList.includes(folder.id)}"
					v-for="folder in currentFolderList" :key="folder.id"
					@click="isSelectFolder?selectFolder(folder.id):handleFolderClick(folder)"
					@longpress="handleLongPress(folder)">
					<view class="iconfont icon-a-wenjianjiawenjian folder-item-style"></view>
					<view class="folder-name">{{folder.name}}</view>
					<view v-if="isSelectFolder" class="folder-checkbox"
						:class="{'select-folder':selectFileList.includes(folder.id)}">
						<uni-icons v-if="selectFileList.includes(folder.id)" type="checkmarkempty"
							color="#fff"></uni-icons>
					</view>
				</view>
			</view>
		</view>
		<view v-if="isSelectFolder" class="workspace-footer" :class="{'folder-actions':selectFileList.length>0}">
			<view class="iconfont icon-shangchuan"></view>
			<view class="iconfont icon-fuzhi"></view>
			<view class="iconfont icon-wenjian"></view>
			<view class="iconfont icon-del"></view>
			<view class="iconfont icon-gengduo"></view>
		</view>
	</view>
</template>

<script setup>
	import {
		onMounted,
		ref
	} from 'vue';
	import {getWorkspaceId} from '@/utils/user-info.js'
	import {getWorkspaceList} from '@/utils/cloud-api.js'
	
	const workspaceId = ref('')
	const navbarBeforeTitle = ref('');
	const navbarTitle = ref('工作区');

	// 选择文件模式
	const isSelectFolder = ref(false);
	const selectFileList = ref([]);
	const handleSelectFolder = () => {
		if (isSelectFolder.value) {
			selectFileList.value = []
		}
		isSelectFolder.value = !isSelectFolder.value;
	}
	const selectFolder = (id) => {
		const index = selectFileList.value.indexOf(id);
		if (index !== -1) {
			selectFileList.value.splice(index, 1);
		} else {
			selectFileList.value.push(id);
		}
	}
	const handleLongPress = (folder) => {
		if (isSelectFolder.value) return;
		uni.showActionSheet({
			itemList:['重命名','删除','下载','压缩'],
			success: (res) => {
				switch(res.tapIndex) {
					case 0:
					handleRename(folder);
					break;
					case 1:
					handleDelete(folder);
					break;
					case 2:
					handleDownload(folder);
					break;
					case 3:
					handleDownload(folder);
					break;
				}
			}
		})
	}
	
	// 重命名
	const handleRename = (folder) => {
	  uni.showModal({
	    title: '重命名',
	    content: '请输入新名称',
	    editable: true,
	    placeholderText: folder.name,
	    success: (res) => {
	      if (res.confirm && res.content) {
	        // 更新文件夹名称
	        updateFolderName(folder.id, res.content);
	      }
	    }
	  });
	};
	
	// 移动
	const handleDownload = (folder) => {
	  // 可以选择跳转到移动页面或显示选择器
	  uni.showToast({
	    title: '移动功能开发中',
	    icon: 'none'
	  });
	};
	
	// 删除
	const handleDelete = (folder) => {
	  uni.showModal({
	    title: '提示',
	    content: `确定要删除文件夹"${folder.name}"吗？`,
	    success: (res) => {
	      if (res.confirm) {
	        // deleteFolder(folder.id);
			console.log('确认删除文件夹');
	      }
	    }
	  });
	};

	// const handleFolderClick = (id) => {
	// 	console.log(id);
	// }

	// 菜单
	const isMenuOpen = ref(false)
	const handleMenu = () => {
		isMenuOpen.value = !isMenuOpen.value;
	}

	// 搜索框
	const searchKeyword = ref('')
	const isSearchFocus = ref(false)
	const handleSearchFocus = () => {
		isSearchFocus.value = !isSearchFocus.value
	}

	const allFoldersData = ref({
		// 根目录下的文件夹
		'root': [{
				id: 1,
				name: '文档资料',
				parentId: 'root',
				children: [{
						id: 11,
						name: '工作文档',
						parentId: 1,
						children: []
					},
					{
						id: 12,
						name: '学习笔记',
						parentId: 1,
						children: []
					},
					{
						id: 13,
						name: '合同模板',
						parentId: 1,
						children: []
					}
				]
			},
			{
				id: 2,
				name: '图片素材',
				parentId: 'root',
				children: [{
						id: 21,
						name: '风景图片',
						parentId: 2,
						children: []
					},
					{
						id: 22,
						name: '人物照片',
						parentId: 2,
						children: []
					},
					{
						id: 23,
						name: 'UI图标',
						parentId: 2,
						children: []
					}
				]
			},
			{
				id: 3,
				name: '视频文件',
				parentId: 'root',
				children: [{
						id: 31,
						name: '教程视频',
						parentId: 3,
						children: []
					},
					{
						id: 32,
						name: '会议录像',
						parentId: 3,
						children: []
					}
				]
			},
			{
				id: 4,
				name: '项目代码',
				parentId: 'root',
				children: [{
						id: 41,
						name: '前端项目',
						parentId: 4,
						children: []
					},
					{
						id: 42,
						name: '后端服务',
						parentId: 4,
						children: []
					}
				]
			},
			{
				id: 5,
				name: '安装包',
				parentId: 'root',
				children: []
			},
			{
				id: 6,
				name: '备份文件',
				parentId: 'root',
				children: []
			},
			{
				id: 7,
				name: '临时文件',
				parentId: 'root',
				children: []
			},
			{
				id: 8,
				name: '个人收藏',
				parentId: 'root',
				children: []
			}
		]
	});
	// 文件夹路径栈
	const folderStack = ref([]);
	// 当前显示的文件夹列表
	const currentFolderList = ref([]);

	const getCurrentFolderList = () => {
		const currentPath = folderStack.value.length > 0 ? folderStack.value[folderStack.value.length - 1].id : 'root';
		if (currentPath === "root") {
			return allFoldersData.value['root'] || [];
		}
		const findFolderById = (folders, id) => {
			for (const folder of folders) {
				if (folder.id === id) return folder;
				if (folder.children && folder.children.length > 0) {
					const found = findFolderById(folder.children, id);
					if (found) return found;
				}
			}
			return null;

		};
		const currentFolder = findFolderById(allFoldersData.value['root'], currentPath);
		return currentFolder ? currentFolder.children : [];
	}

	// 初始化当前文件夹列表
	const initCurrentFolderList = () => {
		workspaceId.value = getWorkspaceId();
		console.log("getWorkspaceId:",workspaceId.value);
		currentFolderList.value = getCurrentFolderList();
	};

	// 处理文件夹点击（非选择模式下进入文件夹）
	const handleFolderClick = (folder) => {
		folderStack.value.push({
			id: folder.id,
			name: folder.name
		});
		navbarTitle.value = folder.name;
		navbarBeforeTitle.value = folderStack.value.length > 1 ? folderStack.value[folderStack.value.length - 2].name :
			'工作区';
		initCurrentFolderList();
		searchKeyword.value = '';
		isSearchFocus.value = false;
	};

	// 全选/取消全选
	const handleSelectAll = () => {
		if (selectFileList.value.length === currentFolderList.value.length) {
			selectFileList.value = [];
		} else {
			selectFileList.value = currentFolderList.value.map(f => f.id);
		}
	};

	// 返回上一级
	const handleBackOrCheck = () => {
		if (isSelectFolder.value) {
			// 选择模式下点击全选/取消全选
			handleSelectAll();
			return;
		}

		if (folderStack.value.length > 0) {
			folderStack.value.pop();
			if (folderStack.value.length === 0) {
				navbarTitle.value = '工作区';
				navbarBeforeTitle.value = null;
			} else {
				navbarTitle.value = folderStack.value[folderStack.value.length - 1].name;
				navbarBeforeTitle.value = folderStack.value.length > 1 ?
					folderStack.value[folderStack.value.length - 2].name :
					'工作区';
			}
			initCurrentFolderList();
			// 返回后清空搜索
			searchKeyword.value = '';
			isSearchFocus.value = false;
		} else {
			// 已在根目录，返回到聊天界面
			uni.navigateBack({
				delta: 1,
				fail() {
					console.log("返回失败，进入兜底跳转")
					uni.reLaunch({
						url: '/pages/Chat/Chat'
					})
				}
			})
		}
	};

	onMounted(() => {
		initCurrentFolderList();
	})
</script>

<style scoped>
	@import url("WorkSpace.css");
</style>