<template>
	<div class="padding-sm" v-loading="loading">
		<el-row :gutter="10">
			<el-col :span="7" :xs="24">
				<el-card shadow="never" :body-style="{ padding: '10px' }">
					<el-select v-model="queryParams.repositoryId" placeholder="请选择" @change="handleQuery">
						<el-option v-for="dict in wareHouseOptions" :key="dict.repositoryId" :label="dict.repositoryName"
							:value="dict.repositoryId"></el-option>
					</el-select>
					<el-scrollbar wrap-class="scrollbar-wrapper" style="height: calc(100vh - 135px);">
						<el-tree class="impa-tree"
						 :data="fileList"
						 node-key="id"
						 :default-expanded-keys="rowItem.keys"
						 :highlight-current="true"
						 :expand-on-click-node="false"
						 @nodeClick="nodeClick">
						 <!-- @node-contextmenu="rightClick" -->
							<template #default="{ node, data }">
								<span class="impa-tree-node">
									<div class="left">
										<div>
											<svg-icon :icon-class="fileTypeIcon(data.label)"/>
											<span class="margin-left-xs">{{ data.label.replace("/","") }}</span>
										</div>
									</div>
								</span>
							</template>
						</el-tree>
					</el-scrollbar>
				</el-card>
			</el-col>
			<el-col :span="15" :xs="21">
				<img :src="imageUrl" alt="">
				<!-- <div class="flex align-center"> -->
					<!-- <div><elIcon alt="返回上一层" style="font-size: 26px;"><Top/></elIcon></div> -->
				<!-- <el-card shadow="never" :body-style="{ padding: '10px' }">
					<el-breadcrumb separator=">">
						<el-breadcrumb-item v-for="(bitem, bindex) in breadcrumbLi" :key="bindex">
							<div class="pointer" @click="handleBreadcrumb(bitem)">{{ bitem.fileName }}</div>
						</el-breadcrumb-item>
					</el-breadcrumb>
				</el-card> -->
				<!-- </div> -->
				<div class="flex text-sm">
					<div class="flex-twice padding-sm">名称</div>
					<div class="flex-sub padding-sm">修改日期</div>
					<div class="flex-sub padding-sm">大小</div>
					<!-- <div class="flex-sub padding-sm" style="display: none;">类型</div> -->
				</div>
				<el-scrollbar wrap-class="scrollbar-wrapper" style="height: calc(100vh - 120px);">
					<ul v-if="fileDetailList.length">
						<li class="fileLi text-sm" 
							v-for="(item,index) in fileDetailList" :key="index"
							@dblclick="dbNext(item)" 
							@click="clickTab = item.fileId"
							@contextmenu.prevent="rightClick($event,item)"
							:class="clickTab == item.fileId?'active':''">
							<div class="flex-twice padding-sm"><svg-icon :icon-class="fileTypeIcon(item.fileName, item.fileType)"/><span class="margin-left-xs">{{ item.fileName }}</span></div>
							<div class="flex-sub padding-sm text-grey">{{ item.updateTime || item.createTime }}</div>
							<div class="flex-sub padding-sm text-grey">
								<span v-if="item.fileSize != null">{{ fomatNumber(Math.ceil(parseFloat(item.fileSize)/1024)) }}KB</span>
							</div>
							<!-- <div class="flex-sub padding-sm text-grey" style="display: none;">
								{{ item.fileType == 1?"文件夹":item.fileType }}
							</div> -->
						</li>
					</ul>
					<div v-else class="text-center padding text-sm text-grey">
						此文件夹为空
					</div>
				</el-scrollbar>
			</el-col>
			<el-col :span="2" :xs="3" @contextmenu.prevent="rightClick($event,rowItem)"></el-col>
		</el-row>
		<div style="position: absolute;" :style="{ top: topY+'',left: leftX+'',bottom: bottomY+'',right: rightX+'' }" v-if="rightMenu">
			<el-card shadow="never" :body-style="{ padding: '10px' }">
				<ul class="text-sm">
					<li class="padding-tb-xs pointer" @click="handleAdd" v-if="isFolder">新建文件夹</li>
					<li class="padding-tb-xs pointer" @click="uploadVisible = true" v-if="isFolder">上传文件</li>
					<li class="padding-tb-xs pointer" @click="handleDel" v-if="!isFolder">删除文件</li>
					<li class="padding-tb-xs pointer" @click="handleRecovery" v-if="!isFolder">回收文件</li>
					<li class="padding-tb-xs pointer" @click="handleRename" v-if="!isFolder">重命名</li>
					<li class="padding-tb-xs pointer" @click="handleDown" v-if="!isFolder">下载文件</li>
				</ul>
			</el-card>
		</div>
		<!-- 重命名 -->
		<el-dialog
		  title="文件重命名"
		  v-model="renameVisible"
		  width="30%">
			<el-form :model="rightItem" ref="renameRef" label-width="80px">
				<el-form-item label="文件名" prop="fileName">
					<el-input v-model="rightItem.fileName" placeholder="请输入文件名"/>
				</el-form-item>
				<el-form-item label="">
					<el-button @click="renameVisible = false">取 消</el-button>
					<el-button type="primary" @click="handleRenameComfirm">确 定</el-button>
				</el-form-item>
			</el-form>
		</el-dialog>
		<!-- 上传文件 -->
		<el-dialog
		  title="文件重命名"
		  v-model="renameVisible"
		  width="30%">
			<el-form :model="rightItem" ref="renameRef" label-width="80px">
				<el-form-item label="文件名" prop="fileName">
					<el-input v-model="rightItem.fileName" placeholder="请输入文件名"/>
				</el-form-item>
				<el-form-item label="">
					<el-button @click="renameVisible = false">取 消</el-button>
					<el-button type="primary" @click="handleRenameComfirm">确 定</el-button>
				</el-form-item>
			</el-form>
		</el-dialog>
		<!-- 新建文件夹 -->
		<el-dialog
		  title="新建文件夹"
		  v-model="addVisible"
		  width="30%">
			<el-form :model="folterForm" ref="addRef" label-width="80px">
				<el-form-item label="文件夹名" prop="fileName">
					<el-input v-model="folterForm.fileName" placeholder="请输入文件夹名"/>
				</el-form-item>
				<el-form-item label="文件目录" prop="filePath">
					<el-input v-model="folterForm.filePath" disabled/>
				</el-form-item>
				<el-form-item label="">
					<el-button @click="addVisible = false">取 消</el-button>
					<el-button type="primary" @click="handleAddComfirm">确 定</el-button>
				</el-form-item>
			</el-form>
		</el-dialog>
		<ImportSection :uploadOpen="uploadVisible" @cancel="uploadVisible = false"
			:data="{ rid: queryParams.repositoryId,pid: (rightItem.id || rightItem.fileId)}" 
			@success="uploadSuccess"/>
		<!-- <el-dialog v-model="preVisible" width="100%" height="60%"> -->
			<div ref="fileView"></div>
		<!-- </el-dialog> -->
	</div>
</template>

<script setup>
	import ImportSection from "@/components/ImportSection";
	import ImportData from "@/components/ImportData";
	import { 
		getFileList, 
		getFileById, 
		downLoadFile ,
		recycleFile,
		delFile,
		editFile,
		addFolder,
		prevFile,
		guid
	} from "@/api/fileHouse";
	import { listWareHouse, treeWareHouse } from "@/api/wareHouse";
	import fileIcon from "@/assets/images/fileIcon2.png";
	import { useWindowSize } from "@vueuse/core";
	// let docx = await import("docx-preview");
	import { renderAsync } from "docx-preview";
	const { width, height } = useWindowSize();
	const { proxy } = getCurrentInstance();
	const { sys_file_type} = proxy.useDict("sys_file_type");
	const route = useRoute();
	const loading = ref(false);
	const wareHouseOptions = ref([]);
	const fileList = ref([]);
	const fileDetailList = ref([]);
	const clickTab = ref(null);
	const rowItem = ref({});
	const breadcrumbLi = ref([]);
	const topY = ref(0);
	const leftX = ref(0);
	const bottomY = ref(0);
	const rightX = ref(0);
	const rightMenu = ref(false);
	const rightItem = ref({});
	const isFolder = ref(false);
	const renameVisible = ref(false);
	const addVisible = ref(false);
	const preVisible = ref(false);
	const uploadVisible = ref(false);
	const imageUrl = ref("");
	
	const data = reactive({
		queryParams: {
			repositoryId: undefined
		},
		folterForm: {}
	});
	const { queryParams, folterForm } = toRefs(data);
	const getTreeFile = function(chag){
		treeWareHouse(queryParams.value).then((response) => {
			fileList.value = response;
			if(response.length){
				getFileDetail(rowItem.value.fileId?rowItem.value:response[0],chag)
			}
		});
	};
	(() => {
		const repositoryId = (route.params && route.params.repositoryId) | (route.query && route.query.repositoryId);
		if (repositoryId) {
			// loading.value = true;
			queryParams.value.repositoryId = repositoryId;
			getTreeFile()
		}
	})()
	watch(rightMenu, (value) => {
		if (value) {
			document.body.addEventListener('click', closeMenu)
		} else {
			document.body.removeEventListener('click', closeMenu)
		}
	});
	
	function closeMenu() {
		rightMenu.value = false
	}
	// 根据文件名获取图标
	function fileTypeIcon(name, dleg){
		let _name = (name.indexOf("/") != -1);
		if(_name || dleg == 1){
			return "filefolder"
		}else{
			if(name.indexOf(".") != -1){
				let _names = name.split(".");
				let _obj = sys_file_type.value.filter(item => item.value.indexOf(_names[_names.length - 1]) != -1)
				return (_obj.length?_obj[0].label:"filewj")
			}else{
				return "filewj"
			}
		}
	}
	// 获取文件夹下的列表
	const getFileDetail = function(row, edit){
		if(((row.fileId || row.id) != rowItem.value.fileId) || edit){
			rowItem.value = {
				fileId: (row.fileId || row.id),
				fileName: (row.fileName || row.label),
				keys: [(row.fileId || row.id)]
			};
			clickTab.value = null;
			getFileList({
				repositoryId: queryParams.value.repositoryId,
				parentId: rowItem.value.fileId,
				pageSize: 999,
				pageNum: 1
			}).then((response) => {
				fileDetailList.value = response.rows;
				loading.value = false;
			});
			// let _ind = breadcrumbLi.value.findIndex(item => { return item.fileId == (row.fileId || row.id); })
			// let _obj = breadcrumbLi.value;
			// if(_ind == -1){
			// 	_obj.push({
			// 		repositoryId: queryParams.value.repositoryId,
			// 		fileId: (row.fileId || row.id),
			// 	});
			// 		// fileName: row.fileName
			// }else{
			// 	_obj = _obj.slice(0, parseInt(_ind)+1)
			// }
			// breadcrumbLi.value = _obj;
		}
	}
	// 点击面包屑列表
	const handleBreadcrumb = function(row){
		getFileDetail(row)
	}
	// 点击树形列表
	const nodeClick = function(data, nosde, esl){
		if(rightMenu.value){
			rightMenu.value = false;
		} 
		if(data.label.indexOf("/") != -1){
			getFileDetail(data);
		}
	}
	// 双击事件
	const dbNext = function(row){
		if(row.fileType == 1){
			getFileDetail(row)
		}else{
			prevFile(row).then(response => {
				// jpg、jpeg、png、gif
				let _names = name.split(".");
				let _type = _names[_names.length - 1];
				if(1 == 1){
					preVisible.value = true
					renderAsync(response.data, proxy.$refs.fileView)
				}else if(1 == 0){
					let bold = new Blob([response.data], { type: 'image/'+_type });
					imageUrl.value = URL.createObjectURL(bold);
				}else{
					let reader = new FileReader();
					imageUrl.value = reader.readAsText(response.data);
				}
				
			})
		}
	}
	// 右键显示菜单
	const rightClick = function(nosde, data, esl){
		let _y = (parseFloat(nosde.pageY) + 20), _x = (parseFloat(nosde.pageX) + 20)
		topY.value = _y>(parseFloat(height.value) - 165)?'auto':_y+'px';
		leftX.value = _x>(parseFloat(width.value) - 80)?'auto':_x+'px';
		bottomY.value = _y>(parseFloat(height.value) - 165)?(parseFloat(height.value) - _y + 50)+'px':'auto';
		rightX.value = _x>(parseFloat(width.value) - 80)?(parseFloat(width.value) - _x)+'px':'auto';
		rightMenu.value = true;
		clickTab.value = data.fileId;
		rightItem.value = JSON.parse(JSON.stringify(data));
		if(data.id){
			if(data.label.indexOf("/") != -1){
				isFolder.value = true;
			}else{
				isFolder.value = false;
			}
		}else{
			isFolder.value = false;
		}
	}
	// 新建文件夹
	const handleAdd = function(){
		getFileById(rightItem.value.id).then(response => {
			folterForm.value = {
				"fileName": "",
				"filePath": response.data.filePath,
				"parentId": response.data.fileId,
				"repositoryId": response.data.repositoryId
			};
			addVisible.value = true;
			proxy.resetForm("dialRef");
		})
	}
	// 新建文件夹确定按钮
	function handleAddComfirm(){
		if(!folterForm.value.fileName.length){
			return;
		}
		addFolder(folterForm.value).then(response => {
			addVisible.value = false;
			getTreeFile(true)
		})
	}
	// 上传成功
	const uploadSuccess = function(val,key){
		console.log(val,key)
		uploadVisible.value = false;
		// getTreeFile(true)
	}
	// 删除
	const handleDel = function(row){
		proxy.$modal
			.confirm('是否确认将文件'+rightItem.value.fileName+'彻底删除？')
			.then(function() {
				return delFile(rightItem.value.fileId);
			})
			.then(() => {
				clickTab.value = null;
				rightItem.value = null;
				getTreeFile(true)
				proxy.$modal.msgSuccess("操作成功");
			})
			.catch(() => {});
		
	}
	// 回收文件
	const handleRecovery = function(row){
		proxy.$modal
			.confirm('是否确认将文件'+rightItem.value.fileName+'回收到垃圾桶？')
			.then(function() {
				return recycleFile(rightItem.value.fileId);
			})
			.then(() => {
				clickTab.value = null;
				rightItem.value = null;
				getTreeFile(true)
				proxy.$modal.msgSuccess("操作成功");
			})
			.catch(() => {});
	}
	const handleRename = function(){
		if(rightItem.value.id){
			getFileById(rightItem.value.id).then(response => {
				rightItem.value = response.data;
				renameVisible.value = true;
				proxy.resetForm("renameRef");
			})
		}else{
			renameVisible.value = true;
			proxy.resetForm("renameRef");
		}
		
	}
	// 重命名确定按钮
	const handleRenameComfirm = function(){
		if(rightItem.value.fileName.length){
			editFile(rightItem.value).then(response => {
				renameVisible.value = false;
				getTreeFile(true);
			})
		}
	}
	// 下载
	const handleDown = function(){
		if(rightItem.value.url != undefined){
			downLFile(rightItem.value);
		}else{
			getFileById(rightItem.value.fileId).then(response => {
				console.log(response)
			})
		}
	}
	const downLFile = function(val){
		downLoadFile(val)
	}
	const handleQuery = function(val){
		queryParams.value.repositoryId = val;
		clickTab.value = null;
		rowItem.value = {};
		rightItem.value = {};
		getTreeFile()
	}
	function getDetail(){
		
	}
	/** 查询用户列表 */
	function getList() {
		listWareHouse().then((res) => {
			wareHouseOptions.value = res.rows;
		});
	}
	getList();
</script>

<style lang="scss" scoped>
	.fileLi{
		display: flex;
		cursor: pointer;
		&:hover{
			background-color:rgba(85, 170,255, 0.1);
		}
		&.active{
			background-color:rgba(85, 170,255, 0.2);
			border: 1px solid rgba(85, 170,255, 1);
		}
	}
</style>
