import type { App, Directive, DirectiveBinding } from 'vue'
import { getUrlByPath } from '@/servers/base/api/wenjianshangchuan'
import { isExternal } from '@/utils'

// 提取出公共处理方法
async function handleSrcUpdate(el: HTMLImageElement | any, binding: DirectiveBinding) {
  try {
    if (!binding.value) {
      return
    }
    
    if (isExternal(binding.value)) {
      el.src = binding.value
      return
    }

    const res = await getUrlByPath({ path: binding.value })
    el.src = res
  } catch (err) {
    console.error('pathToSrc指令错误:', err)
    el.src = '/images/def_agent.svg'
  }
}

const pathToSrc: Directive<HTMLElement, string> = {
  /**
   * 处理路径转换逻辑
   * @param el 目标元素
   * @param binding 指令绑定值
   */
  async mounted(el: HTMLElement, binding: DirectiveBinding) {
    console.log(`[mounted pathToSrc ] 指令`)
    await handleSrcUpdate(el, binding)
  },

  async updated(el: HTMLElement, binding: DirectiveBinding) {
     console.log(`[updated pathToSrc ] 指令`)
    if (binding.value !== binding.oldValue) {
      await handleSrcUpdate(el, binding)
    }
  }
}

export default {
  install(app: App) {
    app.directive('pathToSrc', pathToSrc)
  }
}