// 立即执行计时器
import accounting from 'accounting'

const setIntervalImmediately = (fn, duration) => setInterval((() => (fn(), fn))(), duration)

async function needLogin() {
  const route = useRoute()
  const useAuth = useAuthStore()
  const { token } = storeToRefs(useAuth)
  if (!token.value) {
    await navigateTo({
      path: '/login',
      query: {
        redirect: route.fullPath,
        ...route.query
      },
      replace: true
    })
    return
  }
}

function jumpToLoginPage() {
  const route = useRoute()
  navigateTo({
    path: '/login',
    query: {
      redirect: route.path,
      ...route.query
    },
    replace: true
  })
}

function formatImgSrc(srcArr) {
  if (Array.isArray(srcArr) && srcArr.length > 0) {
    return srcArr[0] ?? ''
  }
  return ''
}
function priceToArray(price) {
  if (!price) return ['0', '00']
  const priceStr = price.toString()
  if (!priceStr.includes('.')) {
    return [priceStr, '00']
  }
  return [priceStr.split('.')[0], priceStr.split('.')[1]]
}

function isEmail(email) {
  if (!email) return false
  const value = email.trim()
  if (
    /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(
      value
    )
  ) {
    return true
  }
  return false
}

const isEmptyValue = (value) => {
  if (value == null) return true

  if (Array.isArray(value) && value.length === 0) return true

  if (typeof value === 'object' && Object.keys(value).length === 0) return true

  return false
}

const formatNumber = (n) => {
  let num = Number(n ?? '')

  // 如果数字大于或等于10,000万，则显示为9999w+
  if (num >= 10000 * 10000) {
    return '9999万+'
  }
  // 如果数字大于或等于1万，则转换为以“万”为单位，不四舍五入，最多保留1位小数
  else if (num >= 10000) {
    let w = Math.floor(num / 10000) // 取整，避免四舍五入
    let remainder = num % 10000

    // 计算小数部分并限制为最多两位
    let decimalPart = ''
    if (remainder > 0) {
      // 将余数转换为1位小数，但不进行四舍五入
      decimalPart = ('.' + Math.floor(remainder / 100)).slice(0, 2)
      // 移除结尾的0，如果有的话
      decimalPart = decimalPart.replace(/\.?0+$/, '')
    }

    return `${w}${decimalPart}万`
  }

  // 对于小于1万的数字直接输出
  else {
    // return accounting.formatNumber(num)
  }
}

const transferCount = (num = 0) => {
  if (isNaN(num)) return 0
  if (num > 10000) {
    return (num / 10000).toFixed(1) + 'w'
  } else {
    return num
  }
}
const transferCountChinese = (num = 0) => {
  if (isNaN(num)) return 0
  if (num > 10000) {
    return (num / 10000).toFixed(1) + '万'
  } else {
    return num
  }
}

export {
  setIntervalImmediately,
  needLogin,
  jumpToLoginPage,
  formatImgSrc,
  isEmail,
  formatNumber,
  isEmptyValue,
  priceToArray,
  transferCount,
  transferCountChinese
}
