import { OrderType, TimeRange } from "./enum";

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() {
  let now = new Date();
  let currentMonthStart = new Date(now.getFullYear(), now.getMonth(), 1);
  let currentMonthEnd = new Date(now.getFullYear(), now.getMonth() + 1, 0);

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

export function getCurrentYearStartAndEnd() {
  let now = new Date();
  let currentYearStart = new Date(now.getFullYear(), 0, 1); // 0 代表一月
  let 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);
  let time1 = new Date(getMonday("s", 0)).getTime();
  let time2 = new Date(new Date(new Date().setHours(0, 0, 0))).getTime();
  if (time1 > time2) {
    startTime = getMonday("s", -1);
    endTime = getMonday("e", -1);
  }
  return {
    start: startTime,
    end: endTime,
  };
}

function getMonday(type: string, dates: number) {
  var now = new Date();
  var nowTime = now.getTime();
  var day = now.getDay();
  var longTime = 24 * 60 * 60 * 1000;
  var 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);
  var y = dd.getFullYear();
  var m = dd.getMonth() + 1;
  var d = dd.getDate();
  m = m < 10 ? "0" + m : m;
  d = d < 10 ? "0" + d : d;
  return y + "-" + m + "-" + d;
}

export function deleteBaseKey(obj: any) {
  delete obj.createTime;
  delete obj.createUserId;
  delete obj.createUserName;
  delete obj.updateTime;
  delete obj.updateUserId;
  delete obj.updateUserName;
  return obj;
}

export function moneyFormat(num: number, decimal = 2, split = ",") {
  /*
    parameter：
    num：格式化目标数字
    decimal：保留几位小数，默认2位
    split：千分位分隔符，默认为,
    moneyFormat(123456789.87654321, 2, ',') // 123,456,789.88
  */
  if (isFinite(num)) {
    // num是数字
    if (num === 0) {
      // 为0
      return num.toFixed(decimal);
    } else {
      // 非0
      var res = "";
      var dotIndex = String(num).indexOf(".");
      if (dotIndex === -1) {
        // 整数
        if (decimal === 0) {
          res = String(num).replace(/(\d)(?=(?:\d{3})+$)/g, `$1${split}`);
        } else {
          res =
            String(num).replace(/(\d)(?=(?:\d{3})+$)/g, `$1${split}`) +
            "." +
            "0".repeat(decimal);
        }
      } else {
        // 非整数
        // js四舍五入 Math.round()：正数时4舍5入，负数时5舍6入
        // Math.round(1.5) = 2
        // Math.round(-1.5) = -1
        // Math.round(-1.6) = -2
        // 保留decimals位小数
        const numStr = String(
          (
            Math.round(num * Math.pow(10, decimal)) / Math.pow(10, decimal)
          ).toFixed(decimal)
        ); // 四舍五入，然后固定保留2位小数
        const decimals = numStr.slice(dotIndex, dotIndex + decimal + 1); // 截取小数位
        res =
          String(numStr.slice(0, dotIndex)).replace(
            /(\d)(?=(?:\d{3})+$)/g,
            `$1${split}`
          ) + decimals;
      }
      return res;
    }
  } else {
    return "--";
  }
}

// 分页内容重置
export function pageListInit() {
  return {
    noMoreData: false,
    total: 0,
    list: [],
    pageNum: 1,
    pageSize: 100,
  };
}
// 过滤掉属性值为null的
export function filterNullUndefined(obj: Object) {
  return Object.entries(obj).reduce((acc: any, [key, value]) => {
    if (value !== null && value !== undefined && value !== "") {
      acc[key] = value;
    }
    return acc;
  }, {});
}

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 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"
  var n = !isFinite(+number) ? 0 : +number,
    prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
    sep = typeof thousands_sep === "undefined" ? "," : thousands_sep,
    dec = typeof dec_point === "undefined" ? "." : dec_point,
    s: any = "",
    toFixedFix = function (n: any, prec: any) {
      var 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(".");
  var 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 countDots(str: any) {
  if (str) {
    return (str.toString().match(/\./g) || []).length;
  } else {
    return 0;
  }
}
export function isTwoDecimalPlaces(num: any) {
  // 转换为字符串并移除可能的符号
  const str = num.toString().replace(/[-]+/g, "");
  // 分割整数部分和小数部分
  const parts = str.split(".");
  // 如果小数点后有两位数字，返回true
  return parts.length === 2 && parts[1].length > 2;
}
export function validateRegex(regexValue: string, value: string) {
  const regex = new RegExp(regexValue);
  return regex.test(value);
}

/***
 * 收货汇总 出货汇总 单据状态获取
 */
export function getScaleStatus(type: number, value: number) {
  if (type === OrderType.Receive) {
    if (value === -1) {
      return "全部";
    } else if (value === 4) {
      return "已支付";
    } else if (value === 3) {
      return "已审未付";
    } else if (value === 2) {
      return "未审核";
    }
  } else if (type === OrderType.Shipment) {
    if (value === -1) {
      return "全部";
    } else if (value === 4) {
      return "已结算";
    } else if (value === 3) {
      return "未结算";
    }
  }
}

// 判断是否是时间格式
export function isDateTimePicker(str: any) {
  return str.split(" ").length === 2;
}

// 格式化开始时间和结束时间
export function formatStartAndEndTime(str: string, type: string) {
  if (type === "s") {
    return str ? (isDateTimePicker(str) ? str : str + " 00:00:00") : "";
  } else if (type === "e") {
    return str ? (isDateTimePicker(str) ? str : str + " 23:59:59") : "";
  }
}

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

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

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

// 两个浮点数相除
export function num_divide(num1: number, num2: number) {
  var t1, t2, r1, r2;
  try {
    t1 = num1.toString().split(".")[1].length;
  } catch (e) {
    t1 = 0;
  }
  try {
    t2 = num2.toString().split(".")[1].length;
  } catch (e) {
    t2 = 0;
  }
  r1 = Number(num1.toString().replace(".", ""));
  r2 = Number(num2.toString().replace(".", ""));
  return (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;
}
