import { ref } from 'vue'
import { getInput } from '@/utils/flow'

export function useQuote(nodeId) {
  const quoteOptions = ref([])
  const cascaderRefs = ref([])

  const handleTypeChange = (index, formData, type = 'default') => {
    // 根据节点类型处理不同数据源
    // 这里简化为通用逻辑，具体实现需根据实际数据结构调整
    if (formData.nodeParams[index].type === 'input') {
      formData.nodeParams[index].quote = ''
    } else {
      formData.nodeParams[index].input = ''
      const option = getInput(nodeId)
      if (option) quoteOptions.value = option
    }
  }

  const cascaderChange = (value, index, formData, field = 'nodeParams') => {
    const selectedOptions = cascaderRefs.value[index]?.getCheckedNodes(true)
    if (selectedOptions && selectedOptions.length) {
      formData[field][index].quote = value
      formData[field][index].quoteType = selectedOptions[0].data.type
    }
  }

  const visibleChange = (visible, index, currentQuote, formData, field = 'nodeParams') => {
    if (visible) {
      const option = getInput(nodeId)
      if (option) {
        quoteOptions.value = option
        const currentValue = [...currentQuote]
        if (cascaderRefs.value[index] && currentValue.length > 0) {
          setTimeout(() => {
            formData[field][index].quote = []
            setTimeout(() => {
              formData[field][index].quote = currentValue
            }, 0)
          }, 0)
        }
      }
    }
  }

  return {
    quoteOptions,
    cascaderRefs,
    handleTypeChange,
    cascaderChange,
    visibleChange
  }
}