<template>
    <div class="mermaid-editor">
        <div class="toolbar">
            <button @click="addNode">添加节点</button>
            <button @click="addEdge">添加连接</button>
            <button @click="deleteSelected">删除选中</button>
        </div>
        <div class="editor-container">
            <textarea v-model="mermaidCode" @input="updateDiagram"></textarea>
            <div class="diagram-container" ref="diagramContainer">
                <div ref="mermaid" class="mermaid"></div>
            </div>
        </div>
    </div>
</template>

<script>
// import mermaid from 'mermaid';
// import interact from 'interactjs';
// // import { SVG } from '@svgdotjs/svg.js';
// import SVG from 'svg.js/dist/svg';

export default {
    name: 'InteractiveMermaid',
    data() {
        return {
            mermaidCode: 'graph TD\n    A[开始] --> B[结束]',
            selectedElement: null,
            nodes: {},
            edges: [],
            svgCanvas: null
        };
    },
    mounted() {
        this.initMermaid();
        this.setupInteractivity();
    },
    methods: {
        initMermaid() {
            mermaid.initialize({
                startOnLoad: false,
                theme: 'default',
                flowchart: {
                    useMaxWidth: true,
                    htmlLabels: true,
                    curve: 'basis'
                }
            });
            this.renderDiagram();
        },

        renderDiagram() {
            this.$nextTick(() => {
                try {
                    mermaid.parse(this.mermaidCode);
                    this.$refs.mermaid.innerHTML = this.mermaidCode;
                    mermaid.init(undefined, this.$refs.mermaid, () => {
                        this.$nextTick(() => {
                            this.setupSvgCanvas();
                            this.enableDragAndDrop();
                            this.enableNodeEditing();
                        });
                    });
                } catch (e) {
                    console.error('Mermaid 渲染错误:', e);
                }
            });
        },

        setupSvgCanvas() {
            const svgElement = this.$refs.mermaid.querySelector('svg');
            if (svgElement) {
                this.svgCanvas = SVG(svgElement);
                this.cacheDiagramElements();
            }
        },

        cacheDiagramElements() {
            // 缓存节点和边信息
            this.nodes = {};
            this.edges = [];

            const nodeElements = this.$refs.mermaid.querySelectorAll('.node');
            nodeElements.forEach(node => {
                const id = node.id.replace('node-', '');
                this.nodes[id] = {
                    element: node,
                    rect: node.querySelector('rect'),
                    text: node.querySelector('text')
                };
            });

            const edgeElements = this.$refs.mermaid.querySelectorAll('.edgePath');
            edgeElements.forEach(edge => {
                this.edges.push({
                    element: edge,
                    path: edge.querySelector('path')
                });
            });
        },

        enableDragAndDrop() {
            interact('.node')
                .draggable({
                    onmove: (event) => {
                        const target = event.target;
                        const x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx;
                        const y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy;

                        target.style.transform = `translate(${x}px, ${y}px)`;
                        target.setAttribute('data-x', x);
                        target.setAttribute('data-y', y);

                        // 更新Mermaid代码
                        this.updateMermaidCodeFromDOM();
                    }
                });
        },

        enableNodeEditing() {
            // 双击节点编辑文本
            Object.keys(this.nodes).forEach(id => {
                const node = this.nodes[id];
                node.text.addEventListener('dblclick', () => {
                    this.editNodeText(id);
                });
            });
        },

        editNodeText(nodeId) {
            const node = this.nodes[nodeId];
            const currentText = node.text.textContent;
            const newText = prompt('编辑节点文本:', currentText);

            if (newText !== null && newText !== currentText) {
                // 更新DOM
                node.text.textContent = newText;

                // 更新Mermaid代码
                this.updateMermaidCodeFromDOM();
            }
        },

        updateMermaidCodeFromDOM() {
            // 从DOM状态重建Mermaid代码
            let newCode = 'graph TD\n';

            // 添加节点
            Object.keys(this.nodes).forEach(id => {
                const node = this.nodes[id];
                const text = node.text.textContent;
                newCode += `    ${id}["${text}"]\n`;
            });

            // 添加边（简化版，实际需要更复杂的逻辑来重建边）
            if (this.edges.length > 0) {
                newCode += `    A --> B\n`; // 这里需要根据实际连接关系重建
            }

            this.mermaidCode = newCode;
        },

        addNode() {
            const newNodeId = 'N' + Object.keys(this.nodes).length;
            const newNodeText = '新节点';

            // 更新Mermaid代码
            this.mermaidCode += `\n    ${newNodeId}["${newNodeText}"]`;
            this.renderDiagram();
        },

        addEdge() {
            if (Object.keys(this.nodes).length >= 2) {
                const nodeIds = Object.keys(this.nodes);
                const fromNode = nodeIds[0]; // 简化：实际应该让用户选择
                const toNode = nodeIds[1];   // 简化：实际应该让用户选择

                this.mermaidCode += `\n    ${fromNode} --> ${toNode}`;
                this.renderDiagram();
            }
        },

        deleteSelected() {
            if (this.selectedElement) {
                // 从Mermaid代码中删除选中的元素
                // 这里需要根据选中元素的类型（节点/边）进行不同的处理
                this.renderDiagram();
            }
        },

        updateDiagram() {
            this.renderDiagram();
        }
    }
};
</script>

<style scoped>
.mermaid-editor {
    display: flex;
    flex-direction: column;
    height: 100%;
}

.toolbar {
    padding: 10px;
    background: #f5f5f5;
    border-bottom: 1px solid #ddd;
}

.editor-container {
    display: flex;
    flex: 1;
    overflow: hidden;
}

.editor-container textarea {
    width: 300px;
    height: 100%;
    padding: 10px;
    border-right: 1px solid #ddd;
    resize: none;
    font-family: monospace;
}

.diagram-container {
    flex: 1;
    overflow: auto;
    padding: 20px;
}

.node {
    cursor: move;
}

.node rect {
    fill: #fff;
    stroke: #333;
    stroke-width: 2px;
}

.node text {
    font-size: 14px;
    font-family: Arial, sans-serif;
}
</style>