import { ElMessageBox } from 'element-plus'
import FileSaver from 'file-saver'
import { VxeUI } from 'vxe-pc-ui'

import dayjs from '#/plugins/dayjs'

const previewImage = (evt: any) => {
  VxeUI.previewImage({
    maskClosable: true,
    escClosable: true,
    urlList: [{ url: evt.currentTarget.src }],
  })
}

export function initImgPreview(dom: any) {
  if (!dom) return
  const images = dom.querySelectorAll('img')
  images.forEach((img: any) => {
    img.style.cursor = 'pointer'
    img.removeEventListener('click', previewImage)
    img.addEventListener('click', previewImage)
  })
}

/**
 * 获取随机数
 * @param length 长度
 * @returns
 */
export const randomString = (length: number = 32) => {
  const STRING_TEMPLATE =
    'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
  const coefficient = STRING_TEMPLATE.length
  let string = ''
  for (let i = 0; i < length; 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: any[],
  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 = function (
  url: Blob | File | string,
  fileName?: string,
  type?: number,
) {
  if (type) {
    FileSaver.saveAs(url, fileName)
  } else {
    const link = document.createElement('a')
    link.download = fileName as any
    link.href = url as string
    document.body.append(link)
    link.click()
    setTimeout(() => {
      link.remove()
    }, 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 { 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)}`

/**
 * 限制输入金额，保留位数可传入,默认保留两位
 * @param val
 */
export const replaceAmount = (val: number | string, limit = 2) => {
  let amount = val as string
  amount = amount.replaceAll(/[^\d.]/g, '') // 保留数字
  amount = amount.replace(/^00/, '0.') // 开头不能有两个0
  amount = amount.replaceAll(/^\./g, '0.') // 开头为小数点转换为0.
  amount = amount.replaceAll(/\.{2,}/g, '.') // 两个以上的小数点转换成一个
  amount = amount.replace('.', '$#$').replaceAll('.', '').replace('$#$', '.') // 只保留一个小数点
  const reg0 = /^0\d+/
  // 两位以上数字开头不能为0
  if (reg0.test(amount)) {
    amount = amount.slice(1)
  }
  const str = `${String.raw`^(\d+)\.(\d{` + limit}}).*$`
  const reg = new RegExp(str)
  // 不需要小数点
  amount =
    limit === 0 ? amount.replace(reg, '$1') : amount.replace(reg, '$1.$2')
  // 通过正则保留小数点后指定的位数

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

// 时间换算
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')}`
}
