<template>
    <div style="width: 100%; max-height: 600px; overflow: auto;padding-bottom: 10px;" class="content">
        <div style="height:600px;position: relative;" ref="container"></div>
    </div>
</template>

<script>
import G6 from '@antv/g6';

export default {
    props: ['Json'],
    data() {
        return {
            graph: null,
        }
    },
    mounted() {
        this.$nextTick(() => {
            if (this.Json && this.Json.nodes) {
                this.showSeeksGraph(this.Json);
            }
        });
        window.addEventListener('resize', this.handleResize);
    },
    beforeDestroy() {
        window.removeEventListener('resize', this.handleResize);
        if (this.graph) {
            this.graph.destroy();
        }
    },
    watch: {
        Json: {
            immediate: true,
            deep: true,
            handler(newValue, oldValue) {
                this.$nextTick(() => {
                    if (newValue && newValue.nodes && this.$refs.container) {
                        this.showSeeksGraph(newValue);
                    }
                });
            }
        }
    },
    methods: {
        showSeeksGraph(data) {
            if (this.graph) {
                this.graph.destroy();
            }
            console.log(data);

            const container = this.$refs.container;
            if (!container) return;
            
            this.graph = new G6.Graph({
                container: container,
                width: container.scrollWidth,
                height: container.scrollHeight || 600,
                fitView: true,
                modes: {
                    default: ['drag-canvas', 'zoom-canvas', 'drag-node'],
                },
                layout: {
                    type: 'force',
                    preventOverlap: true,
                    nodeSpacing: 30,
                    linkDistance: 200,
                    nodeStrength: -60,
                    edgeStrength: 0.1,
                },
                defaultNode: {
                    size: 40,
                    style: {
                        fill: 'rgba(24, 144, 255, 0.2)', // 浅蓝半透明
                        stroke: '#1890ff', // 实色边框
                        lineWidth: 2 // 边框宽度
                    },
                    labelCfg: {
                        position: 'bottom', // 标签显示在节点下方
                        style: {
                            fill: '#000',
                            fontSize: 12
                        }
                    }
                },
                defaultEdge: {
                    type: 'cubic', // 贝塞尔曲线
                    style: {
                        endArrow: true,
                    },
                     labelCfg: {
                        autoRotate: true,
                    }
                }
            });


            const nodeIds = new Set(data.nodes.map(node => node.id));

            // 统计每个节点的连线数量
            const linkCount = {};
            data.edges.forEach(edge => {
                if (edge.source) linkCount[edge.source] = (linkCount[edge.source] || 0) + 1;
                if (edge.target) linkCount[edge.target] = (linkCount[edge.target] || 0) + 1;
            });

            // 六档蓝色系（更有区分度）
            const strokeColors = [
                '#b3e5fc', // 0 浅蓝青
                '#4fc3f7', // 1 天蓝
                '#0288d1', // 2 深天蓝
                '#1976d2', // 3 标准蓝
                '#1565c0', // 4 深蓝
                '#0d47a1', // 5 靛蓝
                '#002171'  // 6+ 极深蓝
            ];
            const fillColors = [
                'rgba(179,229,252,0.2)',
                'rgba(79,195,247,0.2)',
                'rgba(2,136,209,0.2)',
                'rgba(25,118,210,0.2)',
                'rgba(21,101,192,0.2)',
                'rgba(13,71,161,0.2)',
                'rgba(0,33,113,0.2)'
            ];

            const graphData = {
                nodes: data.nodes.map(node => {
                    const count = linkCount[node.id] || 0;
                    const cappedCount = Math.min(count, 6);
                    const size = 20 + count * 10; // 不封顶
                    const stroke = strokeColors[cappedCount];
                    const fill = fillColors[cappedCount];
                    // 保留 comboId 字段
                    const nodeData = {
                        id: node.id,
                        label: node.label,
                        size,
                        style: {
                            fill,
                            stroke,
                            lineWidth: 2
                        }
                    };
                    if (node.comboId) nodeData.comboId = node.comboId;
                    return nodeData;
                }),
                edges: data.edges
                    .filter(edge => {
                        const sourceExists = nodeIds.has(edge.source);
                        const targetExists = nodeIds.has(edge.target);
                        if (!sourceExists || !targetExists) {
                            console.warn('Filtering out edge with non-existent node ID:', edge);
                        }
                        return sourceExists && targetExists;
                    })
                    .map(edge => ({
                        source: edge.source,
                        target: edge.target,
                        label: edge.predicate,
                })),
                combos: Array.isArray(data.combos) ? data.combos : undefined
            };
            console.log('graphData',graphData);
            
            this.graph.data(graphData);
            this.graph.render();

            this.graph.on('node:mouseenter', (e) => {
                this.graph.setItemState(e.item, 'hover', true);
            });

            this.graph.on('node:mouseleave', (e) => {
                this.graph.setItemState(e.item, 'hover', false);
            });
        },
        handleResize() {
            if (!this.graph || this.graph.get('destroyed')) return;
            if (!this.$refs.container) return;
            
            const container = this.$refs.container;
            this.graph.changeSize(container.offsetWidth, container.scrollHeight || 600);
            this.graph.fitView();
        }
    }
}

</script>

<style></style>