<!--
 * @Author: zwq
 * @Date: 2021-11-18 14:16:25
 * @LastEditors: zwq
 * @LastEditTime: 2025-11-25 15:49:17
 * @Description:
-->
<template>
	<div style="width: 100%; display: flex; justify-content: center">
		<tree-transfer
			:title="title"
			:from_data="fromData"
			:to_data="toData"
			@add-btn="add"
			@remove-btn="remove"
			pid="fid"
			:node_key="'uniqueId'"
			:defaultProps="{
				label: 'name',
				children: 'children',
			}"
			height="450px"
			style="padding-bottom: 20px"
			:mode="mode"
			filter
			openAll></tree-transfer>
	</div>
</template>

<script>
import treeTransfer from 'el-tree-transfer';
import { getGroupPlanTree } from '@/api/group/Schedule';

export default {
	components: { treeTransfer },
	data() {
		return {
			title: ['待选', '已选'],
			mode: 'transfer',
			fromData: [], //左边内容
			toData: [], //右边已选内容
		};
	},
	methods: {
		init(val) {
			this._pageIndex = val._pageIndex - 1;
			this.fromData = [];
			this.toData = [];
			getGroupPlanTree().then((res) => {
				res.data.forEach((item) => {
					item.productionLineId = 0;
				});
				this.fromData = this.generateUniqueData(res.data);
				this.$nextTick(() => {
					this.toData = val.bindLineTree || [];
					this.getFilterLeftData(this.fromData, this.toData); //编辑时组件有bug，左边相同数据不消失
				});
			});
		},
		generateUniqueData(data) {
			return data.map((node) => this.processNode(node));
		},
		processNode(node) {
			// 创建唯一ID：类型-原始ID
			const uniqueId = node.type+'L'+node.id;
			if (node.type > 0) {
				node.fid = (node.type - 1)+'L'+node.pid;
			}

			return {
				...node,
				uniqueId,
				children: node.children
					? node.children.map((child) => this.processNode(child))
					: [],
			};
		},
		// 监听穿梭框组件添加
		add(fromData, toData, obj) {
			console.log('fromData:', fromData);
			console.log('toData:', toData, obj);
		},
		// 监听穿梭框组件移除
		remove(fromData, toData, obj) {
			console.log('fromData:', fromData);
			console.log('toData:', toData);
		},
		/** 消除组件左边与右边选中数据相同项 */
		// 处理过滤数据
		getFilterLeftData(data, selData) {
			for (let i = data.length - 1; i >= 0; i--) {
				for (let j = selData.length - 1; j >= 0; j--) {
					if (data[i] && data[i].id === selData[j].id) {
						// 当id相等可以删除的情况 即：没有子级可以删除；
						if (!data[i].children || data[i].children.length == 0) {
							data.splice(i, 1);
						} else {
							this.getFilterLeftData(data[i].children, selData[j].children);
						}
					}
				}
			}
		},
		// 表单提交
		dataFormSubmit() {
			this.$emit('refreshTableData', this._pageIndex, this.toData);
		},
	},
};
</script>
