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);
}

function toDataURL(url) {
  return fetch(url)
    .then((response) => {
      return response.blob();
    })
    .then((blob) => {
      return URL.createObjectURL(blob);
    });
}

// 下载文件
export async function downloadFileURL(url, name) {
  const link = document.createElement("a");
  link.style.display = "none";
  const fileName = name || url.split("/").pop();
  link.setAttribute("download", fileName);

  // txt 文件会直接在浏览器里面打开，这时候只能修改服务器设置，加上 Content-Disposition: attachment
  if ([".txt"].some((v) => fileName.endsWith(v))) {
    // const urlObj = new URL(url);
    // link.href = await toDataURL(url.replace(urlObj.origin));
    link.href = await toDataURL(url);
  } else {
    link.href = url;
  }
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

/**
 * 将目标对象中有的属性值与源对象中的属性值合并
 * @param {Object} target 目标对象
 * @param {Object} sources 源对象
 */
export function objAssign(target, sources) {
  let targ = { ...target };
  for (let k in targ) {
    targ[k] = Object.prototype.hasOwnProperty.call(sources, k)
      ? sources[k]
      : targ[k];
  }
  return targ;
}

/**
 * 文件流下载
 * @param {Function} fetchFunc 下载程序，返回promise
 * @param {String} fileName 保存的文件名
 */
export async function downloadBlob(fetchFunc, fileName) {
  const res = await fetchFunc().catch(() => {});
  if (!res) return;

  const blobUrl = URL.createObjectURL(new Blob([res.data]));
  let a = document.createElement("a");
  a.download = fileName;
  a.href = blobUrl;
  document.body.appendChild(a);
  a.click();
  a.parentNode.removeChild(a);

  return true;
}

export function objTypeOf(obj) {
  const toString = Object.prototype.toString;
  const map = {
    "[object Boolean]": "boolean",
    "[object Number]": "number",
    "[object String]": "string",
    "[object Function]": "function",
    "[object Array]": "array",
    "[object Date]": "date",
    "[object RegExp]": "regExp",
    "[object Undefined]": "undefined",
    "[object Null]": "null",
    "[object Object]": "object",
  };
  return map[toString.call(obj)];
}

export function formatDate(format = "YYYY/MM/DD HH:mm:ss", date = new Date()) {
  if (objTypeOf(date) !== "date") return;
  const options = {
    "Y+": date.getFullYear(),
    "M+": date.getMonth() + 1,
    "D+": date.getDate(),
    "H+": date.getHours(),
    "m+": date.getMinutes(),
    "s+": date.getSeconds(),
  };
  Object.entries(options).map(([key, val]) => {
    if (new RegExp("(" + key + ")").test(format)) {
      const zeros = key === "Y+" ? "0000" : "00";
      const value = (zeros + val).substr(("" + val).length);
      format = format.replace(RegExp.$1, value);
    }
  });
  return format;
}

/**
 *  获取时间长度文字
 * @param {Number} timeNumber 时间数值，单位：毫秒
 */
export function timeNumberToText(timeNumber) {
  const DAY_TIME = 24 * 60 * 60 * 1000;
  const HOUR_TIME = 60 * 60 * 1000;
  const MINUTE_TIME = 60 * 1000;
  const SECOND_TIME = 1000;
  let [day, hour, minute, second] = [0, 0, 0, 0];
  let residueTime = timeNumber;

  if (residueTime >= DAY_TIME) {
    day = Math.floor(residueTime / DAY_TIME);
    residueTime -= day * DAY_TIME;
    day += "天";
  }
  if (residueTime >= HOUR_TIME) {
    hour = Math.floor(residueTime / HOUR_TIME);
    residueTime -= hour * HOUR_TIME;
    hour += "小时";
  }
  if (residueTime >= MINUTE_TIME) {
    minute = Math.floor(residueTime / MINUTE_TIME);
    residueTime -= minute * MINUTE_TIME;
    minute += "分钟";
  }
  if (residueTime >= SECOND_TIME) {
    second = Math.round(residueTime / SECOND_TIME);
    second += "秒";
  }

  return [day, hour, minute, second].filter((item) => !!item).join("");
}

export function deepCopy(obj) {
  return JSON.parse(JSON.stringify(obj));
}
