<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="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" :title="$t('syllabus.tree.hasResource')" v-if="data.rnodes && data.rnodes.length" />
					</span>
					<span class="custom-tree-tools" v-if="editable">
						<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-remove" size="16" :title="$t('syllabus.tree.remove')" @click="remove(node,data)" />
						<Icon type="md-share" v-if="isFirstLevel(data)" :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>
	</div>
</template>

<script>
	import '@/utils/Math.uuid'
	import BaseResource from '@/view/syllabus/newSyllabus/operation/BaseResource'
	import BaseKnowledge from '@/view/syllabus/newSyllabus/operation/BaseKnowledge'
	import BaseQuestionList from '@/common/BaseQuestionList'
	export default {
		props: ['volume', 'treeData', 'editable'],
		components: {
			BaseResource,
			BaseKnowledge,
			BaseQuestionList
		},
		data() {
			return {
				isFalse: false,
				treeDatas: [],
				questionList: [],
				fileList: [],
				defaultProps: {
					children: 'children',
					label: 'title'
				},
				isEditOrAdd: false,
				isLoading: false,
				isRelatedContent: false,
				isShowContent: false,
				isEditItem: false,
				contentIndex: '1',
				currentVolume: null,
				currentEditData: null,
				currentParentData: null,
				currentResources: [],
				currentItems: [],
				curNode: null,
				curData:null,
				nodeInfo: {
					id: null,
					title: '',
					expand: true,
					editable: true,
					version: '',
					type: '1',
					children: [],
					remark: '',
					nodeKey: '',
					pid: '',
					code: '',
					status: 1,
					parent: '',
					rnodes:[]
				},
				isSchool: false,
				flatArr:[]
			}
		},
		created() {
			this.isSchool = this.$route.name === 'syllabus'
		},
		methods: {
			onNodeClick(data, node) {
				this.curNode = node
				this.curData = data
				this.$emit('onNodeClick', {
					data:data,
					node:node
				})
			},

			doShare(data) {
				this.$emit('doShare', data)
			},
			
			/* 禁止一级节点往下级进行拖拽 */
			allowDrop(draggingNode, dropNode, dropType) {
				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

			},

			// 删除节点操作
			remove(node, data) {
				let isFirstLevel = this.isFirstLevel(data)
				this.$Modal.confirm({
					title: this.$t('syllabus.tree.removeTitle'),
					content: this.$t('syllabus.tree.removeConfirm'),
					onOk: () => {
						const parent = node.parent
						const children = parent.data.children || parent.data
						const index = children.findIndex(d => d.id === data.id)
						// 如果是删除的第一层的节点 则直接访问API进行删除 如果不是 则记录子节点的PID
						if(isFirstLevel){
							this.$api.syllabus.DeleteTree({
								id:data.id,
								code:this.volume.id,
								scope:this.volume.scope
							}).then(res => {
								if (!res.error) {
									if(res.code === 404){
										this.$parent.modifyIdArr  = this.$parent.modifyIdArr.filter(i => i !== data.id)
									}
									children.splice(index, 1)
									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))
						}
					}
				})
			},

			// 点击添加展开弹窗
			onAddNode(node,data, e) {
				e.stopPropagation() // 防止点击事件穿透到父层
				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) {
				e.stopPropagation() // 防止点击事件穿透到父层
				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.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
				} 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.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
				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 = []
				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.chapterId
				}
			}

		},
		computed: {
			isFirstLevel() {
				return data => {
					return data.pid === this.volume.id
				}
			},
		},
		watch: {
			// 监听课纲数据变化
			treeData: {
				handler: function(n, o) {
					// 以下为拼接树形数据以及册别数据
					this.treeDatas = n.map(i => i.trees[0])
					this.getAllChild(this.treeDatas)
					this.$nextTick().then(() => {
						const firstNode = document.querySelector('.el-tree-node')
						firstNode.click();
					})
				},
				immediate: true
			},
			// 监听课纲数据变化
			volume: {
				handler: function(n, o) {
					this.volume = n
				}
			}
		}
	}
</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 #626262;
		bottom: 0px;
		height: 100%;
		top: -20px;
		width: 1px;
	}

	.tree /deep/ .el-tree-node:after {
		border-top: 1px dashed #626262;
		height: 20px;
		top: 20px;
		width: 12px;
	}
</style>
