// import FileSaver from "file-saver";
import { ElMessageBox } from 'element-plus'
import dayjs from '@/plugins/dayjs'
import { sys_type, sys_type_study_machine, sys_type_web } from './android'

/**
 * 获取随机数
 * @param length 长度
 * @returns
 */
export const randomString = (length: number) => {
  const len = length || 32
  const STRING_TEMPLATE = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
  const coefficient = STRING_TEMPLATE.length
  let string = ''
  for (let i = 0; i < len; i++) {
    string += STRING_TEMPLATE.charAt(Math.floor(Math.random() * coefficient))
  }
  return string
}

/**
 * @description: 将数组映射为对象
 * @param {*} arr
 * @param {*} key
 * @param {*} value
 * @return {*} {key:value}
 */
export const ArrToObj = (
  arr: anyObj[],
  key = 'code',
  value = 'value',
): { [key: string]: string } => {
  const obj: anyObj = {}
  let i = 0
  for (i; i < arr.length; i++) {
    obj[arr[i][key]] = arr[i][value]
  }
  return obj
}
/**
 * @description: 下载文件
 * @param {anyObj} param1
 * @return {*}
 */
export const downloadFile = (url: string | Blob | File, fileName?: string, type?: number) => {
  if (type) {
    // FileSaver.saveAs(url, fileName);
  } else {
    const link = document.createElement('a')
    link.download = fileName!
    link.href = url as string
    document.body.appendChild(link)
    link.click()
    setTimeout(() => {
      document.body.removeChild(link)
    }, 0)
  }
}
/**
 * @description: 快捷时间
 */
export const generateQuickDate = () => [
  {
    text: '今天',
    value: () => {
      const day = new Date().toLocaleDateString()
      const start = new Date(`${day} 0:0:0`)
      const end = new Date(`${day} 23:59:59`)
      return [start, end]
    },
  },
  {
    text: '昨天',
    value: () => {
      const d = new Date()
      d.setTime(d.getTime() - 3600 * 1000 * 24)
      const day = d.toLocaleDateString()
      const start = new Date(`${day} 0:0:0`)
      const end = new Date(`${day} 23:59:59`)
      return [start, end]
    },
  },
  {
    text: '最近7天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: '最近30天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
]

/**
 * @description: 删除二次确认提醒
 */
export const delConfirm = async (isEdit = false, msg?: string) => {
  await ElMessageBox.confirm(msg || (isEdit ? '确定要放弃此次编辑？' : '是否删除该记录~'), '提示', {
    confirmButtonText: '确认',
    center: true,
  })
}

/**
 * @description: 路由返回上一级
 * @return {*}
 */
export const goBack = async () => {
  const { default: router } = await import('@/router')
  if (router.options.history.state.position === 1) {
    router.push('/')
  } else {
    router.back()
  }
}
/**
 * @description: 生成随机ID
 * @param {string} prefix
 */
export const genId = (prefix?: string) => `${prefix || ''}${Math.random()?.toString(16)?.slice(2)}`

/**
 * @description: 打开新页面
 * @param {string} url
 * @param {*} target
 */
export const newPage = (url: string, target: '_self' | '_blank' = '_blank') => {
  const a = document.createElement('a')
  a.setAttribute('href', url)
  a.setAttribute('target', target)
  a.setAttribute('id', 'newPage')
  if (!document.getElementById('newPage')) {
    document.body.appendChild(a)
  }
  a.click()
  document.body.removeChild(a)
}

// 延迟运行
export const $sleep = (time: number) => {
  return new Promise(res => {
    const timeout = setTimeout(() => {
      res(0)
      clearTimeout(timeout)
    }, time)
  })
}

// 在非web环境延迟执行（）
export const sleepNotInWeb = async (time = 100) => {
  if (isWebEvn) return
  await $sleep(time)
}

// 轮询订单支付状态
export const interval = (
  callback: (
    ...args: any[]
  ) => Promise<{ change?: boolean; success?: boolean } | boolean> | boolean,
  {
    time,
    overdue,
    success,
    fail,
    changeFun,
  }: {
    time?: number
    overdue?: number
    success?: () => void
    fail?: () => void
    changeFun?: () => void
  },
) => {
  let timer: any = null
  let isStop = false
  const end = () => {
    isStop = true
    clearTimeout(timer)
  }

  const loop = async (...args: any[]) => {
    try {
      const res = await callback(...args)
      if (typeof res === 'object') {
        if (res.success) {
          end()
          await success?.()
          return true
        } else if (res.change) {
          changeFun?.()
        }
      } else {
        if (res) {
          end()
          await success?.()
          return true
        }
      }
    } catch (err: any) {
      end()
      await fail?.()
      throw err.message
    }
    if (isStop) return
    setTimeout(() => loop(...args), time || 3000)
  }
  return {
    start: (...args: any[]) => {
      isStop = false
      loop(...args)
      timer = setTimeout(async () => {
        isStop = true
        clearTimeout(timer)
        await fail?.()
      }, overdue || 300000)
    },
    end,
  }
}

// 当前是否网页环境
export const isWebEvn = sys_type === sys_type_web
export const isNotStudyMachine = sys_type !== sys_type_study_machine
export const isStudyMachine = sys_type === sys_type_study_machine

// 获取等级进度
export const getLevelProgress = (data: anyObj) => {
  if (!data) return 0
  const { currentLevelNum, currentExp, currentExpStart, nextExp } = data
  return currentLevelNum >= 60
    ? 100
    : Number((((currentExp - currentExpStart) / (nextExp - currentExpStart)) * 100).toFixed(2))
}

//  1920下的像素转为vw
export const px2vw = (px: any) => {
  const v = Number(px)
  return isNaN(v) ? px : (v / 1920) * 100 + 'vw'
}

//  1200下的像素转为vw
export const px2vh = (px: any) => {
  const v = Number(px)
  return isNaN(v) ? px : (v / 1200) * 100 + 'vh'
}

// 1920下的像素转为当前屏幕的像素【适用于插件不会自动转换的样式，比如某些组件内部样式】
// 比如{width: 100} => {width: px2px(100)}
export const px2px = (px: any) => {
  const v = Number(px)
  return isNaN(v) ? Math.round(px) : Math.round((v / 1920.0) * window.innerWidth)
}

// 1200下的像素转为当前屏幕的像素【适用于插件不会自动转换的样式，比如某些组件内部样式】
// 比如{height: 100} => {height: px2px_h(100)}
export const px2px_h = (px: any) => {
  const v = Number(px)
  return isNaN(v) ? Math.round(px) : Math.round((v / 1200.0) * window.innerHeight)
}

/**
 * @param per 百分比（比如0.8是80%）
 * @returns
 */
export const percentWidth = (per: number) => {
  return Math.round(Number(per) * window.innerWidth)
}

/**
 * @param per 百分比（比如0.8是80%）
 * @returns
 */
export const percentHeight = (per: number) => {
  return Math.round(Number(per) * window.innerHeight)
}

// 获取闯关等级

export const getLevelName = (level: number) => {
  const levelOption: { [key: number]: string } = {
    1: '入门',
    2: '进阶',
    3: '复习普通',
    4: '复习困难',
  }
  for (const key in levelOption) {
    if (key === level.toString()) {
      return levelOption[key]
    }
  }
}
// 时间换算
export const secondsToHours = (s: number) => {
  const day = dayjs.duration(s, 's')
  return `${String(Math.floor(day.asHours())).padStart(2, '0')}:${String(day.minutes()).padStart(
    2,
    '0',
  )}:${String(day.seconds()).padStart(2, '0')}`
}

// 根据秒数算出对应时分秒--补零
export const secondsToTime = (second: number) => {
  const t = dayjs.duration(second, 's')
  const h = t.hours()
  const m = t.minutes()
  const s = t.seconds()

  return (
    (h ? String(h).padStart(2, '0') + 'h ' : '') +
    (h || m ? String(m).padStart(2, '0') + 'm ' : '') +
    String(s).padStart(2, '0') +
    's'
  )
}

// 数字转单位
export const convertNumber = (number: number | undefined) => {
  if (number === undefined) return
  if (number || number === 0) {
    if (number >= 1000 && number < 10000) {
      const result = Math.floor(number / 100) / 10
      return result.toFixed(1) + 'K'
    } else if (number >= 10000) {
      const result = Math.floor(number / 1000) / 10
      return result.toFixed(1) + 'W'
    } else {
      return number.toString()
    }
  }
}
