<template>
	<RelationGraph style="width: 100%; height: 100%" ref="graphRef" :options="currentGraphOptions"
		:on-node-click="onNodeClick" :on-line-click="onLineClick">
		<template #node="{ node }">
			<div class="custom-node" :style="{
				backgroundColor: node.color || 'var(--color-primary-50)'
			}">
				<span :style="{
					color: node.fontColor || '#ffffff',
					fontSize: node.customFontSize || '24px',
					fontWeight: 'normal',
					textAlign: 'center',
					wordBreak: 'break-word',
					padding: '0 8px'
				}">
					{{ node.text }}
				</span>
			</div>
		</template>
	</RelationGraph>
</template>

<script setup>
import { ref, onMounted, watch, computed } from "vue";
import RelationGraph from "relation-graph-vue3";

const graphRef = ref(null);

// 定义 Props
const props = defineProps({
	isVerticalChart: {
		type: Boolean,
		default: false
	},
	// 【新增】是否反向布局（根节点在右侧）
	isReversed: {
		type: Boolean,
		default: false
	},
	graphData: {
		type: Object,
		default: () => ({ rootId: "a", nodes: [], lines: [] })
	}
});

const emit = defineEmits(["nodeClick", "lineClick"]);

// 基础水平配置
const baseGraphOptionsH = {
	layout: {
		layoutName: "tree",
		min_per_height: "auto"
	},
	defaultLineMarker: {
		markerWidth: 12,
		markerHeight: 12,
		refX: 6,
		refY: 6,
		data: "M2,2 L10,6 L2,10 L6,6 L2,2"
	},
	defaultNodeShape: 1,
	defaultNodeWidth: 35,
	defaultLineShape: 4,
	defaultJunctionPoint: "tb",
	defaultNodeBorderWidth: 2,
	defaultNodeBorderColor: "var(--color-primary-100)",
	defaultLineColor: "var(--color-primary-50)",
	defaultNodeColor: "var(--color-primary-50)",
	defaultNodeFontColor: "var(--text-primary-90-color)",
	// 背景图配置
	backgroundImage: new URL('@/assets/images/bg/companyGraph-bg.png', import.meta.url).href, // Vite 引入本地图片
	// backgroundImage: 'https://example.com/your-bg-image.png', // 或者直接用网络图片
	backgroundImageNoRepeat: true, // 图片不重复
	backgroundImageOffsetX: 0,    // X轴偏移
	backgroundImageOffsetY: 0,    // Y轴偏移
	// backgroundColor: '#f5f5f5',    // 背景底色
};

// 基础垂直配置
const baseGraphOptionsV = {
	layouts: [
		{
			layoutName: "tree",
			from: "left", // 默认从左向右
			max_per_width: "auto"
		}
	],
	defaultLineMarker: {
		markerWidth: 12,
		markerHeight: 12,
		refX: 6,
		refY: 6,
		data: "M2,2 L10,6 L2,10 L6,6 L2,2"
	},
	defaultNodeShape: 1,
	defaultNodeWidth: 150,
	defaultLineShape: 4,
	defaultJunctionPoint: "lr",
	defaultNodeBorderWidth: 2,
	defaultLineColor: "var(--color-primary-50)",
	defaultNodeColor: "var(--color-primary-50)",
	defaultNodeFontColor: "var(--bg-white-100)",
	// 背景图配置
	backgroundImage: new URL('@/assets/images/bg/companyGraph-bg.png', import.meta.url).href, // Vite 引入本地图片
	// backgroundImage: 'https://example.com/your-bg-image.png', // 或者直接用网络图片
	backgroundImageNoRepeat: true, // 图片不重复
	backgroundImageOffsetX: 0,    // X轴偏移
	backgroundImageOffsetY: 0,    // Y轴偏移
	// backgroundColor: '#f5f5f5',    // 背景底色
};

// 【核心修改】根据 isReversed 动态计算配置
const currentGraphOptions = computed(() => {
	if (props.isVerticalChart) {
		// 深拷贝配置，避免污染原始对象
		const options = JSON.parse(JSON.stringify(baseGraphOptionsV));
		// 如果反向，则从右向左布局
		if (props.isReversed) {
			options.layouts[0].from = "right";
		} else {
			options.layouts[0].from = "left";
		}
		return options;
	} else {
		// 水平布局通常不受 from 影响太大，或者可以通过 layoutName: 'force' 等调整
		// 这里主要处理垂直树状图的反向
		return baseGraphOptionsH;
	}
});

const showHTree = async () => {
	const __graph_json_data = props.graphData;
	const graphInstance = graphRef.value?.getInstance();
	if (graphInstance) {
		await graphInstance.setOptions(currentGraphOptions.value);
		await graphInstance.setJsonData(__graph_json_data);
		await graphInstance.moveToCenter();
		await graphInstance.setZoom(35);
	}
};

const showVTree = async () => {
	const __graph_json_data = props.graphData;
	const graphInstance = graphRef.value?.getInstance();
	if (graphInstance) {
		// 使用计算后的配置
		await graphInstance.setOptions(currentGraphOptions.value);
		await graphInstance.setJsonData(__graph_json_data);
		await graphInstance.moveToCenter();
		await graphInstance.zoomToFit();
	}
};

const onNodeClick = (nodeObject, $event) => {
	emit("nodeClick", nodeObject);
};

const onLineClick = (lineObject, linkObject, $event) => {
	emit("lineClick", lineObject);
};

watch(
	() => [props.isVerticalChart, props.isReversed, props.graphData],
	() => {
		if (props.isVerticalChart) {
			showVTree();
		} else {
			showHTree();
		}
	},
	{ deep: true }
);

onMounted(() => {
	if (props.isVerticalChart) {
		showVTree();
	} else {
		showHTree();
	}
});
</script>

<style lang="scss" scoped>
:deep(.relation-graph) {
	.c-node-text {
		padding: 0px;
		place-items: center;
		justify-content: center;
	}
}

.custom-node {
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
}
</style>
