// store/modeler-store-enhanced.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) {
        refreshElementLabel()
      }
    }
  }

  // 设置元素变化监听器
  const setupElementChangeListener = (modelerInstance) => {
    modelerInstance.on('element.changed', ({ element }) => {
      // 可以在这里处理额外的视觉更新
    })
  }

  // 刷新元素标签
  const refreshElementLabel = () => {
    if (!modeler.value || !element.value) return
    
    const elementRegistry = modeler.value.get('elementRegistry')
    const eventBus = modeler.value.get('eventBus')
    const graphicsFactory = modeler.value.get('graphicsFactory')
    
    const shape = elementRegistry.get(element.value.id)
    if (shape) {
      // 触发元素变化事件，强制重新渲染
      eventBus.fire('element.changed', { element: shape })
      
      // 直接更新图形
      graphicsFactory.update('shape', shape, element.value)
    }
  }

  // 强制画布重绘
  const forceCanvasRedraw = () => {
    if (canvas.value) {
      canvas.value.resized()
    }
  }

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