<template>
    <div class="mermaid-flow">
        <div ref="mermaidContainer" class="mermaid-content"></div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, computed } from 'vue'
import mermaid from 'mermaid'

interface Props {
    flowNodes?: string[]
}

const props = withDefaults(defineProps<Props>(), {
    flowNodes: () => []
})

const mermaidContainer = ref<HTMLElement>()

// 明确流程节点ID映射
const nodeIdMap = {
    '1': '现场评审',
    '2': '样品试用'
}

// 动态生成流程图的逻辑
const generateFlowDefinition = (selectedNodes: string[]) => {
    // 基础流程
    let flowDefinition = `flowchart TD
    A["供应商申请"] --> B["填写供方基本情况调查表"]
    B --> C["基本情况审核"]
    C --> D{"审核通过"}
    D -->|否| B`

    // 根据选择的节点生成流程
    if (selectedNodes.length === 0) {
        // 没有选择任何节点，直接到合格供应商
        flowDefinition += `
    D -->|是| L["合格供应商"]`
    } else {
        // 有选择节点，按顺序生成流程
        let currentNode = 'D'

        // 如果选择了现场评审
        if (selectedNodes.includes('1')) {
            flowDefinition += `
    D -->|是| E1["现场评审"]
    E1 --> F1["评定报告"]
    F1 --> G1{"评审通过"}
    G1 -->|否| E1`

            currentNode = 'G1'
        }

        // 如果选择了样品试用
        if (selectedNodes.includes('2')) {
            flowDefinition += `
    ${currentNode} -->|是| H1["样品试用"]
    H1 --> I1["试用评估报告"]
    I1 --> J1{"试用通过"}
    J1 -->|否| K["淘汰"]
    J1 -->|是| L["合格供应商"]`
        } else {
            // 没有选择样品试用，直接到合格供应商
            flowDefinition += `
    ${currentNode} -->|是| L["合格供应商"]`
        }
    }

    // 添加样式定义
    flowDefinition += `

    classDef processBox fill:#e1f5fe,stroke:#01579b,stroke-width:2px,color:#000
    classDef decisionBox fill:#fff3e0,stroke:#e65100,stroke-width:2px,color:#000
    classDef endBox fill:#f3e5f5,stroke:#4a148c,stroke-width:2px,color:#000
    classDef rejectBox fill:#ffebee,stroke:#c62828,stroke-width:2px,color:#000
    
    class A,B,C processBox
    class D decisionBox`

    // 根据选择的节点添加样式
    if (selectedNodes.includes('1')) {
        flowDefinition += `
    class E1,F1 processBox
    class G1 decisionBox`
    }

    if (selectedNodes.includes('2')) {
        flowDefinition += `
    class H1,I1 processBox
    class J1 decisionBox`
    }

    flowDefinition += `
    class L endBox
    class K rejectBox`

    return flowDefinition
}

// 计算属性：根据选择的节点生成流程定义
const mermaidDefinition = computed(() => {
    return generateFlowDefinition(props.flowNodes)
})

const initializeMermaid = async () => {
    try {
        // 初始化 Mermaid 配置
        mermaid.initialize({
            startOnLoad: false,
            theme: 'default',
            flowchart: {
                useMaxWidth: true,
                htmlLabels: true,
                curve: 'basis'
            },
            themeVariables: {
                primaryColor: '#e1f5fe',
                primaryTextColor: '#000',
                primaryBorderColor: '#01579b',
                lineColor: '#666',
                secondaryColor: '#fff3e0',
                tertiaryColor: '#f3e5f5'
            }
        })

        // 渲染图表
        if (mermaidContainer.value) {
            const flowDef = mermaidDefinition.value
            // console.log('生成的流程图定义:', flowDef)
            // console.log('选择的流程节点:', props.flowNodes)

            const { svg } = await mermaid.render('supplier-flow', flowDef)
            mermaidContainer.value.innerHTML = svg
        }
    } catch (error) {
        console.error('Mermaid 渲染失败:', error)
        console.error('流程图定义:', mermaidDefinition.value)
        if (mermaidContainer.value) {
            mermaidContainer.value.innerHTML = '<p>流程图加载失败，请检查控制台错误信息</p>'
        }
    }
}

// 监听 flowNodes 变化，重新渲染图表
watch(
    () => props.flowNodes,
    () => {
        initializeMermaid()
    },
    { deep: true }
)

onMounted(() => {
    initializeMermaid()
})

onUnmounted(() => {
    // 清理资源
    if (mermaidContainer.value) {
        mermaidContainer.value.innerHTML = ''
    }
})
</script>

<style lang="scss" scoped>
.mermaid-flow {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20px;
    background: #fafafa;
    border-radius: 8px;
    border: 1px solid #e0e0e0;
}

.mermaid-content {
    width: 100%;
    max-width: 100%;
    overflow: auto;
    display: flex;
    justify-content: center;
    align-items: center;

    :deep(svg) {
        max-width: 100%;
        height: auto;
        display: block;
        margin: 0 auto;
    }

    // 确保图表容器居中
    :deep(.mermaid) {
        text-align: center;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    // 自定义节点样式
    :deep(.node) {
        font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
        font-size: 16px;
        text-align: center;
    }

    // 决策节点样式
    :deep(.node.diamond) {
        transform: rotate(45deg);
    }

    // 连接线样式
    :deep(.edgePath .path) {
        stroke-width: 2px;
    }

    // 箭头样式
    :deep(.arrowheadPath) {
        fill: #666;
    }

    // foreignObject 内容居中
    :deep(foreignObject) {
        display: flex;
        align-items: center;
        justify-content: center;
    }
}
</style>
