<template>
	<RelationGraph
		style="width: 100%; height: 100%"
		ref="graphRef"
		:options="graphOptions"
		@node-click="onNodeClick"
		@line-click="onLineClick"
	>
		<!-- 自定义节点插槽 - 这是官方推荐的方式 -->
		<template #node="{ node }">
			<div
				class="custom-node"
				:style="{
					backgroundColor: node.color || 'var(--color-primary-50)'
				}"
			>
				{{ console.log(node) }}
				<!-- 在这里自由控制文字样式 -->
				<div class="img" v-if="node.data.pic">
					<img :src="node.data.pic" alt="" />
				</div>
				<span
					class="text"
					:style="{
						color: node.fontColor || 'var(--text-primary-80-color)',
						fontSize: node.customFontSize || '24px' // 可以从数据中读取
					}"
				>
					{{ node.text }}
				</span>
			</div>
		</template>
	</RelationGraph>
</template>

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

const props = defineProps({
	graphData: {
		type: Object,
		default: {}
	}
});

const graphRef = ref(null);

const graphOptions = ref({
	debug: false,
	defaultNodeBorderWidth: 0,
	allowSwitchLineShape: true,
	allowSwitchJunctionPoint: true,
	defaultNodeColor: "var(--color-primary-50)",
	defaultNodeFontColor: "var(--text-primary-90-color)", // 默认文字颜色：深灰色
	defaultLineShape: 1,
	layout: {
		layoutName: "force"
	},
	defaultJunctionPoint: "border"
	// defaultNodeWidth:  150,   // 全局默认节点宽度
	// defaultNodeHeight:  150,   // 全局默认节点高度
});

const showGraph = async () => {
	const __graph_json_data = props.graphData;

	const graphInstance = graphRef.value.getInstance();
	if (graphInstance) {
		await graphInstance.setJsonData(__graph_json_data);
		await graphInstance.moveToCenter();
		// await graphInstance.zoomToFit();
		await graphInstance.setZoom(45);
	}
};

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

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

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

onMounted(() => {
	showGraph();
});
</script>

<style lang="scss" scoped>
.custom-node {
	width: 100%;
	height: 100%;
	border-radius: 50%;
	padding: 10px;
	display: flex;
	align-items: center;
	justify-content: center;
	position: relative;

	.img {
		position: absolute;
		width: 50px;
		height: 50px;

		img {
			width: 100%;
			height: 100%;
		}
	}

	.text {
		font-weight: normal;
		text-align: center;
		word-break: break-word;
		padding: 0 8px;
		white-space: nowrap;
		margin-top: 120px;
		display: inline-block;
	}
}
</style>
