<template>
  <component :is="type" v-bind="linkProps()">
    <slot/>
  </component>
</template>

<script setup>
import {isExternal} from '@/utils/validate'

const props = defineProps({
  to: {
    type: [String, Object],
    required: true
  }
})

// 判断是否需要新窗口打开（内部页面）
const needNewWindow = computed(() => {
  
  // 获取路径字符串
  const path = typeof props.to === 'string' ? props.to : props.to.path
  // 规定：路径以 /new-window/ 开头的就在新窗口打开
  const list = ['/inspection/cockpit']
  return list.includes(path)
})

const isExt = computed(() => {
  return isExternal(props.to)
})

const type = computed(() => {
  if (isExt.value) {
    return 'a'
  }
  return 'router-link'
})

function linkProps() {
  if (isExt.value) {
    return {
      href: props.to,
      target: '_blank',
      rel: 'noopener'
    }
  }

  if (needNewWindow.value) {
    // 如果是对象，需要拼接路径
    const fullPath = typeof props.to === 'string' 
      ? props.to 
      : props.to.path + (props.to.query ? '?' + new URLSearchParams(props.to.query).toString() : '')
    return {
      href: fullPath,
      target: '_blank',
      rel: 'noopener'
    }
  }

  return {
    to: props.to
  }
}
</script>
