<template>
  <div>
    <a-form layout="vertical" :rules="rules" size="small" :model="formData">
      <a-form-item :label="isProcess ? '流程标识' : '节点ID'"  name="id">
        <a-input 
          :value="formData.id" 
          @change="(e) => handleInputChange('id', e.target.value)" 
          :disabled="!isProcess" 
        />
      </a-form-item>
      
      <a-form-item  :label="isProcess ? '流程名称' : '节点名称'"  name="name">
        <a-input 
          :value="formData.name" 
          @change="(e) => handleInputChange('name', e.target.value)" 
          @blur="() => updateElementTask('name')"
        />
      </a-form-item>
      
      <!-- 流程的基础属性 -->
      <template v-if="isProcess">
        <a-form-item label="流程分类" name="processCategory">
          <a-select
            :value="formData.processCategory"
            placeholder="请选择流程分类"
            @change="(value) => handleSelectChange('processCategory', value)"
          >
            <a-select-option
              v-for="dict in dictData.sys_process_category"
              :key="dict.value"
              :value="dict.value"
            >
              {{ dict.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </template>
      
      <a-form-item 
        v-if="isSubProcess" 
        label="状态"
      >
        <a-switch
          :checked="formData.isExpanded"
          checked-children="展开"
          un-checked-children="折叠"
          @change="(checked) => handleSwitchChange('isExpanded', checked)"
        />
      </a-form-item>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, reactive, onMounted, computed, toRaw, isProxy } from 'vue'

import { Form, message } from 'ant-design-vue'
import { StrUtil } from '../common/StrUtil'
import { useModelerStore } from '../store/modeler-store'

interface DictItem {
  value: string
  label: string
}

interface FormData {
  id?: string
  name?: string
  processCategory?: string
  isExpanded?: boolean
  elementType?: string
}

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

const useForm = Form.useForm
const modelerStore = useModelerStore()
const isUpdating = ref(false)
const currentElementId = ref('')

// 使用普通对象而不是响应式对象来存储表单数据
const formData = reactive<FormData>({})

// 计算属性
const isProcess = computed(() => formData.elementType === 'bpmn:Process')
const isSubProcess = computed(() => formData.elementType === 'bpmn:SubProcess')

// 表单验证规则
const rules = reactive({
  id: [
    { required: true, message: '节点Id 不能为空', trigger: 'blur' },
  ],
  name: [
    { required: true, message: '节点名称不能为空', trigger: 'blur' },
  ],
})

// 字典数据
const dictData = reactive({
  sys_process_category: [] as DictItem[]
})

// 监听 id 变化
watch(() => props.id, (newVal) => {
  if (StrUtil.isNotBlank(newVal)) {
    resetTaskForm()
  }
}, { immediate: true })

// 监听当前选中的元素变化
watch(() => modelerStore.element, (newElement) => {
  if (newElement && newElement.id !== currentElementId.value) {
    currentElementId.value = newElement.id
    resetTaskForm()
  }
})

// 重置表单 - 避免复制整个 businessObject
const resetTaskForm = () => {
  if (modelerStore.element && modelerStore.element.businessObject) {
    const businessObject = modelerStore.element.businessObject
    
    // 只复制需要的属性，避免响应式代理问题
    formData.id = businessObject.id || ''
    formData.name = businessObject.name || ''
    formData.processCategory = businessObject.processCategory || ''
    formData.isExpanded = businessObject.isExpanded || false
    formData.elementType = businessObject.$type || ''
  }
}

// 处理输入框变化
const handleInputChange = (key: string, value: any) => {
  formData[key] = value
  if (key === 'name') {
    // 名称实时更新
    updateElementTask(key)
  }
}

// 处理选择框变化
const handleSelectChange = (key: string, value: any) => {
  formData[key] = value
  updateElementTask(key)
}

// 处理开关变化
const handleSwitchChange = (key: string, checked: boolean) => {
  formData[key] = checked
  updateElementTask(key)
}

// 安全的属性更新方法
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)
    }

    // 关键修改：必须使用 diagram element（图形元素），而不是 businessObject
    // bpmn-js 要求通过图形元素来更新属性，因为它需要同时处理业务对象和图形信息
    modeling.updateProperties(targetElement, properties)
    return true
    
  } catch (error) {
    console.error('更新属性失败:', error)
    message.error('更新失败')
    return false
  }
}

// 更新元素属性
const updateElementTask = (key: string) => {
  if (isUpdating.value) return
  isUpdating.value = true
 
  try {
    const value = formData[key]
    
    // 特殊处理 ID 更新
    if (key === 'id') {
      if (isProcess.value) {
        const success = safeUpdateProperties(modelerStore.element, { id: value })
        if (!success) {
          // 恢复原来的值
          resetTaskForm()
        }
      } else {
        message.warning('节点ID不可修改')
        // 恢复原来的值
        resetTaskForm()
        return
      }
    } else {
      // 使用安全的更新方法
      const success = safeUpdateProperties(modelerStore.element, { [key]: value })
      if (!success) {
        // 恢复原来的值
        resetTaskForm()
      }
    }
  } catch (error) {
    console.error('更新属性失败:', error)
    message.error('更新失败')
    // 恢复原来的值
    resetTaskForm()
  } finally {
    isUpdating.value = false
  }
}

// 初始化字典数据
onMounted(() => {
  dictData.sys_process_category = [
    { value: '1', label: '简单流程' },
    { value: '2', label: '复杂流程' },
  ]
  
  if (modelerStore.element) {
    currentElementId.value = modelerStore.element.id
    resetTaskForm()
  }
})
</script>