<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"
						 draggable
						 :default-expanded-keys="rowItem.keys"
						 :highlight-current="true"
						 :expand-on-click-node="false"
						 @nodeClick="nodeClick"
						 @node-drop="handleDrop">
							<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">
				<div class="flex align-center">
					<!-- <div><elIcon alt="返回上一层" style="font-size: 26px;"><Top/></elIcon></div> -->
					<el-card shadow="never" :body-style="{ padding: '10px' }" style="width: 100%">
						<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 padding-tb-sm">
					<div class="flex-twice padding-lr-sm">名称</div>
					<div class="flex-sub padding-lr-sm" style="border-left: 1px solid #ccc;border-right: 1px solid #ccc;">修改日期</div>
					<div class="flex-sub padding-lr-sm">大小</div>
				</div>
				<el-scrollbar wrap-class="scrollbar-wrapper" 
					@contextmenu.prevent="rightClick($event,rowItem,true)"
					@dragover.prevent="handleDragOver"
					@drop.prevent="handleDropEnd"
					style="height: calc(100vh - 150px);padding-bottom: 30px;">
					<ul v-if="fileDetailList.length">
						<li class="fileLi text-sm" 
							v-for="(item,index) in fileDetailList" :key="index"
							@dblclick.stop="dbNext(item)" 
							@click.stop="oneClick(item)"
							@contextmenu.prevent.stop="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>
						</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,true)"
				@dragover.prevent="handleDragOver"
				@drop.prevent="handleDropEnd">
			</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="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>
		<!-- 上传文件确定按钮 -->
		<el-dialog
		  title="文件上传"
		  v-model="uploadVis"
		  width="30%">
			<el-form label-width="80px">
				<el-form-item label="文件：" prop="fileName">
					<div class="el-input__wrapper" style="justify-content: start;">
						<span v-if="scheduleList.length>1">{{scheduleList[0].file.name}}等{{scheduleList.length}}个文件</span>
						<span v-else>{{scheduleList[0].file.name}}</span>
					</div>
					<!-- <el-input disabled placeholder="请输入文件夹名"/> -->
				</el-form-item>
				<el-form-item label="上传至：" prop="filePath">
					<el-input v-model="rowItem.fileName"/>
				</el-form-item>
				<el-form-item label="">
					<el-button type="primary" @click="submitUpload">确 定</el-button>
				</el-form-item>
			</el-form>
		</el-dialog>
		<ImportSection :uploadOpen="uploadVisible" @cancel="uploadVisible = false"
			@success="submitFile"/>
		<ul class="el-upload-list" style="padding: 0;" v-if="scheduleVisble">
			<div class="padding-sm text-sm clearfix bg-theme">
				<span class="upload-list-title">文件上传(共{{scheduleList.length}}个)</span>
				<span class="reuploadAllBtn" onclick="reuploadFailDocs()" style="display:none">全部重传 </span>
				<div style="float: right" class="pointer"><elIcon @click="handleClose"><Close/></elIcon></div>	
			</div>
			<div class="uploadedFileList padding-sm" style="max-height: 200px;overflow-y: auto;">
				<li class="flex justify-between padding-xs text-sm" v-for="(item,index) in scheduleList" :key="index">
					<div>
						<svg-icon icon-class="filewj"/>
						<span class="uploadFileName">{{item.file.name}}</span>
					</div>
					<span>{{item.percentage}}%</span>
				</li>
			</div>
		</ul>
		<el-dialog
		  :title="imgSrc.name"
		  top="20px"
		  v-model="imgVisible"
		  width="80%">
			<img v-if="imgSrc.type == 'image'" :src="imgSrc.url" style="width:100%;" alt="">
			<video style="width: 100%;" autoplay controls v-if="imgSrc.type == 'video'" :src="imgSrc.url"></video>
			<audio style="width: 100%;" autoplay controls v-if="imgSrc.type == 'audio'" :src="imgSrc.url"></audio>
		</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,
		uploadFile,
		guid,
		transformPdf
	} 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 imgSrc = ref({});
	const imgVisible = ref(false);
	
	const scheduleList = ref([]);
	const scheduleVisble = ref(false);
	const uploadVis = ref(false);
	
	const data = reactive({
		queryParams: {
			repositoryId: undefined
		},
		folterForm: {}
	});
	const { queryParams, folterForm } = toRefs(data);
	const getTreeFile = function(chag){
		treeWareHouse(queryParams.value).then((response) => {
			fileList.value = response;
			loading.value = false;
			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)
		}
	});
	window.addEventListener('keydown', (event) => {
	    if (event.key === 'Delete'&&rightItem.value.fileId) {
	        handleDel("Deletekeydown");
	    }
	});
	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),
				filePath: (row.filePath || ""),
				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;
				getBreadcrumb(row, response.rows[0]);
			});
			// 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 getBreadcrumb = function(_row, _data){
		let _ids = (_data || _row).ancestors.split(",").slice(1);
		let _paths = (_data || _row).filePath.split("/").slice(1);
		let _obj = [];
		if(_data){
			
		}else{
			_ids.push(_row.fileId);
		}
		for(let i=0;i<_ids.length;i++){
			_obj.push({
				fileName: _paths[i],
				fileId: _ids[i]
			});
		}
		breadcrumbLi.value = _obj;
	}
	// 点击面包屑列表
	const handleBreadcrumb = function(row){
		getFileDetail(row)
	}
	// 树形拖拽事件
	const handleDrop = function(draggingNode, dropNode, dropType, ev) {
		console.log('tree drop: ', draggingNode, dropNode, dropType, ev);
	}
	// 点击树形列表
	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{
			let _names = row.fileName.split(".");
			let _type = _names[_names.length - 1];
			let _obj = sys_file_type.value.filter(item => item.value.indexOf(_type) != -1);
			if(_obj.length){
				row.fileType = _obj[0].elCssType;
				if(_obj[0].elCssType == "pdf"){
					transformPdf(row);
				}else if(_obj[0].elCssType){
					let _smj = _obj[0].elCssType;
					prevFile(row).then(response => {
						if(_smj == "text"){
							preVisible.value = true
							renderAsync(response.data, proxy.$refs.fileView)
						}else if(_smj == "image" || _smj == "video"||_smj == "audio"){
							let bold = new Blob([response.data], { type: _smj+'/'+_type });
							imgSrc.value = {
								url: URL.createObjectURL(bold),
								name: row.fileName,
								type: _smj
							};
							imgVisible.value = true;
						}else{
							let reader = new FileReader();
							imageUrl.value = reader.readAsText(response.data);
						}
						
					})
				}
			}
			
		}
	}
	// 单击事件
	const oneClick = function(row){
		clickTab.value = row.fileId;
		rightItem.value = JSON.parse(JSON.stringify(row));
	}
	// 右键显示菜单
	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;
		if(esl){
			isFolder.value = true;
		}else{
			isFolder.value = false;
		}
		// clickTab.value = data.fileId;
		rightItem.value = JSON.parse(JSON.stringify(data));
	}
	// 新建文件夹
	const handleAdd = function(){
		// getFileById(rightItem.value.id).then(response => {
		folterForm.value = {
			"fileName": "",
			"filePath": rowItem.value.filePath,
			"parentId": rowItem.value.fileId,
			"repositoryId": queryParams.value.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 handleDel = function(row){
		proxy.$modal
			.confirm('是否确认将文件'+rightItem.value.fileName+'彻底删除？')
			.then(function() {
				return delFile(rightItem.value.fileId);
			})
			.then(() => {
				getTreeFile(true);
				clickTab.value = null;
				rightItem.value = {};
				proxy.$modal.msgSuccess("操作成功");
			})
			.catch(() => {});
		
	}
	// 回收文件
	const handleRecovery = function(row){
		proxy.$modal
			.confirm('是否确认将文件'+rightItem.value.fileName+'回收到垃圾桶？')
			.then(function() {
				return recycleFile(rightItem.value.fileId);
			})
			.then(() => {
				getTreeFile(true)
				clickTab.value = null;
				rightItem.value = {};
				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){
			downLoadFile(rightItem.value);
		}
	}
	const handleDragOver = function(event) {
	    // 可以添加一些视觉反馈
	};
	// 拖拽新增上传
	const handleDropEnd = function(event) {
		const files = event.dataTransfer.files;
		if (files.length > 0) {
			submitFile(Object.values(files));
		}
	}
	// 关闭上传列表
	const handleClose = function(){
		scheduleVisble.value = false;
		scheduleList.value = [];
	}
	// 循环上传文件
	const saveFilechunk = function(){
		axiosData(0, 0);
	}
	function axiosData(_fi, _sj){
		if(_fi<scheduleList.value.length){
			let _item = scheduleList.value[_fi];
			let _chunk = scheduleList.value[_fi].chunkList;
			if(_sj<_chunk.length){
				let formData = new FormData()
				formData.append('name', _item.file.name);
				formData.append('index', _sj);
				formData.append('uid', _item.file.uuids);
				formData.append('chunksLength', _chunk.length);
				formData.append('chunk', _chunk[_sj]);
				formData.append('parentId', rowItem.value.fileId);
				formData.append('repalce', false);
				formData.append('repositoryId', queryParams.value.repositoryId);
				uploadFile(formData).then(response => {
					if(response.code == 200){
						_item.percentage = Math.floor(((_sj + 1)/ _chunk.length)* 100);
						axiosData(_fi, _sj+1);
					}
				});
			}else{
				axiosData(_fi+1, 0);
			}
		}else{
			getTreeFile(true)
		}
	}
	function chunkPush(fileRaw){
		const chunksize = 3*1024*1024;
		let _chunkList = [];
		let page = Math.ceil(parseFloat(fileRaw.size)/chunksize);
		for(let i=0;i<page;i++){
			_chunkList.push(fileRaw.slice(i* chunksize, (i+1) * chunksize));
		}
		return _chunkList;
	}
	// 循环将文件切片
	const submitFile = function(list) {
		uploadVisible.value = false;
		let _Arr = [];
		list.forEach((item,index) => {
			let fileRaw = item.raw || item;
			fileRaw.uuids = guid();
			_Arr.push({
				chunkList: chunkPush(fileRaw),
				file: fileRaw,
				percentage: 0
			})
		})
		scheduleList.value = _Arr;
		uploadVis.value = true;
	}
	const submitUpload = function(list) {
		uploadVis.value = false;
		scheduleVisble.value = true;
		saveFilechunk();
	}
	const handleQuery = function(val){
		loading.value = true;
		queryParams.value.repositoryId = val;
		clickTab.value = null;
		rowItem.value = {};
		rightItem.value = {};
		getTreeFile()
	}
	function getDetail(){
		
	}
	/** 查询用户列表 */
	function getList() {
		listWareHouse({
			pageNum: 1,
			pageSize: 999
		}).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);
		}
	}
	.el-upload-list {
	    position: fixed;
	    bottom: 0;
	    right: 0;
	    z-index: 999;
	    width: 25%;
	    min-width: 320px;
	    margin: 5px;
	    padding: 10px 15px;
	    background: white;
	    border: 1px solid #e3e3e3;
	    border-radius: 5px;
	    list-style: none;
	}
</style>
