<template>
  <div v-if="isReady">
    <a-form
      layout="vertical"
      size="small"
      @submit.prevent
    >
      <a-form-item>
        <template #label>
          <span>
            流转类型
            <a-tooltip placement="top">
              <template #title>
                <div style="max-width: 300px">
                  普通流转路径：流程执行过程中，一个元素被访问后，会沿着其所有出口顺序流继续执行。
                  <br />默认流转路径：只有当没有其他顺序流可以选择时，才会选择默认顺序流作为活动的出口顺序流。流程会忽略默认顺序流上的条件。
                  <br />条件流转路径：是计算其每个出口顺序流上的条件。当条件计算为true时，选择该出口顺序流。如果该方法选择了多条顺序流，则会生成多个执行，流程会以并行方式继续。
                </div>
              </template>
              <question-circle-outlined />
            </a-tooltip>
          </span>
        </template>
        <a-select
          v-model:value="bpmnFormData.type"
          @change="handleFlowTypeChange"
        >
          <a-select-option value="normal">普通流转路径</a-select-option>
          <a-select-option value="default">默认流转路径</a-select-option>
          <a-select-option value="condition">条件流转路径</a-select-option>
        </a-select>
      </a-form-item>
      
      <a-form-item 
        label="条件格式" 
        v-if="bpmnFormData.type === 'condition'" 
        key="condition"
      >
        <a-select v-model:value="bpmnFormData.conditionType" @change="handleConditionTypeChange">
          <a-select-option value="expression">表达式</a-select-option>
          <a-select-option value="script">脚本</a-select-option>
        </a-select>
      </a-form-item>
      
      <a-form-item 
        label="表达式" 
        v-if="bpmnFormData.type === 'condition' && bpmnFormData.conditionType === 'expression'" 
        key="express"
      >
        <a-input 
          v-model:value="bpmnFormData.body" 
          allow-clear 
          @change="debouncedUpdateFlowCondition" 
          placeholder="请输入条件表达式"
        />
      </a-form-item>
      
      <template v-if="bpmnFormData.type === 'condition' && bpmnFormData.conditionType === 'script'">
        <a-form-item label="脚本语言" key="language">
          <a-input 
            v-model:value="bpmnFormData.language" 
            allow-clear 
            @change="debouncedUpdateFlowCondition" 
            placeholder="如：groovy, javascript"
          />
        </a-form-item>
        
        <a-form-item label="脚本类型" key="scriptType">
          <a-select v-model:value="bpmnFormData.scriptType" @change="handleScriptTypeChange">
            <a-select-option value="inlineScript">内联脚本</a-select-option>
            <a-select-option value="externalScript">外部脚本</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item 
          label="脚本" 
          v-if="bpmnFormData.scriptType === 'inlineScript'" 
          key="body"
        >
          <a-textarea 
            v-model:value="bpmnFormData.body" 
            allow-clear 
            @change="debouncedUpdateFlowCondition" 
            placeholder="请输入脚本内容"
            :rows="4"
          />
        </a-form-item>
        
        <a-form-item 
          label="资源地址" 
          v-if="bpmnFormData.scriptType === 'externalScript'" 
          key="resource"
        >
          <a-input 
            v-model:value="bpmnFormData.resource" 
            allow-clear 
            @change="debouncedUpdateFlowCondition" 
            placeholder="请输入外部脚本资源地址"
          />
        </a-form-item>
      </template>
    </a-form>
  </div>
  <div v-else class="loading-placeholder">
    加载中...
  </div>
</template>
<script lang="ts" setup>
import { ref, watch, reactive, onMounted, onUnmounted, nextTick } from 'vue'
import { QuestionCircleOutlined } from '@ant-design/icons-vue'
import { StrUtil } from "../common/StrUtil"
import { useModelerStore } from '../store/modeler-store'
import debounce from 'lodash-es/debounce'

interface BpmnFormData {
  type: string
  conditionType: string
  scriptType: string
  body: string
  language: string
  resource: string
  [key: string]: any
}

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

// 就绪状态，防止组件在数据准备好之前渲染
const isReady = ref(false)
const isUpdating = ref(false)

// 初始化响应式数据
const bpmnFormData = reactive<BpmnFormData>({
  type: 'normal',
  conditionType: '',
  scriptType: '',
  body: '',
  language: '',
  resource: ''
})

const bpmnElementSource = ref<any>(null)
const bpmnElementSourceRef = ref<any>(null)

// 使用 store
const modelerStore = useModelerStore()

// 更新流程条件函数 - 需要在防抖函数之前声明
const updateFlowCondition = () => {
  if (!isReady.value || isUpdating.value) {
    return
  }
  
  // 添加空值检查
  if (!modelerStore?.element) {
    console.warn('Modeler element is not available')
    return
  }
  
  if (!modelerStore.moddle || !modelerStore.modeling) {
    console.warn('Modeler moddle or modeling is not available')
    return
  }
  
  const { conditionType, scriptType, body, resource, language } = bpmnFormData
  let condition
  
  if (conditionType === "expression") {
    condition = modelerStore.moddle.create("bpmn:FormalExpression", { body })
  } else if (conditionType === "script") {
    if (scriptType === "inlineScript") {
      condition = modelerStore.moddle.create("bpmn:FormalExpression", { body, language })
    } else {
      condition = modelerStore.moddle.create("bpmn:FormalExpression", { resource, language })
    }
  } else {
    // 没有条件类型，直接返回
    return
  }
  
  try {
    modelerStore.modeling.updateProperties(modelerStore.element, { 
      conditionExpression: condition 
    })
  } catch (error) {
    console.error('Error updating flow condition:', error)
  }
}

// 创建防抖函数 - 现在updateFlowCondition已经声明了
const debouncedUpdateFlowCondition = debounce(updateFlowCondition, 300)

// 组件挂载时初始化
onMounted(() => {
  console.log('ConditionPanel mounted')
  isReady.value = true
})

// 组件卸载时清理
onUnmounted(() => {
  console.log('ConditionPanel unmounting')
  isReady.value = false
  isUpdating.value = false
  
  // 清理防抖函数
  debouncedUpdateFlowCondition.cancel()
  
  // 重置数据
  Object.keys(bpmnFormData).forEach(key => {
    if (key !== 'type') {
      bpmnFormData[key] = ''
    }
  })
  bpmnFormData.type = 'normal'
})

// 监听 id 变化
watch(() => props.id, (newVal, oldVal) => {
  console.log('ID changed from', oldVal, 'to', newVal)
  if (StrUtil.isNotBlank(newVal)) {
    // 确保组件就绪后再重置
    nextTick(() => {
      if (isReady.value) {
        resetFlowCondition()
      }
    })
  } else {
    // id 为空时重置表单
    resetFormData()
  }
}, { immediate: true })

// 重置表单数据
const resetFormData = () => {
  Object.assign(bpmnFormData, {
    body: '',
    type: 'normal',
    conditionType: '',
    scriptType: '',
    language: '',
    resource: ''
  })
  bpmnElementSource.value = null
  bpmnElementSourceRef.value = null
}

// 重置流程条件
const resetFlowCondition = () => {
  if (!isReady.value || isUpdating.value) {
    return
  }
  
  isUpdating.value = true
  
  try {
    resetFormData()
    
    // 添加空值检查
    if (!modelerStore || !modelerStore.element) {
      console.warn('Modeler store or element is not available')
      isUpdating.value = false
      return
    }
    
    if (!modelerStore.element.businessObject) {
      console.warn('Modeler element businessObject is not available')
      isUpdating.value = false
      return
    }
    
    bpmnElementSource.value = modelerStore.element.source
    bpmnElementSourceRef.value = modelerStore.element.businessObject.sourceRef
    
    // 检查默认路径
    if (bpmnElementSourceRef.value && 
        bpmnElementSourceRef.value.default && 
        bpmnElementSourceRef.value.default.id === modelerStore.element.id) {
      bpmnFormData.type = "default"
    } else if (!modelerStore.element.businessObject.conditionExpression) {
      bpmnFormData.type = "normal"
    } else {
      // 带条件
      const conditionExpression = modelerStore.element.businessObject.conditionExpression
      Object.assign(bpmnFormData, {...conditionExpression, type: "condition"})
      
      // resource 可直接标识是否是外部资源脚本
      if (bpmnFormData.resource) {
        bpmnFormData.conditionType = "script"
        bpmnFormData.scriptType = "externalScript"
      } else if (conditionExpression.language) {
        bpmnFormData.conditionType = "script"
        bpmnFormData.scriptType = "inlineScript"
      } else {
        bpmnFormData.conditionType = "expression"
      }
    }
  } catch (error) {
    console.error('Error resetting flow condition:', error)
  } finally {
    isUpdating.value = false
  }
}

// 处理流程类型变化
const handleFlowTypeChange = (flowType: string) => {
  if (isUpdating.value) return
  
  isUpdating.value = true
  try {
    bpmnFormData.type = flowType
    updateFlowType(flowType)
  } catch (error) {
    console.error('Error updating flow type:', error)
  } finally {
    setTimeout(() => {
      isUpdating.value = false
    }, 100)
  }
}

// 处理条件类型变化
const handleConditionTypeChange = (conditionType: string) => {
  if (isUpdating.value) return
  
  bpmnFormData.conditionType = conditionType
  // 重置相关字段
  if (conditionType === 'expression') {
    bpmnFormData.scriptType = ''
    bpmnFormData.language = ''
    bpmnFormData.resource = ''
  } else if (conditionType === 'script') {
    bpmnFormData.scriptType = 'inlineScript'
  }
  debouncedUpdateFlowCondition()
}

// 处理脚本类型变化
const handleScriptTypeChange = (scriptType: string) => {
  if (isUpdating.value) return
  
  bpmnFormData.scriptType = scriptType
  // 重置相关字段
  if (scriptType === 'inlineScript') {
    bpmnFormData.resource = ''
  } else if (scriptType === 'externalScript') {
    bpmnFormData.body = ''
  }
  debouncedUpdateFlowCondition()
}

// 更新流程类型
const updateFlowType = (flowType: string) => {
  // 添加空值检查
  if (!modelerStore?.element) {
    console.warn('Modeler element is not available')
    return
  }
  
  if (!modelerStore.moddle || !modelerStore.modeling) {
    console.warn('Modeler moddle or modeling is not available')
    return
  }
  
  // 正常条件类
  if (flowType === "condition") {
    const flowConditionRef = modelerStore.moddle.create("bpmn:FormalExpression")
    modelerStore.modeling.updateProperties(modelerStore.element, {
      conditionExpression: flowConditionRef
    })
    // 设置默认条件类型
    bpmnFormData.conditionType = 'expression'
    return
  }
  
  // 默认路径
  if (flowType === "default") {
    modelerStore.modeling.updateProperties(modelerStore.element, {
      conditionExpression: null
    })
    if (bpmnElementSource.value) {
      modelerStore.modeling.updateProperties(bpmnElementSource.value, {
        default: modelerStore.element
      })
    }
    // 清空条件格式
    bpmnFormData.conditionType = ''
    bpmnFormData.scriptType = ''
    bpmnFormData.body = ''
    bpmnFormData.language = ''
    bpmnFormData.resource = ''
    return
  }
  
  // 清空条件格式
  bpmnFormData.conditionType = ''
  bpmnFormData.scriptType = ''
  bpmnFormData.body = ''
  bpmnFormData.language = ''
  bpmnFormData.resource = ''
  
  // 正常路径，如果来源节点的默认路径是当前连线时，清除父元素的默认路径配置
  if (bpmnElementSourceRef.value?.default && 
      bpmnElementSourceRef.value.default.id === modelerStore.element.id && 
      bpmnElementSource.value) {
    modelerStore.modeling.updateProperties(bpmnElementSource.value, {
      default: null
    })
  }
  
  modelerStore.modeling.updateProperties(modelerStore.element, {
    conditionExpression: null
  })
}
</script>

<style scoped>
.loading-placeholder {
  padding: 20px;
  text-align: center;
  color: #999;
}
</style>