/* eslint-disable */
export function initDiagnosisDropdown (editor, data, identificationCode, emitFunc) {
  if (typeof editor === 'undefined' || !editor.$) {
    return
  }

  // 确保元素存在
  const diagnosisField = editor.$(identificationCode)

  if (!diagnosisField.length) {
    return
  }

  // 更详细的调试信息
  const fieldElement = diagnosisField[0]

  // 模拟诊断数据
  const mockDiagnosisList = data
  // 生成唯一的下拉框类名
  const dropdownClassName = `diagnosis-dropdown-${identificationCode.replace('#', '')}`
// 创建下拉列表容器 - 使用 Ant Design 风格
  editor.$(`.${dropdownClassName}`).remove() // 修改这里，使用唯一的类名
  const dropdownList = editor.document.createElement('div')
  dropdownList.className = dropdownClassName // 使用唯一的类名

  // 添加 Ant Design 样式，修改样式选择器使用唯一的类名
  const styleElement = editor.document.createElement('style')
  styleElement.textContent = `
    .${dropdownClassName} {
      display: none;
      position: absolute;
      z-index: 999999;
      background: #fff;
      border-radius: 2px;
      box-shadow: 0 3px 6px -4px rgba(0,0,0,.12), 0 6px 16px 0 rgba(0,0,0,.08), 0 9px 28px 8px rgba(0,0,0,.05);
      padding: 4px 0;
      min-width: 300px;
      width: auto;
      max-width: 400px;
      max-height: 256px;
      overflow-y: auto;
    }
    .${dropdownClassName}::-webkit-scrollbar {
      width: 6px;
      height: 6px;
    }
    .${dropdownClassName}::-webkit-scrollbar-thumb {
      background: rgba(0,0,0,.2);
      border-radius: 3px;
    }
    .${dropdownClassName} .ant-list-item {
      padding: 8px 12px;
      cursor: pointer;
      transition: all .3s;
      white-space: nowrap;
    }
    .${dropdownClassName} .ant-list-item:hover {
      background: #f5f5f5;
    }
    .${dropdownClassName} .ant-list-item-content {
      display: flex;
      flex-direction: row;
      align-items: center;
      gap: 8px;
    }
    .${dropdownClassName} .ant-list-item-title {
      color: rgba(0,0,0,.85);
      font-weight: 500;
      font-size: 14px;
      line-height: 1.5715;
      flex: 1;
      min-width: 120px;
    }
    .${dropdownClassName} .ant-list-item-description {
      color: rgba(0,0,0,.45);
      font-size: 12px;
      line-height: 1.5715;
      min-width: 80px;
    }
    .${dropdownClassName} .ant-list-empty {
      padding: 16px;
      color: rgba(0,0,0,.45);
      text-align: center;
      min-width: 200px;
    }
  `
  editor.document.head.appendChild(styleElement)

  // 将下拉列表添加到编辑器文档中
  diagnosisField.after(dropdownList)

  // 获取当前模式
  function getCurrentMode () {
    return editor.option.mode
  }

  // 检查是否允许编辑
  function isEditableMode () {
    const currentMode = getCurrentMode()
    return currentMode === 'form' || currentMode === 'design'
  }

  // 更新下拉列表位置的函数
  function updateDropdownPosition () {
    try {
      // 获取输入框的位置和尺寸
      const fieldRect = fieldElement.getBoundingClientRect()

      // 获取父容器的滚动位置
      const scrollTop = editor.$(editor.document).scrollTop()
      const scrollLeft = editor.$(editor.document).scrollLeft()

      // 计算绝对位置
      const top = fieldRect.bottom + scrollTop
      const left = fieldRect.left + scrollLeft

      // 设置下拉列表位置，不设置宽度，让它自适应内容
      dropdownList.style.cssText = `
        position: absolute;
        top: ${top}px;
        left: ${left}px;
        display: block;
      `
    } catch (error) {
    }
  }

  // 处理输入事件的函数
  function handleInput () {
    if (!isEditableMode()) {
      dropdownList.style.display = 'none'
      return
    }

    const keyword = this.textContent.trim()

    if (keyword && keyword !== '请输入') {
      const results = mockDiagnosisList.filter(item =>
        item.name.toLowerCase().includes(keyword.toLowerCase()) ||
        item.code.toLowerCase().includes(keyword.toLowerCase())
      )

      // 1. 先清空内容
      dropdownList.innerHTML = ''

      // 2. 添加内容
      if (results.length === 0) {
        dropdownList.innerHTML = `
          <div class="ant-list-empty">
            <div style="color: rgba(0,0,0,.25);">
              <svg viewBox="64 64 896 896" width="16" height="16" fill="currentColor">
                <path d="M928 224H768v-56c0-4.4-3.6-8-8-8h-56c-4.4 0-8 3.6-8 8v56H548v-56c0-4.4-3.6-8-8-8h-56c-4.4 0-8 3.6-8 8v56H328v-56c0-4.4-3.6-8-8-8h-56c-4.4 0-8 3.6-8 8v56H96c-17.7 0-32 14.3-32 32v576c0 17.7 14.3 32 32 32h832c17.7 0 32-14.3 32-32V256c0-17.7-14.3-32-32-32zM424 688c0 4.4-3.6 8-8 8h-48c-4.4 0-8-3.6-8-8v-48c0-4.4 3.6-8 8-8h48c4.4 0 8 3.6 8 8v48zm0-136c0 4.4-3.6 8-8 8h-48c-4.4 0-8-3.6-8-8v-48c0-4.4 3.6-8 8-8h48c4.4 0 8 3.6 8 8v48zm136 136c0 4.4-3.6 8-8 8h-48c-4.4 0-8-3.6-8-8v-48c0-4.4 3.6-8 8-8h48c4.4 0 8 3.6 8 8v48zm0-136c0 4.4-3.6 8-8 8h-48c-4.4 0-8-3.6-8-8v-48c0-4.4 3.6-8 8-8h48c4.4 0 8 3.6 8 8v48zm136 136c0 4.4-3.6 8-8 8h-48c-4.4 0-8-3.6-8-8v-48c0-4.4 3.6-8 8-8h48c4.4 0 8 3.6 8 8v48zm0-136c0 4.4-3.6 8-8 8h-48c-4.4 0-8-3.6-8-8v-48c0-4.4 3.6-8 8-8h48c4.4 0 8 3.6 8 8v48z"/>
              </svg>
              <div style="margin-top: 8px;">无匹配结果</div>
            </div>
          </div>
        `
      } else {
        const itemsHtml = results.map(item => `
          <div class="ant-list-item">
            <div class="ant-list-item-content">
              <div class="ant-list-item-title">${item.name}</div>
              <div class="ant-list-item-description">${item.code}</div>
            </div>
          </div>
        `).join('')
        dropdownList.innerHTML = itemsHtml
      }

      // 3. 更新位置并显示
      updateDropdownPosition()
    } else {
      dropdownList.style.display = 'none'
    }
  }

  // 输入法编辑状态处理
  let isCompositing = false

  // 输入法开始
  fieldElement.addEventListener('compositionstart', function (e) {
    isCompositing = true
  })

  // 输入法结束
  fieldElement.addEventListener('compositionend', function (e) {
    isCompositing = false
    handleInput.call(this)
  })

  // 输入事件
  fieldElement.addEventListener('input', function (e) {
    if (!isCompositing) {
      handleInput.call(this)
    }
  })

  // 焦点事件
  fieldElement.addEventListener('focus', function (e) {
  })

  // 失去焦点事件
  fieldElement.addEventListener('blur', function (e) {
    setTimeout(() => {
      if (!this.textContent.trim()) {
        this.textContent = '请输入'
      }
    }, 200)
  })

  // 点击选项事件
  editor.$(dropdownList).on('mousedown', '.ant-list-item', function (e) {
    e.preventDefault()
    e.stopPropagation()
    if (isEditableMode()) {
      const name = editor.$(this).find('.ant-list-item-title').text()
      const code = editor.$(this).find('.ant-list-item-description').text()
      // 根据选中的name和code查找完整数据
      const selectedItem = mockDiagnosisList.find(item =>
        item.name === name && item.code === code
      )

      // 打印完整数据，包括id、name和code
      if (selectedItem) {
        // 使用传入的emit函数触发事件
        if (typeof emitFunc === 'function') {
          // 只传递数据参数，不再传递事件名
          emitFunc(Object.assign(selectedItem,{codeKey :identificationCode.replace(/^#/, '') + '_code'}))
        }
      } else {
        // 如果找不到完整数据，至少打印出已知信息
        // 使用传入的emit函数触发事件，发送部分数据
        if (typeof emitFunc === 'function') {
          // 只传递数据参数，不再传递事件名
          emitFunc({name, code, element: identificationCode})
        }
      }
      fieldElement.textContent = name
      dropdownList.style.display = 'none'
      fieldElement.focus()
    }
  })

  // 点击文档其他区域时隐藏下拉列表，修改选择器
  editor.$(editor.document).on('mousedown', function (e) {
    if (!editor.$(e.target).closest(`.${dropdownClassName}, ${identificationCode}`).length) {
      dropdownList.style.display = 'none'
    }
  })

  // 添加滚动事件监听，实时更新下拉列表位置
  editor.$(editor.window).on('scroll', function () {
    if (dropdownList.style.display !== 'none') {
      updateDropdownPosition()
    }
  })

  editor.$(editor.window).on('resize', function () {
    if (dropdownList.style.display !== 'none') {
      updateDropdownPosition()
    }
  })
}
