<template>
    <div class="mermaid-container">
        <div class="mermaid-editor">
            <textarea v-model="code" @input="updateDiagram"></textarea>
        </div>
        <div class="mermaid-display" ref="mermaidDiagram"></div>
    </div>
</template>
<!-- MermaidDiagram -->
<script>
// import mermaid from 'mermaid';

export default {
    name: 'MermaidDiagram',
    props: {
        initialCode: {
            type: String,
            default: 'graph TD\n    A[Start] --> B{Decision}\n    B -->|Yes| C[Action 1]\n    B -->|No| D[Action 2]'
        }
    },
    data() {
        return {
            code: this.initialCode
        };
    },
    mounted() {
        mermaid.initialize({
            startOnLoad: false,
            theme: 'default',
            flowchart: {
                useMaxWidth: true,
                htmlLabels: true,
                curve: 'basis'
            }
        });
        this.updateDiagram();
    },
    methods: {
        updateDiagram() {
            this.$emit('code-updated', this.code);

            this.$nextTick(() => {
                try {
                    // 清空容器，避免重复渲染
                    this.$refs.mermaidDiagram.innerHTML = '';
                    // 手动插入 Mermaid 代码并渲染
                    this.$refs.mermaidDiagram.innerHTML = `<div class="mermaid">${this.code}</div>`;
                    mermaid.init(undefined, this.$refs.mermaid);
                } catch (e) {
                    console.error('Mermaid 渲染失败:', e.message);
                }
            });

            // try {
            //     mermaid.parse(this.code);
            //     this.$nextTick(() => {
            //         mermaid.init(undefined, this.$refs.mermaidDiagram);
            //         this.$refs.mermaidDiagram.innerHTML = this.code;
            //     });
            // } catch (error) {
            //     console.error('Mermaid syntax error:', error);
            // }
        },
        getDiagramCode() {
            return this.code;
        },
        exportAsImage() {
            const svgElement = this.$refs.mermaidDiagram.querySelector('svg');
            if (!svgElement) return;

            const svgData = new XMLSerializer().serializeToString(svgElement);
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            const img = new Image();

            img.onload = () => {
                canvas.width = img.width;
                canvas.height = img.height;
                ctx.drawImage(img, 0, 0);

                const pngFile = canvas.toDataURL('image/png');
                const downloadLink = document.createElement('a');
                downloadLink.download = 'diagram.png';
                downloadLink.href = pngFile;
                downloadLink.click();
            };

            img.src = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svgData)));
        }
    }
};
</script>

<style scoped>
.mermaid-container {
    display: flex;
    height: 500px;
}

.mermaid-editor {
    flex: 1;
    padding: 10px;
}

.mermaid-editor textarea {
    width: 100%;
    height: 100%;
    font-family: monospace;
}

.mermaid-display {
    flex: 1;
    padding: 10px;
    border: 1px solid #ddd;
    overflow: auto;
}
</style>