import { Message } from 'element-ui'
export const uuid = (len = 16, radix = 10) => {
  const chars =
    '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
  const uuid = []
  let i
  radix = radix || chars.length
  if (len) {
    // Compact form
    for (i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)]
  } else {
    // rfc4122, version 4 form
    let r

    // rfc4122 requires these characters
    uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
    uuid[14] = '4'

    // Fill in random data.  At i==19 set the high bits of clock sequence as
    // per rfc4122, sec. 4.1.5
    for (i = 0; i < 36; i++) {
      if (!uuid[i]) {
        r = 0 | (Math.random() * 16)
        uuid[i] = chars[i === 19 ? (r & 0x3) | 0x8 : r]
      }
    }
  }
  return uuid.join('')
}

export const copy = (data) => {
  var copy = document.createElement('p')
  copy.innerText = data
  document.body.append(copy)
  var range = document.createRange()
  range.selectNode(copy)
  var selection = window.getSelection()
  if (selection) {
    if (selection.rangeCount > 0) selection.removeAllRanges()
    selection.addRange(range)
  }
  document.execCommand('copy')
  document.body.removeChild(copy)
}

export const jsonToFormData = (data) => {
  const formData = new FormData()
  Object.keys(data).forEach((key) => {
    formData.append(key, data[key])
  })
  return formData
}

/**
 *
 * @param {object} positionData {
 *   centerPosition:{x: x, y: y} 圆心坐标
 *   originPosition:{x: x, y: y} 初始坐标
 *   rotate: rotate 旋转角度
 * }
 * @description 根据圆心坐标、旋转角度计算旋转后的坐标
 */
export const getRotatePosition = (positionData) => {
  const radian = (Math.PI / 180) * positionData.rotate
  return {
    x:
      (positionData.originPosition.x - positionData.centerPosition.x) *
        Math.cos(radian) -
      (positionData.originPosition.y - positionData.centerPosition.y) *
        Math.sin(radian) +
      positionData.centerPosition.x,
    y:
      (positionData.originPosition.y - positionData.centerPosition.y) *
        Math.cos(radian) +
      (positionData.originPosition.x - positionData.centerPosition.x) *
        Math.sin(radian) +
      positionData.centerPosition.y
  }
}

/**
 * @description 防抖
 * @param {*} fn
 * @param {*} wait
 * @returns
 */
export function _debounce(fn, wait = 500) {
  let timer
  return function () {
    const context = this
    const args = arguments
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(context, args)
    }, wait)
  }
}

/**
 * @description 节流
 * @param {*} fn
 * @param {*} wait
 * @returns
 */
export function _throttle(fn, wait = 500) {
  let last, timer, now
  return function () {
    now = Date.now()
    if (last && now - last < wait) {
      clearTimeout(timer)
      timer = setTimeout(function () {
        last = now
        fn.call(this, ...arguments)
      }, wait)
    } else {
      last = now
      fn.call(this, ...arguments)
    }
  }
}

/**
 * @param {Array} permissionList
 * @param {String} routerName
 * @description 判断是否有权限
 */
export const hasPermission = (permissionList, routerName) => {
  return permissionList.some((permission) => {
    if (permission.code === routerName) {
      return true
    } else {
      return (
        permission.children &&
        permission.children.length &&
        permission.children.find((child) => {
          if (child.code === routerName) {
            return true
          }
        })
      )
    }
  })
}

// 后端返回二进制流下载文件
export const downloadBlob = (blob, fileName = 'download') => {
  const reader = new FileReader()
  reader.readAsDataURL(blob)
  reader.onload = (e) => {
    const a = document.createElement('a')
    a.download = fileName
    a.href = e.target.result
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
  }
}

/**
 * @description base64下载word
 */

export const downloadWord = (base64Data, filename) => {
  // 创建Blob对象
  var blob = base64ToBlob(
    base64Data,
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
  )

  // 创建下载链接
  var url = URL.createObjectURL(blob)
  var downloadLink = document.createElement('a')

  // 设置下载链接属性
  downloadLink.href = url
  downloadLink.download = filename

  // 触发下载
  document.body.appendChild(downloadLink)
  downloadLink.click()
  document.body.removeChild(downloadLink)
  URL.revokeObjectURL(url) // 清理
}

export const base64ToBlob = (base64, mimeType) => {
  // 解码Base64字符串
  var byteCharacters = atob(base64.replace(/^data:\w+\/\w+;base64,/, ''))

  // 将解码的字符串转换为类型化数组
  var byteNumbers = new Array(byteCharacters.length)
  for (var i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i)
  }

  // 创建Blob对象
  var byteArray = new Uint8Array(byteNumbers)
  return new Blob([byteArray], { type: mimeType })
}

export const downloadExcel = (base64Data, filename, type) => {
  const blobs = type
    ? 'application/vnd.ms-excel'
    : 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  // 创建Blob对象
  var blob = base64ToBlob(base64Data, blobs)

  // 创建下载链接
  var url = URL.createObjectURL(blob)
  var downloadLink = document.createElement('a')

  // 设置下载链接属性
  downloadLink.href = url
  downloadLink.download = filename

  // 触发下载
  document.body.appendChild(downloadLink)
  downloadLink.click()
  document.body.removeChild(downloadLink)
  URL.revokeObjectURL(url) // 清理
}
// 时间戳转化为时间
export function convertTimestamp(timestamp) {
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
// 格式化时间
export function formatDate(timestamp, formate) {
  const date = new Date()
  date.setTime(parseInt(timestamp))
  //  传入formate形式 yyyy-MM-dd yyyy-MM-dd hh:mm
  formate = formate != null ? formate : 'yyyy-MM-dd'
  const Format = function (fmt) {
    var o = {
      'M+': date.getMonth() + 1, // 月
      'd+': date.getDate(), // 日
      'h+': date.getHours(), // 小时
      'm+': date.getMinutes(), // 分
      's+': date.getSeconds(), // 秒
      'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
      S: date.getMilliseconds() // 毫秒
    }
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        (date.getFullYear() + '').substr(4 - RegExp.$1.length)
      )
    }
    // if (/(y+)/.test(fmt))
    //   fmt = fmt.replace(
    //     RegExp.$1,
    //     (date.getFullYear() + '').substr(4 - RegExp.$1.length)
    //   )
    for (var k in o) {
      if (new RegExp('(' + k + ')').test(fmt)) {
        fmt = fmt.replace(
          RegExp.$1,
          RegExp.$1.length === 1
            ? o[k]
            : ('00' + o[k]).substr(('' + o[k]).length)
        )
      }
    }
    return fmt
  }
  return Format(formate)
}
export default {
  uuid,
  copy,
  jsonToFormData,
  getRotatePosition,
  _debounce,
  _throttle,
  hasPermission,
  downloadBlob,
  downloadWord,
  base64ToBlob,
  downloadExcel,
  findExcelBase64,
  convertTimestamp,
  formatDate
}
