<template>
	<div class="syllabus-tree-main">
		<vuescroll>
			<el-tree :data="treeDatas" :props="defaultProps" :allow-drop="allowDrop" class="tree" node-key="id"
				default-expand-all highlight-current @node-drop="handleDrop" @node-click="onNodeClick"
				:draggable="Boolean(editable)" :expand-on-click-node="false" ref="tree">
				<span class="custom-tree-node" slot-scope="{ node, data }">
					<span class="tree-node-lable">
						{{data.title}}
						<!-- {{data.id}} -->
						<Icon type="md-cube" color="#70B1E7" :title="$t('syllabus.tree.hasResource')" v-if="data.rnodes && data.rnodes.length" />
						<Icon type="md-git-compare" color="#70B1E7" :title="$t('syllabus.tree.hasCoEdit')" v-if="hasEditAuth(data) && isSchool" />
						<Tooltip  placement="right" transfer  theme="light" max-width="none">
							<Icon type="md-information-circle" color="#b9b9b9" size="18" v-if="hasEditAuth(data) && isSchool"/>
							<div slot="content" style="font-size: 12px;">
								<p>{{ $t('syllabus.latestId') }}：{{ data.creatorName || '' }}</p>
								<p>{{ $t('syllabus.latestTime') }}：{{ $tools.formatTime(data.updateTime) }}</p>
							</div>
						</Tooltip>
					</span>
					<span class="custom-tree-tools" v-if="inShareView && isFirstLevel(data)">
						<Icon type="md-copy" style="margin-right: 5px;" size="16" />
						<span style="color: #9f9f9f;font-size: 12px;margin-right: 20px;" @click="onCopyChapter(data)">复制该章节</span>
						<Icon type="ios-remove-circle-outline" style="margin-right: 5px;" size="16" />
						<span style="color: #9f9f9f;font-size: 12px;margin-right: 20px;"  @click="onIgnoreShare(data)">忽略该章节</span>
					</span>
					<span class="custom-tree-tools" v-if="((hasEditAuth(data) || $access.can('admin.*|Syllabus_Edit')) && !inShareView) && !inSchoolAbility">
						<Icon type="md-create" size="16" :title="$t('syllabus.tree.edit')" @click="onEditItem(node,data,$event)" />
						<Icon type="md-add" size="16" :title="$t('syllabus.tree.add')" @click="onAddNode(node,data,$event)" />
						<Icon type="md-trash" size="16" :title="$t('syllabus.tree.remove')" @click="remove(node,data)" v-if="!isFirstLevel(data) ||  (canDeleteChapter && isFirstLevel(data))"/>
						<Icon type="md-share" v-if="isFirstLevel(data) && canDeleteChapter" :title="isSchool ? $t('syllabus.tree.coEdit') : $t('syllabus.tree.share')"
							@click="doShare(data)" />
					</span>
				</span>
			</el-tree>
		</vuescroll>

		<!-- 新增或者编辑弹窗 -->
		<Modal v-model="isEditOrAdd" width="500" footer-hide class="tree-modal">
			<div class="modal-header" slot="header">{{ isEditItem ? $t('syllabus.tree.editTitle'):$t('syllabus.tree.addTitle')}}</div>
			<div class="modal-content">
				<p class="node-title">{{ $t('syllabus.tree.parent') }}</p>
				<Input v-model="nodeInfo.parent" style="width: 100%" disabled />
				<p class="node-title">{{ $t('syllabus.tree.nodeName') }}</p>
				<Input v-model="nodeInfo.title" :placeholder="$t('syllabus.tree.place1')" style="width: 100%" />
			</div>
			<Button @click="onSubmitNode" class="modal-btn"
				style="width: 88%;margin-left: 6%;margin-bottom: 20px;">{{ $t('syllabus.tree.confirm') }}</Button>
		</Modal>
		
		<!-- 新增或者编辑弹窗 -->
		<Modal v-model="chapterCopyModal" width="500" footer-hide class="tree-modal add-volume-modal choose-content-modal">
			<div class="modal-header" slot="header">{{ $t('syllabus.tree.copyNode') }}</div>
			<div class="modal-content">
				<p class="node-title">{{ $t('syllabus.tree.curChapter') }}: <span class="node-name">{{ curChapter.title }}</span></p>
				<p class="node-title" style="display: inline-block;">{{ $t('syllabus.tree.targetV') }}:</p>
				<Select v-model="copyTargetVolume" style="width: 300px;">
					<Option v-for="(item,index) in volumeList" :value="index" :key="index">{{item.name}}</Option>
				</Select>
			</div>
			<Button @click="doCopyChapter" :loading="isCopyBtnLoading" class="modal-btn"
				style="width: 88%;margin-left: 6%;margin-bottom: 20px;">{{ $t('syllabus.tree.confirm') }}</Button>
		</Modal>
	</div>
</template>

<script>
	import '@/utils/Math.uuid'
	import BlobTool from '@/utils/blobTool.js'
	export default {
		props: ['volume', 'treeData', 'editable'],
		data() {
			return {
				isFalse: false,
				treeDatas: [],
				questionList: [],
				fileList: [],
				defaultProps: {
					children: 'children',
					label: 'title'
				},
				isEditOrAdd: false,
				isLoading: false,
				isCopyBtnLoading:false,
				isRelatedContent: false,
				isShowContent: false,
				chapterCopyModal:false,
				isEditItem: false,
				copyTargetVolume:0,
				contentIndex: '1',
				currentVolume: null,
				currentEditData: null,
				currentParentData: null,
				currentResources: [],
				currentItems: [],
				curNode: null,
				curData:null,
				curChapter:{
					id: null,
					title: '',
				},
				nodeInfo: {
					id: null,
					title: '',
					expand: true,
					editable: true,
					version: '',
					type: '1',
					children: [],
					creatorId: this.curTeammodelId,
					creatorName: this.curName,
					remark: '',
					nodeKey: '',
					pid: '',
					code: '',
					status: 1,
					parent: '',
					rnodes:[]
				},
				isSchool: false,
				flatArr:[],
				flatRNodes:[],
				highlightId:null
			}
		},
		created() {
			this.isSchool = this.$route.name === 'syllabus'
			console.log('xxxx');
		},
		methods: {
			onNodeClick(data, node) {
				console.log(data)
				this.curNode = node
				this.curData = data
				sessionStorage.setItem('highlightId',data.id)
				this.$emit('onNodeClick', {
					data:data,
					node:node
				})
			},
			doShare(data) {
				this.$emit('doShare', data)
			},
			/* 禁止一级节点往下级进行拖拽 */
			allowDrop(draggingNode, dropNode, dropType) {
				if(dropNode.level === 3){
					return dropType === 'prev' || dropType === 'after'
				}else if (draggingNode.level === dropNode.level) {
					if(draggingNode.level === 1){
						return dropType === 'prev' || dropType === 'after'
					}else{
						return dropType === 'prev' || dropType === 'after' ||  dropType === 'inner'
					}
				} else {
					// 如果是二三级拖到其他级别 则正常拖拽 但是不能拖到第一级
					if(draggingNode.level !== 1 && dropNode.level !== 1){
						return dropType === 'prev' || dropType === 'after' ||  dropType === 'inner'
					}
					
				}
			},
			// 拖拽完成回调
			handleDrop(draggingNode, dropNode, dropType) {
				this.$emit('addModifyId',this.getChapterIdById(draggingNode.data.id))
				this.$emit('addModifyId',this.getChapterIdById(dropNode.data.id))
				switch (dropType) {
					case 'before':
						draggingNode.data.pid = dropNode.data.pid
						break
					case 'inner':
						draggingNode.data.pid = dropNode.data.id
						break
					case 'after':
						draggingNode.data.pid = dropNode.data.pid
						break
					default:
						break
				}
				this.$parent.hasModify = true

			},
			/* 忽略某个章节的分享 */
			onIgnoreShare(data){
				this.$Modal.confirm({
					title: this.$t('syllabus.tree.removeTitle'),
					content: this.$t('syllabus.tree.ignoreTip'),
					onOk: () => {
						this.$api.syllabus.ShareAgree({
							"code": this.curTeammodelId,
							"ids": [data.id],
							"type": "share",
							"opt": "ignore"
						}).then(res => {
							if(res.status === 200){
								this.$Message.success(this.$t('syllabus.doSuc'))
								this.$parent.getShareVolumeList(true)
							}
						})
					}
				})
			},
			/* 复制章节到课纲 */
			onCopyChapter(data){
				if(this.volumeList.length){
					this.curChapter = data
					this.chapterCopyModal = true
				}else{
					this.$Message.warning(this.$t('syllabus.tree.noVTip'))
				}
			},
			/* 复制章节的业务逻辑 */
			async doCopyChapter(){
				let targetVolume = this.volumeList[this.copyTargetVolume]
				let allRNodes = this.getAllRNodes(JSON.parse(JSON.stringify(this.curChapter)))
				let hasItemOrPaper = allRNodes.filter(i => i.type === 'item' || i.type === 'paper').length > 0
				this.flatRNodes = allRNodes
				this.isCopyBtnLoading = true
				this.curChapter.auth = []
				this.curChapter.pid = targetVolume.id
				// 在复制章节过程中 如果章节节点以及子节点有关联试题试卷 则需要询问用户是否进行入库操作
				if(hasItemOrPaper){
					this.$Modal.confirm({
						title: this.$t('syllabus.tip'),
						content: this.$t('syllabus.tree.hasItemTip'),
						okText: this.$t('syllabus.tree.okText'),
						cancelText: this.$t('syllabus.tree.cancelText'),
						onOk: async () => {
							let copyResult = await this.doCopyResources(allRNodes,true)
							console.log('复制后的回调',copyResult)
							this.sendCopyApi(targetVolume)
						},
						onCancel: async () => {
							let copyResult = await this.doCopyResources(allRNodes,false)
							console.log('复制后的回调',copyResult)
							this.sendCopyApi(targetVolume)
						}
					})
				}else{
					let copyResult = await this.doCopyResources(allRNodes,false)
					this.sendCopyApi(targetVolume)
				}
			},
			/* 发送复制章节到个人课纲的请求API */
			sendCopyApi(targetVolume){
				console.log(JSON.stringify(this.flatRNodes))
				let newChapterId = this.$tools.guid()
				console.log(newChapterId)
				let upsertParams = [{
					id: newChapterId,
					codeval: this.curCode,
					volumeId: targetVolume.id,
					scope: targetVolume.scope,
					trees: [this.refreshCopyChapter(this.curChapter,targetVolume.id,newChapterId)]
				}]
				this.$api.syllabus.UpsertTree(upsertParams).then((res) => {
					if (!res.error && res) {
						this.$Message.success(this.$t('syllabus.tree.copySuc'));
						this.chapterCopyModal = false
					} else {
						this.$Message.error(this.$t('syllabus.saveFailTip'));
					}
				}).catch(e => {
					this.$Message.error(e);
				}).finally(() => {
					this.isCopyBtnLoading = false
				})
			},
			/* 将复制的节点内的创建信息、code等更新为当前用户 */
			refreshCopyChapter(chapterNode,newVolumeId,newChapterId){
				console.log(this.flatRNodes);
				let myId = this.curTeammodelId
				let myName = this.curName
				let newId = newChapterId
				chapterNode.pid = newVolumeId
				chapterNode.id = newId
				const fn = (source)=>{
					source.creatorId = myId
					source.creatorName = myName
					if(source.rnodes.length){
						source.rnodes.forEach(i => {
							i.cntr = myId
							i.code = i.code.split('-').length > 1 ? i.code.split('-')[0] + '-' + myId : myId
							i.link = this.flatRNodes.find(j => j.id === i.id).link
						})
					}
					if(source.children.length){
						source.creatorId = myId
						source.creatorName = myName
						source.children.forEach(i => {
							i.pid = source.id
							fn(i)
						})
					}
				}
				fn(chapterNode)
				return chapterNode
			},
			/* 复制节点到个人课纲 需要把关联的内容全部拷贝到个人的BLOB容器内 */
			doCopyResources(rnodes,needSave){
				return new Promise((r,j) => {
					let promiseArr = []
					let tmdId = this.curTeammodelId
					console.log(JSON.stringify(this.flatRNodes));
					rnodes.forEach((file,fileIndex) => {
						let copyFile = JSON.parse(JSON.stringify(file))
						if(copyFile.type === 'item'){
							promiseArr.push(this.copyItemToBlob(copyFile,needSave))
							// 如果不入库 则需要修改资源的link地址
							this.flatRNodes[fileIndex].link = (needSave ? '/item/' : '/syllabus/') + rnodes[fileIndex].id + '/' + rnodes[fileIndex].id + '.json'
							
						}else if(copyFile.type === 'paper'){
							promiseArr.push(this.copyPaperToBlob(copyFile,needSave))
							// 如果不入库 则需要修改资源的link地址
							if(!needSave){
								this.flatRNodes[fileIndex].link = rnodes[fileIndex].link.replace('paper/','syllabus/')
							}else{
								this.flatRNodes[fileIndex].link = rnodes[fileIndex].link.replace('syllabus/','paper/')
							}
						}else{
							promiseArr.push(this.copyFileToBlob(copyFile))
						}
						this.flatRNodes[fileIndex].code = this.flatRNodes[fileIndex].code.includes('-') ? this.flatRNodes[fileIndex].code.split('-')[0] + '-' +  tmdId : tmdId
						this.flatRNodes[fileIndex].cntr = tmdId
					})
					Promise.all(promiseArr).then(result => {
						r(result)
						console.log(result)
					}).catch(err =>{
						j(err)
					})
				})
			},
			/* 根据醍摩豆ID获取对应BLOB个人容器授权信息 */
			getBlobPrivateSas(tmdId){
				return new Promise((r,j) => {
					this.$api.blob.blobSasR({
						name:tmdId,
						role:'teacher'
					}).then(res => {
						if(!res.error){
							r(res)
						}
					})
				})
			},
			/* 复制试题到当前用户BLOB */
			copyItemToBlob(resourceItem,needSave){
				console.log(resourceItem)
				// console.log(JSON.stringify(rnodes))
				return new Promise(async (r, j) => {
					let toPath = needSave ? `item/${resourceItem.id}/` : `syllabus/${resourceItem.id}/`
					// 是否入库 来决定保存的路径
					let fromPath = resourceItem.link.split('/')[1] + '/' + resourceItem.id
					// 试题的拥有者也就是复制的来源容器
					let myId = this.curTeammodelId
					let fileOwner = resourceItem.code.replace('Item-','')
					let privateSas = await this.getBlobPrivateSas(fileOwner)
					let privateBlobTool = new BlobTool(privateSas.url, privateSas.name, '?' + privateSas.sas,'private')
					// 拿到试题的完整数据 方便保存到COSMOS
					const itemJsonFile = await this.$evTools.getFullItemByTmdId(fileOwner, resourceItem.link)
					let file = new File([JSON.stringify(itemJsonFile)],resourceItem.id + ".json", {type: "",});
					console.log(itemJsonFile);
					// 先把对应试题目录下的全部复制到校本BLOB 然后再更新添加学段科目等字段后的题目Json文件
					this.$parent.containerClient.copyFolder(toPath,fromPath,privateBlobTool).then(async res => {
						try{
							itemJsonFile.blob = '/' + toPath + resourceItem.id + '.json'
							itemJsonFile.code = myId
							itemJsonFile.scope = resourceItem.scope
							this.$parent.saveExercise(itemJsonFile).then(result => {
								console.log(result)
								r(result)
							})
						}catch(e){
							j(e)
						}
					}).catch(err => {
						j(err)
					})
				})
			},
			/* 根据关联的试卷资源获取数据库的试卷信息 方便复制的入库问题 */
			getCosmosPaper(paperResourceItem){
				console.log(JSON.stringify(paperResourceItem))
				return new Promise((r,j) => {
					this.$api.learnActivity.FindExamPaper({
						id:paperResourceItem.id,
						code:paperResourceItem.code.replace('Paper-',''),
						scope:paperResourceItem.scope
					}).then(res => {
						if(!res.error && res.papers.length){
							r(res.papers[0])
						}
					}).catch(e => {
						j(e)
					})
				})
			},
			/* 保存复制的试卷到cosmos */
			async savePaperToCosmos(paperResourceItem){
				console.log(JSON.stringify(paperResourceItem))
				let cosmosPaper = await this.getCosmosPaper(paperResourceItem)
				cosmosPaper.code = this.curTeammodelId
				cosmosPaper.scope = 'pravite'
				return new Promise(async (r,j) => {
					let params = {
						paper: cosmosPaper,
						option: 'insert'
					}
					//  保存试卷到cosmos
					this.$api.learnActivity.SaveExamPaper(params).then(
						res => {
							if (res.error == null) {
								r(res)
							} else {
								r(res.error)
							}
						},
						err => {
							j(err)
						}
					)
				})
			},
			/* 复制试题到当前用户BLOB */
			copyPaperToBlob(resourceItem,needSave){
				return new Promise(async (r, j) => {
					let toPath = needSave ? `paper/${resourceItem.title}/` : `syllabus/${resourceItem.title}/`
					// 是否入库 来决定保存的路径
					let fromPath = `paper/${resourceItem.title}`
					// 试题的拥有者也就是复制的来源容器
					let myId = this.curTeammodelId
					let fileOwner = JSON.parse(JSON.stringify(resourceItem.code)).replace('Paper-','')
					let privateSas = await this.getBlobPrivateSas(fileOwner)
					let privateBlobTool = new BlobTool(privateSas.url, privateSas.name, '?' + privateSas.sas,'private')
					// 拿到试题的完整数据 方便保存到COSMOS
					const paperJsonFile = await this.$evTools.getFullPaperByTmdId(fileOwner, resourceItem.link)
					// let file = new File([JSON.stringify(paperJsonFile)],resourceItem.id + ".json", {type: "",});
					// 先把对应试题目录下的全部复制到校本BLOB 然后再更新添加学段科目等字段后的题目Json文件
					this.$parent.containerClient.copyFolder(toPath,fromPath,privateBlobTool).then(async res => {
						try{
							console.log(JSON.stringify(resourceItem))
							this.savePaperToCosmos(resourceItem).then(result => {
								console.log(result)
								r(result)
							})
						}catch(e){
							j(e)
						}
					}).catch(err => {
						j(err)
					})
				})
			},
			/* 复制内容文件到当前用户BLOB */
			copyFileToBlob(resourceItem){
				return new Promise(async (r, j) => {
					// 试题的拥有者也就是复制的来源容器
					let fileOwner = resourceItem.code.replace('Paper-','')
					let privateSas = await this.$evTools.getBlobPrivateSas(fileOwner)
					let fullLink = 	this.$evTools.getBlobHost() + '/' + fileOwner + resourceItem.link
					console.log(fullLink)
					// 拿到试题的完整数据 方便保存到COSMOS
					this.$parent.containerClient.copyBlob('syllabus/' + resourceItem.title, fullLink, privateSas).then(res => {
						r(200)
					}).catch(err => {
						console.log(err)
						j(err)
					})
				})
			},
			/* 获取章节下所有的资源节点 */
			getAllRNodes(chapterNode){
				let result = []
				const fn = (source)=>{
					result.push(...source.rnodes)
					if(source.children.length){
						console.log(JSON.stringify(source.children[0].rnodes));
						source.children.forEach(i => {
							fn(i)
						})
					}
				}
				fn(chapterNode)
				return result
			},
			// 删除节点操作
			remove(node, data) {
				let isFirstLevel = this.isFirstLevel(data)
				let rNodeLinks = isFirstLevel ? this.getAllRNodes(data).map(i => i.link) : data.rnodes.map(i => i.link)
				console.log(rNodeLinks)
				this.$Modal.confirm({
					title: this.$t('syllabus.tree.removeTitle'),
					content: this.$t('syllabus.tree.removeConfirm'),
					onOk: async () => {
						const parent = node.parent
						const children = parent.data.children || parent.data
						const index = children.findIndex(d => d.id === data.id)
						this.$parent.curNode = {
							id:'',
							rnodes:[]
						}
						this.doDeleteBlobResource(rNodeLinks,data).then(result => {
							// 如果是删除的第一层的节点 则直接访问API进行删除 如果不是 则记录子节点的PID
							if(isFirstLevel){
								this.$api.syllabus.DeleteTree({
									id:data.id,
									code:this.curCode,
									scope:this.volume.scope
								}).then(res => {
									if (!res.error) {
										if(res.code === 404){
											this.$parent.modifyIdArr  = this.$parent.modifyIdArr.filter(i => i !== data.id)
										}
										this.$parent.treeOrigin = this.$parent.treeOrigin.filter(i => i.id !== data.id)
										children.splice(index, 1)
										if(data.id == sessionStorage.getItem('highlightId')){
											sessionStorage.setItem('highlightId',null)
										}
										this.$nextTick().then(() => {
											const firstNode = document.querySelector('.el-tree-node')
											firstNode && firstNode.click();
										})
										this.$Message.success(this.$t('syllabus.tree.removeSucTip'))
									} else {
										this.$Message.warning(res.error);
									}
								}).catch(err => {
									this.$Message.error(err);
								})
							}else{
								children.splice(index, 1)
								this.$Message.success(this.$t('syllabus.tree.removeSucTip'))
								this.$parent.hasModify = true
								this.$emit('addModifyId',this.getChapterIdById(data.id))
								this.$nextTick().then(() => {
									const firstNode = document.querySelector('.el-tree-node')
									firstNode && firstNode.click();
								})
							}
						})
					}
				})
			},
			/* 删除对应关联的资源 */
			doDeleteBlobResource(links,data){
				return new Promise((r,j) => {
					if(!links.length) r(200)
					let syllabusLinks = links.filter(i => i.includes('/syllabus/'))
					if(syllabusLinks.length){
						this.$api.blob.deletePrefix({
							"cntr": this.curCode,
							"prefix": "syllabus/" + data.id
						}).then(res => {
							r(200)
						})
						// this.$api.syllabus.CheckLink({
						// 	"links": syllabusLinks,
						// 	"code": this.curCode,
						// 	"scope": this.isSchool ? 'school' : 'private'
						// }).then(res => {
						// 	console.log(res)
						// 	let needDeleteLink = []
						// 	let curVolumeId = this.volume.id
						// 	let curChapterId = this.getChapterIdById(data.id)
						// 	let curNodeId = data.id
						// 	// 如果删除的是章节 则判断是否有其他章节引用了资源 如果没有 则要进行blob删除
						// 	if(curChapterId === curNodeId){
						// 		syllabusLinks.forEach(i => {
						// 			if(!res.links.filter(j => j.link === i && j.syllabusId !== curChapterId).length){
						// 				needDeleteLink.push(i)
						// 			}
						// 		})
						// 	}else{
						// 		syllabusLinks.forEach(i => {
						// 			if(!res.links.filter(j => j.link === i && j.syllabusId !== curChapterId && j.treeid !== curNodeId).length){
						// 				needDeleteLink.push(i)
						// 			}
						// 		})
						// 	}
						// 	if(needDeleteLink.length){
						// 		let promiseArr = []
						// 		needDeleteLink.forEach(i => {
						// 			promiseArr.push(this.deleteBlobPrefix(i))
						// 		})
						// 		Promise.all(promiseArr).then(result => {
						// 			r(result)
						// 		}).catch(err => {
						// 			j(err)
						// 		})
						// 	}else{
						// 		r(200)
						// 	}
						// }).catch(e => {
						// 	j(e)
						// })
					}else{
						r(200)
					}
				})
			},
			
			/* 删除blob指定试题目录下所有 */
			deleteBlobPrefix(link) {
				return new Promise((resolve, reject) => {
					this.$api.blob.deletePrefix({
						"cntr": this.curCode,
						"prefix": link.substring(1)
					}).then(
						(res) => {
							if (!res.error) {
								resolve(200)
							} else {
								resolve(500)
							}
						},
						(err) => {
							reject(err)
						}
					)
				})
			},
			
			// 点击添加展开弹窗
			onAddNode(node,data, e) {
				if(node.level === 3){
					this.$Message.warning(this.$t('syllabus.tree.nodeCountTip'))
					return
				}
				this.isEditItem = false
				this.isEditOrAdd = true
				this.currentParentData = data // 当前点击节点即为父节点
				this.nodeInfo.parent = data.title
				this.nodeInfo.id = data.id
				this.nodeInfo.title = ''
				this.curNode = node
			},
			// 编辑节点操作
			onEditItem(node, data, e) {
				this.isEditOrAdd = true
				this.isEditItem = true
				this.currentEditData = data
				this.nodeInfo.parent = node.parent.data.title || this.volume.name
				this.nodeInfo.title = node.data.title
				this.nodeInfo.id = node.data.id
				this.nodeInfo.creatorId = this.curTeammodelId
				this.nodeInfo.creatorName = this.curName
				node.creatorId = this.curTeammodelId
				node.creatorName = this.curName
				this.curNode = node
			},
			/* 根据节点获取它所在的章节信息 */
			getChapterByNode(node){
				console.log(node)
				if(node.level === 1){
					return node
				}else{
					return this.getChapterByNode(node.parent)
				}
			},
			// 提交编辑或者新增
			onSubmitNode() {
				if (!this.nodeInfo.title) {
					this.$Message.warning(this.$t('syllabus.tree.nodeNameTip'))
					return
				}
				if (this.isEditItem) {
					this.currentEditData.title = this.nodeInfo.title
					this.currentEditData.creatorId = this.curTeammodelId
					this.currentEditData.creatorName = this.curName
				} else {
					let newChild = Object.assign({}, this.nodeInfo) // 创建新节点
					let parentNode = this.currentParentData
					newChild.id = Math.uuid()
					newChild.nodeKey = newChild.id
					newChild.pid = parentNode.id
					newChild.code = parentNode.code
					newChild.creatorId = this.curTeammodelId
					newChild.creatorName = this.curName
					newChild.children = []
					newChild.resources = []
					newChild.knowledges = []
					if (!this.currentParentData.children) {
						this.$set(this.currentParentData, 'children', [])
					}
					this.currentParentData.children.push(newChild)
				}
				this.isEditOrAdd = false
				this.$parent.hasModify = true
				console.log(this.curData.id);
				this.$emit('addModifyId',this.getChapterIdById(this.curData.id))
				this.$Message.success(this.isEditItem ? this.$t('syllabus.tree.editSucTip') : this.$t('syllabus.tree.addSucTip'))
			},
			/* 获取整个树的章节与子节点归属 */
			getAllChild(arr){
				let result = []
				if(!arr.length) return result
				arr.forEach(item => {
					result.push({
						chapterId:item.id,
						children:this.flatChildren(item.children)
					})
				})
				this.flatArr = result
			},
			/* 递归拉平所有children */
			flatChildren(children){
				let result = []
				const fn = (source)=>{
				    source.forEach(i => {
				    	result.push(i.id)
				    	if(i.children.length){
				    		fn(i.children)
				    	}
				    })
				}
				fn(children)
				return result
			},
			/* 根据某个节点ID换取它对应的章节ID */
			getChapterIdById(id){
				if(this.flatArr.map(i => i.chapterId).includes(id)){
					return id
				}else{
					let targetChapter = this.flatArr.find(i => i.children.includes(id))
					return targetChapter ? targetChapter.chapterId : 0
				}
			}

		},
		computed: {
			curTeammodelId(){
				return this.$store.state.userInfo.TEAMModelId
			},
			curName(){
				return this.$store.state.userInfo.name
			},
			// 判断是否为一级节点
			isFirstLevel() {
				return data => {
					return data.pid === this.volume.id
				}
			},
			getNameById(){
				return id => {
					if(this.$parent.teacherList.length && id){
						let target = this.$parent.teacherList.find(i => i.id === id)
						return target ? target.name : ''
					}else{
						return ''
					}
				}
			},
			// 判断当前用户是否有当前节点的编辑权限（如果父节点有权限则下面的子节点相应都有操作权限）
			hasEditAuth(){
				return nodeData => {
					let userId = this.curTeammodelId
					// 判断是否为一级节点，如果是二级节点则需要拿对应的一级节点去做判断
					let chapterId = nodeData.pid === this.volume.id ? nodeData.id : this.getChapterIdById(nodeData.id)
					let chapterNode = this.treeDatas.find(i => i.id === chapterId)
					return (!this.isSchool && !this.inShareView) || this.$access.can('admin.*|Syllabus_Edit') || this.volume.auth.map(i => i.tmdid).includes(userId) || (chapterNode && chapterNode.auth && chapterNode.auth.length && chapterNode.auth.map(i => i.tmdid).includes(userId))
				}
			},
			// 判断当前用户是否可以删除当前章节
			canDeleteChapter(){
				let userId = this.curTeammodelId
				return this.$access.can('admin.*|Syllabus_Edit') || this.volume.auth.map(i => i.tmdid).includes(userId) || !this.isSchool
			},
			curCode() {
				return this.isSchool ? this.$store.state.userInfo.schoolCode : this.curTeammodelId
			},
			inShareView(){
				return !this.isSchool && this.$parent.activeTab === 'fromShare'
			},
			inSchoolAbility(){
				return this.$route.name === 'abilityMgmt'
			},
			volumeList(){
				return this.$parent.myVolumeList
			}
		},
		watch: {
			// 监听课纲数据变化
			treeData: {
				handler: function(n, o) {
					console.log(n);
					// 以下为拼接树形数据以及册别数据
					this.treeDatas = n.map(i => {
						if(i.trees.length){
							i.trees[0].auth = i.auth
							return i.trees[0]
						}else{
							return {}
						}
					})
					this.getAllChild(this.treeDatas)
					console.log(this.treeDatas);
					if(this.treeDatas.length){
						this.$nextTick().then(() => {
							// const firstNode = document.querySelector('.el-tree-node')
							// firstNode && firstNode.click();
							let highlightId = sessionStorage.getItem('highlightId') || this.treeDatas[0].id
							// let highlightId = this.treeDatas[0].id
							this.$refs.tree.setCurrentKey(highlightId)
							let curSelectNode = this.$refs.tree.getNode(highlightId)
							let curSelectData = this.$refs.tree.getCurrentNode()
							this.onNodeClick(curSelectData,curSelectNode)
						})
					}else{
						this.highlightId = null
					}
					
				},
				immediate: true,
				// deep:true
			},
			// 监听课纲数据变化
			volume: {
				handler: function(n, o) {
					this.volume = n
					
				},
				immediate: true
			}
		}
	}
</script>


<style lang="less" src="./DragTree.less"></style>

<style scoped>
	.tree /deep/ .el-tree-node {
		position: relative;
		padding-left: 16px;
	}

	.tree /deep/ .el-tree-node__children {
		padding-left: 16px;
	}

	.tree /deep/ .el-tree-node :last-child:before {
		height: 38px;
	}

	.tree /deep/ .el-tree>.el-tree-node:before {
		border-left: none;
	}

	.tree-container /deep/ .el-tree>.el-tree-node:after {
		border-top: none;
	}

	.tree /deep/ .el-tree-node:before {
		content: "";
		left: -4px;
		position: absolute;
		right: auto;
		border-width: 1px;
	}

	.tree /deep/ .el-tree-node:after {
		content: "";
		left: -4px;
		position: absolute;
		right: auto;
		border-width: 1px;
	}

	.tree /deep/ .el-tree-node:before {
		border-left: 1px dashed #bebebe;
		bottom: 0px;
		height: 100%;
		top: -20px;
		width: 1px;
	}

	.tree /deep/ .el-tree-node:after {
		border-top: 1px dashed #bebebe;
		height: 20px;
		top: 20px;
		width: 12px;
	}
	
	.tree /deep/ .ivu-tooltip-popper{
		font-size: 12px !important;
	}
</style>
