import { TimeRange } from "./enum";
/**
 * Check if an element has a class
 * @param {HTMLElement} ele
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass(ele: HTMLElement, cls: string) {
  return !!ele.className.match(new RegExp("(\\s|^)" + cls + "(\\s|$)"));
}

/**
 * Add class to element
 * @param {HTMLElement} ele
 * @param {string} cls
 */
export function addClass(ele: HTMLElement, cls: string) {
  if (!hasClass(ele, cls)) ele.className += " " + cls;
}

/**
 * Remove class from element
 * @param {HTMLElement} ele
 * @param {string} cls
 */
export function removeClass(ele: HTMLElement, cls: string) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp("(\\s|^)" + cls + "(\\s|$)");
    ele.className = ele.className.replace(reg, " ");
  }
}

/**
 * 判断是否是外部链接
 *
 * @param {string} path
 * @returns {Boolean}
 */
export function isExternal(path: string) {
  const isExternal = /^(https?:|http?:|mailto:|tel:)/.test(path);
  return isExternal;
}

// 格式化金额
export function formatMoney(
  number: any,
  decimals?: any,
  dec_point?: any,
  thousands_sep?: any,
  roundtag?: any
) {
  /*
   * 参数说明：
   * number：要格式化的数字
   * decimals：保留几位小数
   * dec_point：小数点符号
   * thousands_sep：千分位符号
   * roundtag:舍入参数，默认 "ceil" 向上取,"floor"向下取,"round" 四舍五入
   * */
  if (!number) {
    number = 0;
  }
  if (!decimals) {
    decimals = 0; //默认保留2位小数
  }
  if (!dec_point) {
    dec_point = ".";
  }
  if (!thousands_sep) {
    thousands_sep = ",";
  }
  if (!roundtag) {
    roundtag = "round";
  }
  number = (number + "").replace(/[^0-9+-Ee.]/g, "");
  roundtag = roundtag || "ceil"; //"ceil","floor","round"
  const n = !isFinite(+number) ? 0 : +number;
  const prec = !isFinite(+decimals) ? 0 : Math.abs(decimals);
  const sep = typeof thousands_sep === "undefined" ? "," : thousands_sep;
  const dec = typeof dec_point === "undefined" ? "." : dec_point;
  let s: any = "";
  const toFixedFix = function (n: any, prec: any) {
    const k = Math.pow(10, prec);

    return (
      "" +
      parseFloat(
        (Math as any)
          [roundtag](parseFloat((n * k).toFixed(prec * 2)))
          .toFixed(prec * 2)
      ) /
        k
    );
  };
  s = (prec ? toFixedFix(n, prec) : "" + Math.round(n)).split(".");
  const re = /(-?\d+)(\d{3})/;
  while (re.test(s[0])) {
    s[0] = s[0].replace(re, "$1" + sep + "$2");
  }

  if ((s[1] || "").length < prec) {
    s[1] = s[1] || "";
    s[1] += new Array(prec - s[1].length + 1).join("0");
  }
  return s.join(dec);
}

export function formatDate(time: any, cFormat: string) {
  const format = cFormat || "{y}-{m}-{d}";
  const date = new Date(time);
  const formatObj: any = {
    //年
    y: date.getFullYear(),
    //月
    m: date.getMonth() + 1,
    //日
    d: date.getDate(),
    //小时
    h: date.getHours(),
    //分钟
    i: date.getMinutes(),
    //秒
    s: date.getSeconds(),
    //星期
    a: date.getDay(),
  };
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key];
    // Note: getDay() returns 0 on Sunday
    if (key === "a") {
      //如果key是a，就是星期，格式化成一~日
      //例如formatDate(new Date(), '{y}-{m}-{d}-{h}-{i}-{s}-{a}');
      //会输出2021-10-29-00-00-00-五
      //星期的value会返回0-6，['日', '一', '二', '三', '四', '五', '六'][2]代表周二
      return ["日", "一", "二", "三", "四", "五", "六"][value];
    }
    //padStart用于字符串头部补全，2个字符，如果不够前面补0
    return value.toString().padStart(2, "0");
  });
  return time_str;
}

export function getCurrentMonthStartAndEnd() {
  const now = new Date();
  const currentMonthStart = new Date(now.getFullYear(), now.getMonth(), 1);
  const currentMonthEnd = new Date(now.getFullYear(), now.getMonth() + 1, 0);

  return {
    start: currentMonthStart,
    end: currentMonthEnd,
  };
}

export function getCurrentYearStartAndEnd() {
  const now = new Date();
  const currentYearStart = new Date(now.getFullYear(), 0, 1); // 0 代表一月
  const currentYearEnd = (new Date(now.getFullYear() + 1, 0, 1) as any) - 1; // 下一年的一月一日减一毫秒

  return {
    start: currentYearStart,
    end: currentYearEnd,
  };
}

export function getCurrentWeekStartAndEnd() {
  // let startTime = getMonday("s", 0);
  // let endTime = getMonday("e", 0);
  // const time1 = new Date(getMonday("s", 0)).getTime();
  // const time2 = new Date(new Date(new Date().setHours(0, 0, 0))).getTime();
  // if (time1 > time2) {
  //   startTime = getMonday("s", -1);
  //   endTime = getMonday("e", -1);
  // }
  var currentDate = new Date();

  // 获取本周第一天的日期
  var firstDay = new Date(
    currentDate.setDate(currentDate.getDate() - currentDate.getDay() + 1)
  );

  // 获取本周最后一天的日期
  var lastDay = new Date(
    currentDate.setDate(currentDate.getDate() - currentDate.getDay() + 7)
  );

  // 格式化日期为字符串，例如："YYYY-MM-DD"
  var format = function (date: any) {
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    return year + "-" + month + "-" + day;
  };

  return {
    start: format(firstDay),
    end: format(lastDay),
  };
}

function getMonday(type: string, dates: number) {
  const now = new Date();
  const nowTime = now.getTime();
  const day = now.getDay();
  const longTime = 24 * 60 * 60 * 1000;
  const n = longTime * 7 * (dates || 0);
  let dd: any = null;
  if (type == "s") {
    dd = nowTime - (day - 1) * longTime + n;
  }
  if (type == "e") {
    dd = nowTime + (7 - day) * longTime + n;
  }
  dd = new Date(dd);
  const y = dd.getFullYear();
  let m = dd.getMonth() + 1;
  let d = dd.getDate();
  m = m < 10 ? "0" + m : m;
  d = d < 10 ? "0" + d : d;
  return y + "-" + m + "-" + d;
}

export function timeShortcuts() {
  return [
    {
      text: "今天",
      value: () => {
        const start = new Date();
        const end = new Date();
        start.setHours(0, 0, 0);
        end.setHours(23, 59, 59);
        return [start, end];
      },
    },
    {
      text: "昨天",
      value: () => {
        const start = new Date();
        const end = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24);
        end.setTime(end.getTime() - 3600 * 1000 * 24);
        start.setHours(0, 0, 0);
        end.setHours(23, 59, 59);
        return [start, end];
      },
    },
    {
      text: "最近一周",
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
        return [start, end];
      },
    },
    {
      text: "最近一个月",
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
        return [start, end];
      },
    },
    {
      text: "最近三个月",
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
        return [start, end];
      },
    },
  ];
}

export function getPaymentMethod(paymentMethod: any) {
  return ["", "现金", "转账", "微信", "支付宝"][paymentMethod];
}

export function getWeighingMethod(index: any) {
  return ["有皮重", "零皮重"][index];
}

export function getMultiCategory(index: any) {
  return ["单品类", "多品类"][index];
}

// 两个浮点数求和
export function num_add(num1: number, num2: number) {
  let r1, r2;
  try {
    r1 = num1.toString().split(".")[1].length;
  } catch (e) {
    r1 = 0;
  }
  try {
    r2 = num2.toString().split(".")[1].length;
  } catch (e) {
    r2 = 0;
  }
  const m = Math.pow(10, Math.max(r1, r2));
  return Number(Math.round(num1 * m + num2 * m) / m);
}

// 两个浮点数相减
export function num_subtract(num1: number, num2: number) {
  let r1, r2;
  try {
    r1 = num1.toString().split(".")[1].length;
  } catch (e) {
    r1 = 0;
  }
  try {
    r2 = num2.toString().split(".")[1].length;
  } catch (e) {
    r2 = 0;
  }
  const m = Math.pow(10, Math.max(r1, r2));
  const n = r1 >= r2 ? r1 : r2;
  return Number(Number((Math.round(num1 * m - num2 * m) / m).toFixed(n)));
}

// 两个浮点数相乘
export function num_multiply(num1: number, num2: number) {
  let m = 0;
  const s1 = num1.toString();
  const s2 = num2.toString();
  try {
    m += s1.split(".")[1].length;
  } catch (e) {}
  try {
    m += s2.split(".")[1].length;
  } catch (e) {}
  return Number(
    (Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) /
      Math.pow(10, m)
  );
}

// 两个浮点数相除
export function num_divide(num1: number, num2: number) {
  let t1, t2;
  try {
    t1 = num1.toString().split(".")[1].length;
  } catch (e) {
    t1 = 0;
  }
  try {
    t2 = num2.toString().split(".")[1].length;
  } catch (e) {
    t2 = 0;
  }
  const r1 = Number(num1.toString().replace(".", ""));
  const r2 = Number(num2.toString().replace(".", ""));
  return Number((r1 / r2) * Math.pow(10, t2 - t1));
}

export function isNullV(item: any) {
  return item === null ? "-" : item;
}

// 四舍五入到指定的小数位数
export function roundToDecimalPlace(number: number, decimalPlaces: number) {
  const factor = Math.pow(10, decimalPlaces);
  return Math.round(number * factor) / factor;
}

export function floorToDecimalPlace(number: number, decimalPlaces: number) {
  const factor = Math.pow(10, decimalPlaces);
  return Math.floor(number * factor) / factor;
}

// { id: 1, name: "正常计算" },
// { id: 2, name: "抹分" },
// { id: 3, name: "抹角分" },
// { id: 4, name: "抹元" },
// { id: 5, name: "分位四舍五入" },
// { id: 6, name: "角位四舍五入" },
// { id: 7, name: "元位四舍五入" },
export function getNumberValue(
  settlementConfig: number,
  tempTotalPrice: string
) {
  let totalPrice = 0;
  if (settlementConfig === 1) {
    totalPrice = parseFloat(tempTotalPrice);
  } else if (settlementConfig === 2) {
    totalPrice = floorToDecimalPlace(parseFloat(tempTotalPrice), 1);
  } else if (settlementConfig === 3) {
    totalPrice = floorToDecimalPlace(parseFloat(tempTotalPrice), 0);
  } else if (settlementConfig === 4) {
    totalPrice = floorToDecimalPlace(parseFloat(tempTotalPrice), -1);
  } else if (settlementConfig === 5) {
    totalPrice = roundToDecimalPlace(parseFloat(tempTotalPrice), 1);
  } else if (settlementConfig === 6) {
    totalPrice = roundToDecimalPlace(parseFloat(tempTotalPrice), 0);
  } else if (settlementConfig === 7) {
    totalPrice = roundToDecimalPlace(parseFloat(tempTotalPrice), -1);
  } else {
    totalPrice = parseFloat(tempTotalPrice);
  }
  return totalPrice;
}

export function isFormDataEmpty(formData: any) {
  let isEmpty = true;
  for (const [key, value] of formData.entries()) {
    isEmpty = false;
    break;
  }
  return isEmpty;
}
export const timeList = [
  {
    id: 1,
    name: "昨日",
  },
  {
    id: 2,
    name: "今日",
  },
  {
    id: 3,
    name: "本周",
  },
  {
    id: 4,
    name: "本月",
  },
  {
    id: 5,
    name: "本年",
  },
];

export function timeRange(id: number) {
  const today = new Date();
  const yesterday = new Date((today as any) - 24 * 60 * 60 * 1000);
  let startTime = "";
  let endTime = "";
  if (id === TimeRange.Today) {
    startTime = formatDate(today, "{y}-{m}-{d}");
    endTime = formatDate(today, "{y}-{m}-{d}");
  } else if (id === TimeRange.Yesterday) {
    startTime = formatDate(yesterday, "{y}-{m}-{d}");
    endTime = formatDate(yesterday, "{y}-{m}-{d}");
  } else if (id === TimeRange.Month) {
    startTime = formatDate(getCurrentMonthStartAndEnd().start, "{y}-{m}-{d}");
    endTime = formatDate(getCurrentMonthStartAndEnd().end, "{y}-{m}-{d}");
  } else if (id === TimeRange.Year) {
    startTime = formatDate(getCurrentYearStartAndEnd().start, "{y}-{m}-{d}");
    endTime = formatDate(getCurrentYearStartAndEnd().end, "{y}-{m}-{d}");
  } else if (id === TimeRange.Week) {
    startTime = formatDate(getCurrentWeekStartAndEnd().start, "{y}-{m}-{d}");
    endTime = formatDate(getCurrentWeekStartAndEnd().end, "{y}-{m}-{d}");
  }
  return { startTime: startTime, endTime: endTime };
}

export function downLoadExcel(content: any, name: string) {
  // const blob = new Blob([content], { type: "application/vnd.ms-excel" });
  const blob = new Blob([content], {
    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8",
  });

  const fileName = name;
  if ("download" in document.createElement("a")) {
    const elink = document.createElement("a");
    elink.download = fileName;
    elink.style.display = "none";
    elink.href = URL.createObjectURL(blob);
    document.body.appendChild(elink);
    elink.click();
    URL.revokeObjectURL(elink.href);
    document.body.removeChild(elink);
  }
}
