import { useToast } from '@/utils/modals'
export function loadJs(src: string) {
  return new Promise((resolve, reject) => {
    const script = document.createElement('script')
    script.type = 'text/javascript'
    script.src = src
    document.body.appendChild(script)
    script.onload = () => {
      resolve(true)
    }
    script.onerror = () => {
      reject()
    }
  })
}

/**
 * 处理微信重定向地址
 * @param appid wx公众号id
 * @param href 重定向地址
 * @param scope 微信授权 snsapi_userinfo: 头像等信息授权 snsapi_base: jscode授权
 * @returns 微信授权地址
 */
export function handleWxRedict(
  appid: string,
  href: string,
  scope: string,
  state?: any,
): string {
  console.log(
    `%c>_> appid=>`,
    'color:#ff7b54;font-size:16px;',
    appid,
    href,
    scope,
    state,
  )
  if (state) {
    return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(
      href,
    )}&response_type=code&scope=${scope}&state=${encodeURIComponent(
      state,
    )}#wechat_redirect`
  } else {
    return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(
      href,
    )}&response_type=code&scope=${scope}#wechat_redirect`
  }
}

function addZero(num: number) {
  return num >= 10 ? String(num) : '0' + num
}

/**
 * 秒数时间转换
 * @param seconds 秒数
 * @param format 时间格式
 * @returns HH:mm:ss时间格式
 */
export function secondFormat(seconds: number, format = 'h'): string {
  const hour: string = addZero(Math.floor(seconds / 60 / 60))
  const minute: string = addZero(Math.floor(seconds / 60) % 60)
  const second: string = addZero(seconds % 60)
  if (format === 'h') {
    return `${hour}:${minute}:${second}`
  } else if (format === 'm') {
    return `${minute}:${second}`
  } else {
    return `${second}`
  }
}

export function getQueryString(name: string) {
  const queryList = window.location.href.split('?')
  if (queryList.length < 2) {
    return null
  }
  const getqyinfo: any = queryList[queryList.length - 1] //qycode=1001&qyname=%E4%BC%81%E4%B8%9A%E5%BF%99   截取到参数部分
  const getqys: any = new URLSearchParams('?' + getqyinfo)
  return getqys.get(name)
}

export function initClipboard(name: any) {
  if (name === null) {
    return
  }
  const inputElement = document.createElement('input')
  inputElement.value = name
  document.body.appendChild(inputElement)
  inputElement.select()
  document.execCommand('copy')
  inputElement.remove()
  useToast('复制成功')
}

export function thousandthTranslate(num: any) {
  if (!num) {
    return '0.00'
  }
  if (String(num).includes('.')) {
    if (String(num).split('.')[1].length === 1) {
      return Number(num).toLocaleString() + '0'
    }
    return Number(num).toLocaleString()
  }
  return Number(num).toLocaleString() + '.00'
}
