<template>
  <!-- 外部链接 -->
  <view v-if="isExternal" class="im-link" :class="[
    `im-link--${type}`,
    `im-link--${size}`,
    `im-link--${underline}`,
    { 'im-link--disabled': disabled },
    { 'im-link--loading': loading },
    customClass
  ]" :style="[customStyle, linkStyle]" @tap="handleExternalLink">
    <!-- 加载状态 -->
    <view v-if="loading" class="im-link__loading">
      <slot name="loading">
        <view class="im-link__loading-icon"></view>
      </slot>
    </view>

    <!-- 前置图标 -->
    <view v-if="icon || $slots.icon" class="im-link__icon">
      <slot name="icon">
        <text v-if="icon" class="im-link__icon-text">{{ icon }}</text>
      </slot>
    </view>

    <!-- 链接内容 -->
    <text class="im-link__text">{{ text || href }}</text>

    <!-- 后置图标 -->
    <view v-if="showArrow || $slots.arrow" class="im-link__arrow">
      <slot name="arrow">
        <text v-if="showArrow" class="im-link__arrow-text">→</text>
      </slot>
    </view>

    <!-- 角标 -->
    <im-badge v-if="badge" class="im-link__badge" :type="badgeType" :value="badgeValue" :max="badgeMax" :dot="badgeDot"
      :position="badgePosition" />
  </view>

  <!-- 内部链接 -->
  <navigator v-else class="im-link" :class="[
    `im-link--${type}`,
    `im-link--${size}`,
    `im-link--${underline}`,
    { 'im-link--disabled': disabled },
    { 'im-link--loading': loading },
    customClass
  ]" :style="[customStyle, linkStyle]" :url="href" :open-type="openType" :delta="delta" :hover-class="hoverClass"
    :hover-start-time="hoverStartTime" :hover-stay-time="hoverStayTime" @click="handleClick" @success="handleSuccess"
    @fail="handleFail" @complete="handleComplete">
    <!-- 加载状态 -->
    <view v-if="loading" class="im-link__loading">
      <slot name="loading">
        <view class="im-link__loading-icon"></view>
      </slot>
    </view>

    <!-- 前置图标 -->
    <view v-if="icon || $slots.icon" class="im-link__icon">
      <slot name="icon">
        <text v-if="icon" class="im-link__icon-text">{{ icon }}</text>
      </slot>
    </view>

    <!-- 链接内容 -->
    <text class="im-link__text">{{ text }}</text>

    <!-- 后置图标 -->
    <view v-if="showArrow || $slots.arrow" class="im-link__arrow">
      <slot name="arrow">
        <text v-if="showArrow" class="im-link__arrow-text">→</text>
      </slot>
    </view>

    <!-- 角标 -->
    <im-badge v-if="badge" class="im-link__badge" :type="badgeType" :value="badgeValue" :max="badgeMax" :dot="badgeDot"
      :position="badgePosition" />
  </navigator>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import ImBadge from '../im-badge/im-badge.vue'
import type { LinkProps, LinkEmits } from '../../types/components/link'

// // 定义 Props
// interface Props {
//   // 链接配置
//   href?: string
//   text?: string
//   target?: '_self' | '_blank' | '_parent' | '_top'
//   rel?: string
//   download?: boolean

//   // 导航配置
//   openType?: 'navigate' | 'redirect' | 'switchTab' | 'reLaunch' | 'navigateBack'
//   delta?: number
//   hoverClass?: string
//   hoverStartTime?: number
//   hoverStayTime?: number

//   // 样式配置
//   type?: 'default' | 'primary' | 'success' | 'warning' | 'error' | 'info'
//   size?: 'small' | 'medium' | 'large'
//   underline?: 'none' | 'hover' | 'always'
//   disabled?: boolean
//   loading?: boolean

//   // 图标配置
//   icon?: string
//   showArrow?: boolean

//   // 角标配置
//   badge?: boolean
//   badgeType?: 'primary' | 'success' | 'warning' | 'danger' | 'info' //'primary' | 'success' | 'warning' | 'error' | 'info'
//   badgeValue?: string | number
//   badgeMax?: number
//   badgeDot?: boolean
//   badgePosition?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'

//   // 自定义样式
//   customClass?: string
//   customStyle?: string | Record<string, string>
//   color?: string
//   hoverColor?: string
//   activeColor?: string
//   fontSize?: string | number

//   // 事件配置
//   beforeNavigate?: (url: string) => boolean | Promise<boolean>
// }

// // 定义 Emits
// interface Emits {
//   (e: 'click', event: any): void
//   (e: 'success', event: any): void
//   (e: 'fail', event: any): void
//   (e: 'complete', event: any): void
//   (e: 'before-navigate', url: string): void
//   (e: 'after-navigate', url: string): void
//   (e: 'navigate-error', error: Error): void
// }

// 定义 Props 默认值
const props = withDefaults(defineProps<LinkProps>(), {
  href: '',
  text: '',
  target: '_self',
  rel: 'noopener noreferrer',
  download: false,

  openType: 'navigate',
  delta: 1,
  hoverClass: 'im-link--hover',
  hoverStartTime: 50,
  hoverStayTime: 400,

  type: 'primary',
  size: 'medium',
  underline: 'hover',
  disabled: false,
  loading: false,

  icon: '',
  showArrow: false,

  badge: false,
  badgeType: 'danger',
  badgeValue: '',
  badgeMax: 99,
  badgeDot: false,
  badgePosition: 'top-right',

  customClass: '',
  customStyle: () => ({}),
  color: '',
  hoverColor: '',
  activeColor: '',
  fontSize: '',

  beforeNavigate: () => true
})

const emit = defineEmits<LinkEmits>()

// 判断是否为外部链接
const isExternal = computed(() => {
  if (!props.href) return false

  return (
    props.href.startsWith('http://') ||
    props.href.startsWith('https://') ||
    props.href.startsWith('//') ||
    props.href.startsWith('mailto:') ||
    props.href.startsWith('tel:')
  )
})

// 链接样式
const linkStyle = computed(() => {
  const style: Record<string, string> = {}

  // 自定义颜色
  if (props.color) {
    style.color = props.color
  }

  // 字体大小
  if (props.fontSize) {
    const fontSize = typeof props.fontSize === 'number' ? `${props.fontSize}rpx` : props.fontSize
    style.fontSize = fontSize
  }

  // 禁用状态
  if (props.disabled) {
    style.opacity = '0.6'
    style.cursor = 'not-allowed'
  }

  // 加载状态
  if (props.loading) {
    style.opacity = '0.8'
  }

  return style
})

// 处理点击事件
const handleClick = async (event: any) => {
  if (props.disabled || props.loading) {
    return
  }

  emit('click', event)

  // 执行前置导航钩子
  if (props.beforeNavigate) {
    try {
      const shouldNavigate = await Promise.resolve(props.beforeNavigate(props.href))
      if (!shouldNavigate) {
        return
      }
    } catch (error) {
      console.error('beforeNavigate error:', error)
      return
    }
  }

  emit('before-navigate', props.href)

  // 如果是外部链接，已经在 handleExternalLink 中处理
  if (!isExternal.value) {
    // 内部链接由 navigator 组件处理
  }
}

// 处理外部链接点击
const handleExternalLink = async (event: any) => {
  if (props.disabled || props.loading) {
    return
  }

  emit('click', event)

  // 执行前置导航钩子
  if (props.beforeNavigate) {
    try {
      const shouldNavigate = await Promise.resolve(props.beforeNavigate(props.href))
      if (!shouldNavigate) {
        return
      }
    } catch (error) {
      console.error('beforeNavigate error:', error)
      return
    }
  }

  emit('before-navigate', props.href)

  try {
    // 处理不同类型的链接
    if (props.href.startsWith('mailto:')) {
      // 邮箱链接
      window.location.href = props.href
    } else if (props.href.startsWith('tel:')) {
      // 电话链接
      window.location.href = props.href
    } else if (props.download) {
      // 下载链接
      window.open(props.href, props.target, `rel=${props.rel}`)
    } else {
      // 普通外部链接
      if (props.target === '_blank') {
        window.open(props.href, '_blank', `rel=${props.rel}`)
      } else {
        window.location.href = props.href
      }
    }

    emit('after-navigate', props.href)
  } catch (error) {
    console.error('打开链接失败:', error)
    emit('navigate-error', error as Error)
  }
}

// 处理成功事件
const handleSuccess = (event: any) => {
  emit('success', event)
}

// 处理失败事件
const handleFail = (event: any) => {
  emit('fail', event)
}

// 处理完成事件
const handleComplete = (event: any) => {
  emit('complete', event)
}

// 导航到指定页面
const navigateTo = (options: {
  url: string
  openType?: 'navigate' | 'navigateBack' | 'redirect' | 'switchTab' | 'reLaunch'
  delta?: number
}) => {
  if (props.disabled || props.loading) {
    return false
  }

  const { url, openType = 'navigate', delta = 1 } = options

  try {
    switch (openType) {
      case 'navigate':
        uni.navigateTo({ url })
        break
      case 'redirect':
        uni.redirectTo({ url })
        break
      case 'switchTab':
        uni.switchTab({ url })
        break
      case 'reLaunch':
        uni.reLaunch({ url })
        break
      case 'navigateBack':
        uni.navigateBack({ delta })
        break
    }
    return true
  } catch (error) {
    console.error('导航失败:', error)
    return false
  }
}

// 暴露方法
defineExpose({
  navigateTo
})
</script>

<style lang="scss" scoped>
.im-link {
  display: inline-flex;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  text-decoration: none;
  user-select: none;

  // 尺寸
  &--small {
    padding: 8rpx 16rpx;
    font-size: 24rpx;

    .im-link__icon {
      margin-right: 8rpx;
    }

    .im-link__arrow {
      margin-left: 8rpx;
    }
  }

  &--medium {
    padding: 12rpx 24rpx;
    font-size: 28rpx;

    .im-link__icon {
      margin-right: 12rpx;
    }

    .im-link__arrow {
      margin-left: 12rpx;
    }
  }

  &--large {
    padding: 16rpx 32rpx;
    font-size: 32rpx;

    .im-link__icon {
      margin-right: 16rpx;
    }

    .im-link__arrow {
      margin-left: 16rpx;
    }
  }

  // 类型
  &--default {
    color: #606266;

    &:not(.im-link--disabled):not(.im-link--loading) {
      &:hover {
        color: #409eff;
      }

      &:active {
        color: #337ecc;
      }
    }
  }

  &--primary {
    color: #409eff;

    &:not(.im-link--disabled):not(.im-link--loading) {
      &:hover {
        color: #66b1ff;
      }

      &:active {
        color: #337ecc;
      }
    }
  }

  &--success {
    color: #67c23a;

    &:not(.im-link--disabled):not(.im-link--loading) {
      &:hover {
        color: #85ce61;
      }

      &:active {
        color: #529b2d;
      }
    }
  }

  &--warning {
    color: #e6a23c;

    &:not(.im-link--disabled):not(.im-link--loading) {
      &:hover {
        color: #ebb563;
      }

      &:active {
        color: #b88230;
      }
    }
  }

  &--error {
    color: #f56c6c;

    &:not(.im-link--disabled):not(.im-link--loading) {
      &:hover {
        color: #f78989;
      }

      &:active {
        color: #c45656;
      }
    }
  }

  &--info {
    color: #909399;

    &:not(.im-link--disabled):not(.im-link--loading) {
      &:hover {
        color: #a6a9ad;
      }

      &:active {
        color: #73767a;
      }
    }
  }

  // 下划线
  &--underline-none {
    text-decoration: none;
  }

  &--underline-hover {
    text-decoration: none;

    &:hover {
      text-decoration: underline;
    }
  }

  &--underline-always {
    text-decoration: underline;
  }

  // 禁用状态
  &--disabled {
    cursor: not-allowed;
    opacity: 0.6;
  }

  // 加载状态
  &--loading {
    cursor: wait;
    opacity: 0.8;
  }

  // 悬停效果
  &--hover {
    opacity: 0.8;
  }
}

.im-link__loading {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  margin-right: 8rpx;

  &-icon {
    width: 20rpx;
    height: 20rpx;
    border: 2rpx solid currentColor;
    border-top-color: transparent;
    border-radius: 50%;
    animation: im-link-rotate 1s linear infinite;
  }
}

.im-link__icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;

  &-text {
    font-size: inherit;
    line-height: 1;
  }
}

.im-link__text {
  line-height: 1.4;
  white-space: nowrap;
}

.im-link__arrow {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  transition: transform 0.3s;

  .im-link:hover & {
    transform: translateX(4rpx);
  }

  &-text {
    font-size: inherit;
    line-height: 1;
  }
}

.im-link__badge {
  position: absolute;
  top: -8rpx;
  right: -8rpx;
}

@keyframes im-link-rotate {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}
</style>