const downloadCvs2Img = (params) => {
  const {
    cvs,
    title
  } = params;

  let $a = document.createElement('a');
  $a.download = title + '.jpg';
  $a.target = '_blank';
  let url;
  if (cvs) {
    url = cvs.toDataURL("image/jpg");
  }

  if (url) $a.href = url;

  if (typeof MouseEvent === 'function') {
    var evt = new MouseEvent('click', {
      view: window,
      bubbles: true,
      cancelable: false
    });
    $a.dispatchEvent(evt);
  } else {
    if (window.navigator.msSaveOrOpenBlob) {
      var bstr = atob(url.split(',')[1]);
      var n = bstr.length;
      var u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      var blob = new Blob([u8arr]);
      window.navigator.msSaveOrOpenBlob(blob, title + '.jpg');
    } else {
      var html = '' +
        '<body style="margin:0;">' +
        '<img src="' + url + '" style="max-width:100%;" title="" />' +
        '</body>';
      var tab = window.open();
      tab.document.write(html);
    }
  }
}

const format = (fmt) => {
  const date = new Date();
  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 {
  downloadCvs2Img,
  format,
}