// store/modeler-store.js
import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useModelerStore = defineStore('modeler', () => {
  // 状态
  const modeler = ref(null)
  const modeling = ref(null)
  const moddle = ref(null)
  const canvas = ref(null)
  const bpmnFactory = ref(null)
  const elRegistry = ref(null)
  const element = ref(null) // 当前选中的元素

  // Actions
  const setModeler = (instance) => {
    modeler.value = instance
    modeling.value = instance.get('modeling')
    moddle.value = instance.get('moddle')
    canvas.value = instance.get('canvas')
    bpmnFactory.value = instance.get('bpmnFactory')
    elRegistry.value = instance.get('elementRegistry')
    
    // 添加元素变化监听
    setupElementChangeListener(instance)
  }

  const setElement = (el) => {
    element.value = el
  }

  const updateProperties = (properties) => {
    if (modeling.value && element.value) {
      modeling.value.updateProperties(element.value, properties)
      
      // 特别处理名称更新，触发画布重新渲染
      if (properties.name !== undefined) {
        triggerCanvasRefresh()
      }
    }
  }

  // 设置元素变化监听器
  const setupElementChangeListener = (modelerInstance) => {
    modelerInstance.on('element.changed', ({ element }) => {
      // 当元素属性变化时，可以在这里处理额外的逻辑
      console.log('Element changed:', element.id)
    })
  }

  // 触发画布刷新
  const triggerCanvasRefresh = () => {
    if (modeling.value && element.value) {
      // 强制更新元素标签
      const elementRegistry = modeler.value.get('elementRegistry')
      const graphicsFactory = modeler.value.get('graphicsFactory')
      
      const shape = elementRegistry.get(element.value.id)
      if (shape) {
        // 更新元素的视觉表现
        graphicsFactory.update('shape', shape, element.value)
      }
    }
  }

  return {
    modeler,
    modeling,
    moddle,
    canvas,
    bpmnFactory,
    elRegistry,
    element,
    setModeler,
    setElement,
    updateProperties,
    triggerCanvasRefresh
  }
})