import { createVNode, render } from 'vue'
import serviceFacility from './YHZTooltip.vue'

const UIMap = {
  serviceFacility
}

class ImageMarkTooltip {
  constructor({ key }) {
    this.key = key
    this.instance = null
    this.container = null
    this.entity = null
    this.root = null
  }

  // 显示 tooltip
  show(options = {}) {
    // 销毁之前的实例
    this.close()

    // 创建容器
    this.container = document.createElement('div')
    this.container.className = 'tooltip-service-container'
    this.root = document.querySelector('.cockpit-main')
    this.root.appendChild(this.container)

    this.entity = options.entity

    const UIInstance = UIMap[this.key]

    // 创建 VNode
    const vnode = createVNode(UIInstance, {
      visible: true,
      position: options.position || { x: 0, y: 0 },
      data: options.data || {},
      loading: options.loading || false,
      error: options.error || '',
      onClose: () => {
        this.close()
      }
    })

    // 渲染到容器
    render(vnode, this.container)
    this.instance = vnode.component
    if(this.instance.exposed?.init) {
      this.instance.exposed.init()
    }
    return this.instance
  }

  updatePosition(position) {
    if (this.instance) {
      this.instance.props.position = position
      this.instance.update()
    }
  }

  // 更新 tooltip 内容
  update(options) {
    if (this.instance) {
      this.instance.props = {
        ...this.instance.props,
        ...options
      }
    }
  }

  // 关闭 tooltip
  close() {
    if (this.container) {
      render(null, this.container)
      this.root.removeChild(this.container)
      this.container = null
      this.instance = null
    }
  }
}


export const newImageMarkTooltip = ({ key }) => {
  return new ImageMarkTooltip({ key })
}