/**
 * post写法get传参
 * @param obj
 * @returns {string}
 */
export function postConvertGet(obj) {
  let params = ''
  if (obj === undefined) {
    return params
  } else if (JSON.stringify(obj) === '{}') {
    return params
  } else {
    for (const [key, value] of Object.entries(obj)) {
      params += `${key}=${value}&`
    }
    params = `?${params.slice(0, -1)}`
    return params
  }
}

/**
 * 时间戳转换
 * @param date
 * @returns {string}
 */
export function convertTimestamp(date) {
  const addZero = num => (num > 9 ? num : '0' + num)
  return `${date.getFullYear()}-${date.getMonth() +
    1}-${date.getDate()} ${addZero(date.getHours())}:${addZero(
    date.getMinutes()
  )}:${addZero(date.getSeconds())}`
}

/**
 * 对数组进行过滤
 * @param list
 * @param param
 * @returns [*]
 */
export function filterList(list, param) {
  return list.map(item => item[param])
}

/**
 * 移除文件路径，保留文件名
 * @param str
 * @returns {T}
 */
export function removeFileDomain(str) {
  return str
    .split('\\')
    .pop()
    .split('/')
    .pop()
}

/**
 * 移除空值
 * @param obj
 * @returns {*}
 */
export function removeEmptyValue(obj) {
  Object.keys(obj).forEach(key => {
    if (obj[key] === null || obj[key] === undefined || obj[key] === '') {
      delete obj[key]
    }
  })
  return obj
}

/**
 * 数组转为字符串
 * @param arr
 * @returns {string}
 */
export function arrayConvertString(arr) {
  const list = arr.map(item => Number(item))
  const listStr = JSON.stringify(list)
  return listStr.substring(1, listStr.length - 1)
}

/**
 * 判断一个字符串是否是正整数
 * @param str
 * @returns {boolean}
 */
export function isNormalInteger(str) {
  const n = Math.floor(Number(str))
  return n !== Infinity && String(n) === str && n >= 0
}

/**
 * 下载图片
 * @param imgsrc
 * @param name
 * @returns {boolean}
 */
export function downloadIamge(imgsrc, name) {
  var image = new Image()
  // 解决跨域 Canvas 污染问题
  image.setAttribute('crossOrigin', 'anonymous')
  image.onload = function() {
    var canvas = document.createElement('canvas')
    canvas.width = image.width
    canvas.height = image.height
    var context = canvas.getContext('2d')
    context.drawImage(image, 0, 0, image.width, image.height)
    var url = canvas.toDataURL('image/png') // 得到图片的base64编码数据
    var a = document.createElement('a') // 生成一个a元素
    var event = new MouseEvent('click') // 创建一个单击事件
    a.download = name || 'photo' // 设置图片名称
    a.href = url // 将生成的URL设置为a.href属性
    a.dispatchEvent(event) // 触发a的单击事件
  }
  image.src = imgsrc
}
