<template>
	<view class="content" style="background: none;">
		<view class="user-box">
			<m-tree class="u-p-l-40" ref="mtree" :defaultProps="defaultProps" :data="tree" :divider="divider" :edit="edit"
				:unfold="true" @node-click="nodeClick" @up-item="upNode" @down-item="downNode" @add-item="openAddModel"
				@edit-item="openEditModel" @delete-item="deleteNode" @finger-action="fingerAction"
				@long-press="longpressNode"></m-tree>
		</view>
		<u-toast ref="uToast" />
		<u-modal v-model="modelShow" :title="modelTitle" show-cancel-button	@confirm="confirmModel">
			<view class="slot-content">
				<view class="form-item">
					<view class="form-item-label">
						{{typeName}}名:
					</view>
					<view class="form-item-value">
						<u-input type="text" border v-model="form.labelKey" style="flex: 1;"/>
					</view>
				</view>
				<view class="form-item">
					<view class="form-item-label">
						排序:
					</view>
					<view class="form-item-value">
						<u-input type="text" border v-model="form.orderNum" style="flex: 1;"/>
					</view>
				</view>
				<!-- <view class="form-item">
					<view class="form-item-label">
						绑定码:
					</view>
					<view class="form-item-value">
						<u-input type="text" border v-model="form.barCode" placeholder="非必填" style="flex: 1;"/>
						<u-button type="primary" size="mini" style="margin-left: 10rpx;" :custom-style="customStyle" @click="scanCode">
							<u-icon name="scan" border color="#fff" size="32"></u-icon>
						</u-button>
					</view>
				</view> -->
			</view>
		</u-modal>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				projectId: '',
				projectRole: '',
				tagType: '',
				defaultProps: {
					id: 'labelCode',
					children: 'children',
					label: 'labelKey',
					sort: 'orderNum',
					typeName:'空间',
					oneTreeType:'设备组'
				},
				divider: false,
				edit: true,
				tree: [],
				form: {
					labelCode: null,
					parentId: null,
					labelKey: null,
					orderNum: 50,
					labelType: null,
					barCode:null
				},
				typeName:'空间',
				modelShow:false,
				modelTitle:'新增空间',
				customStyle: {
					height:'70rpx',
					display: 'flex', 
					alignItems: 'center'
				}
			}
		},
		onLoad(option) {
			this.projectId = option.projectId;
			this.projectRole = option.projectRole;
			this.typeName = option.typeName;
			this.defaultProps.typeName = option.typeName;
			uni.setNavigationBarTitle({
				title: `${option.typeName}管理`
			});
			this.getTagTypeList();
		},
		onShow() {
			if (this.tagType) {
				this.getTagTypeList();
			}
		},
		onPullDownRefresh() {
			this.getTagList(true);
		},
		methods: {
			scanCode(){
				uni.scanCode({
					// scanType: ['barCode'],
					success: (data) => {
						console.log('条码类型：' + data.scanType);
						console.log('条码内容：' + data.result);
						this.form.barCode = data.result;
					},
					fail: (err) => {
						console.log('扫码失败：' + err);
					}
				});
			},
			getTagTypeList() {
				let obj = {
					projectId: this.projectId,
				}
				this.$get("iot/labelType/list", obj).then((res) => {
					if (res.rows && res.rows.length > 0) {
						let tagType = '';
						res.rows.forEach(item => {
							if (item.labelName == this.typeName) {
								tagType = item.labelType;
							}
						})
						this.tagType = tagType;
						if (tagType) {
							this.getTagList()
						}
					} else {}
				}).catch(() => {})
			},
			getTagList(flag) {
				let obj = {
					labelType: this.tagType,
					projectId: this.projectId,
				}
				this.$get("iot/labelData/list", obj).then((res) => {
					if (res.rows && res.rows.length > 0) {
						// 接口返回的当前页数据列表 (数组)
						let curPageData = res.rows;
						this.tree = handleTree(curPageData, "labelCode", "parentId");
					} else {
						this.tree = [];
					}
					if (flag) {
						uni.stopPullDownRefresh();
					}
				}).catch(() => {
					//联网失败, 结束加载
					this.mescroll.endErr();
					if (flag) {
						uni.stopPullDownRefresh();
					}
				})
			},
			//遍历id节点并删除
			removeNodeData(datas, id) { //遍历树  获取id数组
				for (var i in datas) {
					if (id === datas[i].id) {
						console.log('要删除项目：', datas[i].id);
						datas.splice(i, 1);
						break;
					} else {
						if (datas[i].children) { //存在子节点就递归
							this.removeNodeData(datas[i].children, id);
						}
					}
				}
			},
			//遍历id节点添加子项
			addNodeData(datas, id, nodedata) { //遍历树  获取id数组
				var addflag = false;
				if (id === 0) {
					datas.unshift(nodedata);
					addflag = true;
				} else {
					for (var i in datas) {
						console.log(JSON.stringify(datas[i]));
						if (id === datas[i].id) {
							console.log('要增加项目：', datas[i].id, nodedata);
							datas[i].children.unshift(nodedata);
							addflag = true;
							break;
						} else {
							if (datas[i].children) { //存在子节点就递归
								this.addNodeData(datas[i].children, id, nodedata);
							}
						}
					}
				}
				return addflag;
			},
			//节点点击事件
			nodeClick(e) {
				let labelCodes = this.getAllLabelCodes(e);
				uni.navigateTo({
					url: '/pages/project/space/deviceList?labelCode=' + e.labelCode + '&projectId=' + this.projectId +
						'&projectRole=' + this.projectRole + '&tagType=' + this.tagType + '&isDefault=' + e.isDefault +
						'&labelCodes=' + labelCodes + '&ancestors=' + e.ancestors + '&labelKey=' + e.labelKey + '&typeName=' + this.typeName
				})
			},
			//节点up按钮点击事件
			upNode(e) {
				const that = this;
				if (e.index != 0) {
					// 根据自身需求，自行修改数据处理方法；

					// up上移操作，排序并更新tree中对应元素sort属性
					var data = {
						pnode: {},
						itemA: {
							id: e.items[e.index - 1].id,
							sort: e.items[e.index].sort
						},
						itemB: {
							id: e.items[e.index].id,
							sort: e.items[e.index - 1].sort
						},
					}
					that.$refs.mtree.treeSort(that.tree, e.item.pid, data); // 调用组件方法 排序sort 从小到大排序

				}
			},
			//节点down按钮点击事件
			downNode(e) {
				const that = this;
				console.log('downNode');
				if (e.index != e.items.length - 1) {
					// 根据自身需求，自行修改数据处理方法；

					// down下移操作，排序并更新tree中对应元素sort属性
					var data = {
						pnode: {},
						itemA: {
							id: e.items[e.index + 1].id,
							sort: e.items[e.index].sort
						},
						itemB: {
							id: e.items[e.index].id,
							sort: e.items[e.index + 1].sort
						},
					}
					that.$refs.mtree.treeSort(that.tree, e.item.pid, data); // 调用组件方法 排序sort 从小到大排序
				}
			},
			//节点新增按钮点击事件
			addNode(e) {
				console.log('点击的项目add', e);
				this.$post("/iot/labelData", {
					labelCode: this.form.labelCode,
					labelKey: this.form.labelKey,
					labelType: this.form.labelType,
					orderNum: this.form.orderNum,
					parentId: this.form.parentId,
					barCode: this.form.barCode,
				}).then((res) => {
					console.log("res", res)
					if (res.code == 200) {
						this.$refs.uToast.show({
							title: '添加成功',
							type: 'success',
						})
						this.getTagTypeList();
					} else {
						this.$refs.uToast.show({
							title: res.msg,
							type: 'error',
						})
					}
				}).catch((err) => {
					this.$refs.uToast.show({
						title: err.msg,
						type: 'error',
					})
				})
			},
			openAddModel(e){
				console.log("e",e)
				this.modelTitle = '新增'+ this.typeName;
				this.form = {
					labelCode: null,
					parentId: e.labelCode,
					labelKey: null,
					orderNum: 50,
					labelType: e.labelType,
					barCode: null
				}
				this.modelShow = true;
			},
			openEditModel(e){
				console.log("e",e)
				this.modelTitle = '编辑'+ this.typeName;
				this.form = {
					labelCode: e.labelCode,
					parentId: e.parentId,
					labelKey: e.labelKey,
					orderNum: e.orderNum,
					labelType: e.labelType,
					barCode: e.barCode
				}
				this.modelShow = true;
			},
			confirmModel(){
				if (this.modelTitle === ('新增'+this.typeName)){
					this.addNode()
				}else if (this.modelTitle === ('编辑'+this.typeName)){
					this.editNode()
				}
			},
			
			//节点更新按钮点击事件
			editNode(e) {
				console.log("e",e)
				this.$put("/iot/labelData", {
					labelCode: this.form.labelCode,
					labelKey: this.form.labelKey,
					labelType: this.form.labelType,
					orderNum: this.form.orderNum,
					parentId: this.form.parentId,
					barCode: this.form.barCode,
				}).then((res) => {
					console.log("res", res)
					if (res.code == 200) {
						this.$refs.uToast.show({
							title: '编辑成功',
							type: 'success',
						})
						this.getTagTypeList();
					} else {
						this.$refs.uToast.show({
							title: res.msg,
							type: 'error',
						})
					}
				}).catch((err) => {
					this.$refs.uToast.show({
						title: err.msg,
						type: 'error',
					})
				})
			},
			//节点删除按钮点击事件
			deleteNode(e) {
				console.log('点击的项目delete', e);
				uni.showModal({
					title: '提示',
					content: '确认要删除空间(' + e.labelKey + ')吗？',
					confirmText: '确认',
					cancelText: '取消',
					success: (res) => {
						if (res.confirm) {
							let arr = this.getAllLabelCodes(e)
							let labelCode = arr.join(',');
							this.$DELETE("/iot/labelData/" + labelCode, {}).then((res) => {
								console.log("res", res)
								if (res.code == 200) {
									this.$refs.uToast.show({
										title: '删除成功',
										type: 'success',
									})
									this.getTagTypeList()
								} else {
									this.$refs.uToast.show({
										title: res.msg,
										type: 'error',
									})
								}
							}).catch((err) => {
								this.$refs.uToast.show({
									title: err.msg,
									type: 'error',
								})
							})
						} else if (res.cancel) {

						}
					}
				});
			},
			getAllLabelCodes(obj) {
				const labelCodes = [];
				function traverse(node) {
					if (node && node.labelCode !== undefined) {
						labelCodes.push(node.labelCode);
					}
					if (node && node.children && Array.isArray(node.children)) {
						node.children.forEach(child => {
							traverse(child);
						});
					}
				}
				traverse(obj);
				return labelCodes;
			},
			//节点滑动
			fingerAction(e) {
				console.log('节点滑动fingerAction', JSON.stringify(e));
			},
			//节点选线长按事件
			longpressNode(e) {
				console.log('长按的项目longpress', JSON.stringify(e));
			},
		}
	}

	function handleTree(data, id, parentId, children, rootId) {
		id = id || 'id';
		parentId = parentId || 'parentId';
		children = children || 'children';
		rootId = rootId || Math.min.apply(Math, data.map(item => {
			return item[parentId];
		})) || 0;

		// 对源数据深度克隆
		const cloneData = JSON.parse(JSON.stringify(data));

		// 循环所有项
		const treeData = cloneData.filter(father => {
			let branchArr = cloneData.filter(child => {
				// 返回每一项的子级数组
				return father[id] === child[parentId];
			});
			// 按 orderNum 排序子节点
			branchArr.sort((a, b) => a.orderNum - b.orderNum);
			// 如果子节点数组不为空，将其赋值给父节点的 children 属性
			if (branchArr.length > 0) {
				father[children] = branchArr;
			}
			// 返回第一层
			return father[parentId] === rootId;
		});
		return treeData.length > 0 ? treeData : data;
	}
</script>

<style lang="scss">
	page {
		background-color: #ededed;
	}

	.user-box {
		background-color: #fff;
	}
	.slot-content{
		padding: 20rpx 10rpx;
		.form-item{
			display: flex;
			align-items: center;
			margin-bottom: 10rpx;
			.form-item-label{
				width: 120rpx;
				font-size: 28rpx;
			}
			.form-item-value{
				flex: 1;
				display: flex;
				align-items: center;
			}
		}
	}
</style>