<template>
  <div>
    <a-form layout="vertical" size="small" @submit.prevent>
      <a-form-item label="流程表单">
        <a-select
          v-model:value="bpmnFormData.formKey"
          allow-clear
          placeholder="挂载节点表单"
          @change="updateElementFormKey"
          :loading="loading"
        >
          <a-select-option
            v-for="item in formList"
            :key="item.formId"
            :value="item.formId"
          >
            {{ item.formName }}
          </a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, onMounted, reactive, nextTick, toRaw, isProxy } from 'vue'
import { listAllForm } from '../api/form'
import { StrUtil } from "../common/StrUtil"
import { useModelerStore } from '../store/modeler-store'

interface FormItem {
  formId: string
  formName: string
  value?: string
  [key: string]: any
}

interface BpmnFormData {
  formKey?: string
}

const props = defineProps<{
  id: string
}>()

// 响应式数据
const modelerStore = useModelerStore()
const formList = ref<FormItem[]>([])
const bpmnFormData = reactive<BpmnFormData>({})
const loading = ref(false)

// 使用 nextTick 确保组件完全挂载后再执行初始化
onMounted(() => {
  nextTick(() => {
    if (StrUtil.isNotBlank(props.id)) {
      getListForm()
      resetFlowForm()
    }
  })
})

// 监听 id 变化，但不再使用 immediate: true
watch(() => props.id, (newVal) => {
  if (StrUtil.isNotBlank(newVal)) {
    getListForm()
    resetFlowForm()
  }
})

// 监听当前选中的元素变化
watch(() => modelerStore.element, (newElement) => {
  if (newElement) {
    resetFlowForm()
  }
})

// 重置流程表单
const resetFlowForm = () => {
  if (modelerStore.modeler && modelerStore.element && modelerStore.element.businessObject) {
    bpmnFormData.formKey = modelerStore.element.businessObject.formKey || ''
  }
}

// 安全的属性更新方法
const safeUpdateProperties = (element: any, properties: Record<string, any>) => {
  if (!modelerStore.modeler || !element) {
    console.warn('Modeler or element not available')
    return false
  }

  try {
    const modeling = modelerStore.modeler.get('modeling')
    if (!modeling) {
      console.error('Modeling module not found')
      return false
    }

    // 获取原始对象，避免 Vue 响应式代理问题
    let targetElement = element
    
    // 如果是 Vue 代理对象，获取原始对象
    if (isProxy(element)) {
      targetElement = toRaw(element)
    }

    // 执行更新
    modeling.updateProperties(targetElement, properties)
    return true
    
  } catch (error) {
    console.error('更新属性失败:', error)
    return false
  }
}

// 更新元素表单键
const updateElementFormKey = (val: string) => {
  if (!modelerStore.modeler || !modelerStore.element) {
    console.warn('Modeler or element not available')
    return
  }

  try {
    // 使用安全的更新方法
    const success = safeUpdateProperties(modelerStore.element, { formKey: val })
    
    if (success) {
      console.log('表单键更新成功:', val)
    } else {
      console.error('表单键更新失败')
      // 恢复原来的值
      resetFlowForm()
    }
  } catch (error) {
    console.error('更新表单键失败:', error)
    // 恢复原来的值
    resetFlowForm()
  }
}

// 获取表单信息
const getListForm = async () => {
  loading.value = true
  try {
    const res = await listAllForm()
    const formattedData = res.map((item: any) => ({
      ...item,
      formId: item.formId.toString()
    }))
    formList.value = formattedData
  } catch (error) {
    console.error('获取表单列表失败:', error)
  } finally {
    loading.value = false
  }
}
</script>