import { ArticleTypeEnum } from '@/constants'
import { useUserStore } from '@/stores'
import { storeToRefs } from 'pinia'
import dayjs from 'dayjs'
/**
 * 页面改变标题
 * @param title
 */
export function changeAppTitle(title: string) {
  document.title = title
}

/**
 * 判断设备，判断是 ios 还是 安卓
 */
export function checkUserAgent() {
  const agent = navigator.userAgent
  const isAndroid = agent.indexOf('Android') > -1 || agent.indexOf('Linux') > -1
  const isIOS = !!agent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
  if (isAndroid) {
    return 'android'
  }
  if (isIOS) {
    return 'ios'
  }
  return ''
}

/**
 * 判断设备，判断是 移动端 还是 PC端
 */
export function isMoible() {
  const UA = navigator.userAgent

  if (window.innerWidth < 500) {
    return true
  }

  return !!/(Android|webOS|iPhone|iPod|tablet|BlackBerry|Mobile)/i.test(UA)
}

/**
 * 将颜色转成 rgb 的 三个数字，逗号分割
 * @param {*} hex 颜色
 * @returns  255,255,255
 */
export function hexToRgb(hex: string) {
  // 去除可能包含的 # 符号
  hex = hex.replace(/^#/, '')

  // 将 HEX 转换为 RGB
  const bigint = parseInt(hex, 16)
  const r = (bigint >> 16) & 255
  const g = (bigint >> 8) & 255
  const b = bigint & 255

  // 返回 RGB 格式的颜色
  return `${r}, ${g}, ${b}`
}

// 当前路径是否是企业文化
export function isCulturePath() {
  const path = window.location.pathname
  return path.includes('/culture')
}

// 点击头像跳转用户首页 【实践 专访 问吧】 是 1 实名 其他是 0 匿名
export function jumpToUserHomePage({ userId, type }: { userId: string; type: ArticleTypeEnum }) {
  const userStore = useUserStore()
  const { userInfo } = storeToRefs(userStore)
  const isSelf = userInfo.value.userId === userId
  if (isSelf) {
    window.open(`/userPage/selfPublish`)
  } else {
    let isReal = 0
    if (
      type === ArticleTypeEnum.PRACTICE ||
      type === ArticleTypeEnum.INTERVIEW ||
      type === ArticleTypeEnum.QUESTION
    ) {
      isReal = 1
    }
    window.open(`/otherUserPage/${userId}/${isReal}`)
  }
}

// 根据文章类型跳到对应的文章详情页面
export function jumpToArticleDetailPage({ type, id }: { type: ArticleTypeEnum; id: number }) {
  if (type === ArticleTypeEnum.VIDEO) {
    window.open(`/videoDetail/${id}`)
  } else if (type === ArticleTypeEnum.QUESTION) {
    window.open(`/questionDetail/${id}`)
  } else {
    window.open(`/articleDetail/${id}`)
  }
}

// 根据oss视频链接获取视频元信息
export function getVideoMetadata(url: string): Promise<{
  duration: string
  resolution: string
}> {
  return new Promise((resolve, reject) => {
    const video = document.createElement('video')
    video.src = url
    video.preload = 'metadata'
    video.addEventListener('loadedmetadata', () => {
      const duration = formatDuration(video.duration)
      const resolution = `${video.videoWidth}x${video.videoHeight}`

      resolve({
        duration,
        resolution,
      })
    })
    video.addEventListener('error', () => {
      reject(new Error('视频加载失败'))
    })
  })
}

// 格式化视频时长
export function formatDuration(seconds: number): string {
  const mins = Math.floor(seconds / 60)
  const secs = Math.floor(seconds % 60)
  return `${mins}:${secs.toString().padStart(2, '0')}`
}

// 处理秒级时间戳 把当前秒级时间戳 转换成 当前 23:59:59 的秒级时间戳
export function formatSeconds(seconds: number): number
export function formatSeconds(seconds: string): string
export function formatSeconds(seconds: string | number) {
  const res = dayjs.unix(Number(seconds)).endOf('day').unix()
  return typeof seconds === 'number' ? res : res.toString()
}
