import { YYYYMMDDHHmmss } from "@/constant/constants";
import moment from "moment";
import queryString from "query-string";

export function dateFormatForAPI(date) {
  return moment(date).format(YYYYMMDDHHmmss);
}

export function formatEmptyToNull(obj) {
  Object.keys(obj).forEach((key) => {
    obj[key] = obj[key] === "" || obj[key] === undefined ? null : obj[key];
  });
  return obj;
}

// 错误上报：本地打印，百度统计，阿里云日志
export function errorLog(message, { stack = "", code = "" }) {
  console.error({ message, stack, code });
  window._hmt.push([
    "_trackEvent",
    "message: " + message,
    stack && "stack: " + stack,
    code && "code: " + code,
  ]);
}

const CryptoJS = require("crypto-js");

export function AESString(content) {
  const KEY = "1234567890123456";
  const IV = "1234567890123456";
  // console.log(content);

  var key = CryptoJS.enc.Utf8.parse(KEY);
  var iv = CryptoJS.enc.Utf8.parse(IV);
  var encrypted = CryptoJS.AES.encrypt(content, key, { iv: iv });
  return encrypted.toString();
}

export function object2QueryString(obj) {
  return queryString.stringify(obj);
}

// 下载文件
export function downloadFileURL(url, name) {
  const link = document.createElement("a");
  link.style.display = "none";
  // txt 文件会直接在浏览器里面打开，这时候只能修改服务器设置，加上 Content-Disposition: attachment
  link.href = url;
  const fileName = name || url.split("/").pop();
  link.setAttribute("download", fileName);
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}
