<template>
	<div class="syllabus-tree-main">
		<vuescroll>
			<el-tree :data="treeDatas" :props="defaultProps" class="tree" node-key="id"  default-expand-all highlight-current
				@node-drop="handleDrop" @node-click="onNodeClick" :draggable="editable" :expand-on-click-node="false">
				<span class="custom-tree-node" slot-scope="{ node, data }">
					<span class="tree-node-lable">
						{{data.title}}
						<Icon type="md-cube" title="有关联资源" v-if="data.rnodes && data.rnodes.length"/>
					</span>
					<span class="custom-tree-tools" v-if="editable">
						<Icon type="md-create" size="16" title="编辑" @click="onEditItem(node,data,$event)" />
						<Icon type="md-add" size="16" title="添加" @click="onAddNode(data,$event)" />
						<Icon type="md-remove" size="16" title="删除" @click="remove(node,data)" />
						<Icon type="md-share" v-if="isFirstLevel(data.pid)" @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 ? '编辑节点':'新增节点'}}</div>
			<div class="modal-content">
				<p class="node-title">父节点</p>
				<Input v-model="nodeInfo.parent" style="width: 100%" disabled />
				<p class="node-title">节点名称</p>
				<Input v-model="nodeInfo.title" placeholder="请输入节点名称..." style="width: 100%" />
			</div>
			<Button @click="onSubmitNode" class="modal-btn" style="width: 88%;margin-left: 6%;margin-bottom: 20px;">确认</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,
				nodeInfo: {
					id: null,
					title: '',
					expand: true,
					editable: true,
					version: '',
					type: '1',
					children: [],
					remark: '',
					nodeKey: '',
					pid: '',
					code: '',
					status: 1,
					parent: ''
				}
			}
		},
		methods: {
			onNodeClick(data, node) {
				console.log(data, node)
				this.curNode = data
				this.$emit('onNodeClick',data)
			},
			
			doShare(data){
				this.$emit('doShare',data)
			},
			// 拖拽完成回调
			handleDrop(draggingNode, dropNode, dropType) {
				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) {
				this.$Modal.confirm({
					title: '删除节点',
					content: '<p>确认删除该节点？</p>',
					okText: '确认',
					cancelText: '取消',
					onOk: () => {
						const parent = node.parent
						const children = parent.data.children || parent.data
						const index = children.findIndex(d => d.id === data.id)
						children.splice(index, 1)
						this.$Message.success('删除成功')
						this.$parent.hasModify = true
					}
				})
			},

			// 点击添加展开弹窗
			onAddNode(data, e) {
				e.stopPropagation() // 防止点击事件穿透到父层
				this.isEditItem = false
				this.isEditOrAdd = true

				this.currentParentData = data // 当前点击节点即为父节点
				this.nodeInfo.parent = data.title
				this.nodeInfo.title = ''
			},

			// 编辑节点操作
			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
			},


			onRelatedContent(node, data, e) {
				e.stopPropagation() // 防止点击事件穿透到父层
				this.isRelatedContent = true
				this.currentEditData = data
			},

			onShowContent(val, data) {
				console.log(data)
				this.contentIndex = val
				this.currentItems = []
				this.currentResources = []
				// data.items.length && this.findQuestionById(data.items)
				data.resources.length && this.findResourceById(data.resources)
				this.isShowContent = true
			},

			/**
			 * 通过id查询内容信息
			 * */
			findResourceById(ids) {

				this.$api.learnActivity.FindSyllabusResourceById(ids).then(
					res => {
						if (!res.error) {
							this.currentResources = res.result.data
						} else {
							this.$Message.error("API ERROR")
						}
					},
					err => {
						this.$Message.error("API ERROR")

					}
				)

			},
			/**
			 * 通过id查询题目信息
			 * */
			findQuestionById(ids) {
				this.$api.learnActivity.FindQuestionById(ids).then(
					res => {
						if (!res.error) {
							this.currentItems = res.result.data
						} else {
							this.$Message.error("API ERROR")
						}
					},
					err => {
						this.$Message.error("API ERROR")

					}
				)
			},


			// 提交编辑或者新增
			onSubmitNode() {
				if (!this.nodeInfo.title) {
					this.$Message.warning('节点名称不能为空')
					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.$Message.success(this.isEditItem ? '编辑成功' : '添加成功')
			},


			/**
			 * 选择关联题目
			 * @param val 当前已选题目
			 */
			onSelectQuestion(val) {
				this.questionList = val.questions
			},

			/**
			 * 选择关联内容
			 * @param val 当前已选内容
			 */
			onSelectFile(val) {
				this.fileList = val.files
				console.log(val)
			},

			/** 保存内容与题目关联 */
			onSaveNode() {
				this.isLoading = true
				this.currentEditData.items = this.currentEditData.items ? [...new Set(this.currentEditData.items.concat(
					this.questionList.map(item => item.id)))] : [...new Set(this.questionList.map(item => item.id))]
				this.currentEditData.resources = this.currentEditData.resources ? [...new Set(this.currentEditData
					.resources.concat(this.fileList.map(item => item.url)))] : [...new Set(this.fileList.map(item =>
					item.url))]
				this.$api.syllabus.SaveOrUpdateAsNodes([this.currentEditData]).then(res => {
					if (!res.error && res) {
						this.isRelatedContent = false
						this.$emit('onTreeUpdate')
						this.isLoading = false
						this.$parent.hasModify = true
					} else {
						this.$Message.warning('获取数据失败')
					}
				})
			},

		},
		computed:{
			isFirstLevel(){
				return pid => {
					return pid === this.volume.id
				}
			},
		},
		watch: {
			// 监听课纲数据变化
			treeData: {
				handler: function(n, o) {
					// 以下为拼接树形数据以及册别数据
					// let defaultTree = []
					// let volumeParent = {
					//     title: this.volume.name,
					//     id: this.volume.id,
					//     code: this.volume.code,
					//     pid: 'Root',
					//     children: []
					// }
					// volumeParent.children = n
					// defaultTree.push(volumeParent)
					this.treeDatas = n
					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 #343434;
		bottom: 0px;
		height: 100%;
		top: -20px;
		width: 1px;
	}

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