/**
 * @description 格式化金额
 */
const useFormatAmount = () => {
  const plusOrMinus = (values) => {
    let newValue;
    if (!/[^0-9.-]/g.test(values)) {
      newValue =
        values
          .replace(/[^\-\d.]/g, "")
          .replace(/\b(0+){2,}/g, "0")
          .replace(/-{2,}/g, "-")
          .replace(/^\./g, "")
          .replace(/\.{2,}/g, ".")
          .replace(".", "$#$")
          .replace(/\./g, "")
          .replace("$#$", ".") || "";
      if (
        newValue.toString().indexOf(".") >= 1 &&
        Number(newValue.toString().split(".")[1].length) > 2
      ) {
        newValue = parseInt(String(parseFloat(newValue) * 100)) / 100;
      }
      if (newValue.toString().split("-").length - 1 > 1) {
        newValue = parseFloat(newValue) || "";
      }
      if (
        newValue.toString().split("-").length > 1 &&
        newValue.toString().split("-")[0].length >= 1
      ) {
        newValue = parseFloat(newValue) || "";
      }
      if (
        newValue.toString().length > 1 &&
        (newValue.toString().charAt(0) === "0" ||
          (newValue.toString().length > 2 &&
            newValue.toString().charAt(0) === "-" &&
            newValue.toString().charAt(1) === "0" &&
            newValue.toString().charAt(2) !== ".")) &&
        newValue.toString().indexOf(".") < 1
      ) {
        newValue = parseFloat(newValue) || "";
      }
    } else {
      newValue = values.replace(/[^0-9.-]/g, "");
    }
    return newValue;
  };
  const formatPrice = (n) => {
    if (!n) {
      return "";
    }
    let n1 = plusOrMinus(n.toString());
    if (n1.toString().indexOf(".") >= 1) {
      n1 =
        n1.toString().split(".")[0].substring(0, 9) +
        "." +
        n1.toString().split(".")[1].substring(0, 2);
    } else {
      n1 = n1.toString().substring(0, 9);
    }

    let re = /\d{1,3}(?=(\d{3})+$)/g;
    let n2 = n1.replace(/^(\d+)((\.\d+)?)$/, function (s, s1, s2) {
      return s1.replace(re, "$&,") + s2;
    });

    return n2;
  };
  let price2NumStr = (values) => {
    return plusOrMinus(values.toString());
  };
  return {
    formatPrice,
    price2NumStr,
  };
};

export default useFormatAmount;
