import Base64 from 'Base64'

export const dateFormat = (date, 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));
  }
  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;
}

export const copyText = (text) => {
  const input = document.createElement('input')
  document.body.appendChild(input);

  input.setAttribute('value', text);
  input.select()

  document.execCommand('copy')

  document.body.removeChild(input)
}


export const throttle = (fn, mis = 500) => {
  let time

  return (...args) => {
    clearTimeout(time)
    time = setTimeout(() => fn(...args), mis)
  }
}

export function randomWord(randomFlag, min, max) {
  let str = ''
  let range = min
  let arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  // 随机产生
  if (randomFlag) {
    range = Math.round(Math.random() * (max - min)) + min
  }
  for (var i = 0; i < range; i++) {
    let pos = Math.round(Math.random() * (arr.length - 1))
    str += arr[pos]
  }
  return str
}

export const encryption = (str, strv = '') => {
  str = Base64.btoa(str)
  const NUM = 2
  const front = randomWord(false, 8)
  const middle = randomWord(false, 8)
  const end = randomWord(false, 8)

  let str1 = str.substring(0, NUM)
  let str2 = str.substring(NUM)

  if (strv) {
    let strv1 = strv.substring(0, NUM)
    let strv2 = strv.substring(NUM)
    return [front + str2 + middle + str1 + end, front + strv2 + middle + strv1 + end]
  }

  return front + str2 + middle + str1 + end
}


/**
 *获取id
 */
export const guid = () => {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    let r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

export const downloadFile = (url, fileName) => {
  var x = new XMLHttpRequest();
  x.open("GET", url, true);
  x.responseType = 'blob';
  x.onload = function(e) {
      var url = window.URL.createObjectURL(x.response)
      var a = document.createElement('a');
      a.href = url;
      console.log(e)
      a.setAttribute('download', fileName)
      a.click();
  }
  x.send();
}