import { getOrderById } from "@/api/order.js";
import { useUser } from "@/store/user.js";
import dayjs from "dayjs";

/**
 * 生成范围随机数
 * @param {Object} Min
 * @param {Object} Max
 */
export function RandomNumBoth(Max, Min = 0) {
  var Range = Max - Min;
  var Rand = Math.random();
  var num = Min + Math.round(Rand * Range); //四舍五入
  return num;
}

/**
 * 去除字符串中除了数字和点以外的其他字符
 * @param {Object} obj
 */
export function clearNoNum(obj) {
  // 如果用户第一位输入的是小数点，则重置输入框内容
  if (obj.value != "" && obj.value.substr(0, 1) == ".") {
    obj.value = "";
  }

  // 去除数字前面多余的 0，但保留 0. 这种情况
  obj.value = obj.value.replace(/^0*(0\.|[1-9])/, "$1");

  // 清除“数字”和“.”以外的字符
  obj.value = obj.value.replace(/[^\d.]/g, "");

  // 只保留第一个. 清除多余的
  obj.value = obj.value.replace(/\.{2,}/g, ".");
  obj.value = obj.value
    .replace(".", "$#$")
    .replace(/\./g, "")
    .replace("$#$", ".");

  // 只能输入两个小数
  obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3");

  if (obj.value.indexOf(".") < 0 && obj.value != "") {
    // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02 的金额
    if (obj.value.substr(0, 1) == "0" && obj.value.length == 2) {
      obj.value = obj.value.substr(1, obj.value.length);
    }
  }
  return obj.value;
}

/**
 * 保留小数n位，不进行四舍五入
 * num你传递过来的数字,
 * decimal你保留的几位,默认保留小数后两位
 * isInt 是否保留0
 */
export function formatDecimal(num, decimal = 2, isInt = false) {
  num = num.toFixed(3).toString();
  const index = num.indexOf(".");
  if (index !== -1) {
    num = num.substring(0, decimal + index + 1);
  } else {
    num = num.substring(0);
  }
  //截取后保留两位小数
  if (isInt) {
    return parseFloat(num);
  } else {
    return parseFloat(num).toFixed(decimal);
  }
}

/**
 * 过滤input只能输入整数
 * @param {*} value
 * @returns
 */
export function inputFilterInt(value) {
  if (!value) return;
  return value.replace(/[^\d]/g, "");
}

/**
 * 过滤input只能输入数字，并且最多输入两位小数
 * @param {*} value
 * @returns
 */
export function inputFilterFloat(value) {
  if (!value) return;
  // 去除首位小数点
  if (value.startsWith(".")) {
    value = value.slice(1);
  }
  // 清除非数字和小数点（除了第一个小数点）
  value = value.replace(/[^\d.]/g, "");
  // 确保最多只有一个小数点
  if (value.split(".").length > 2) {
    value = value.split(".").slice(0, 2).join(".");
  }
  // 限制小数位数为两位
  if (value.split(".")[1] && value.split(".")[1].length > 2) {
    value = value.split(".")[0] + "." + value.split(".")[1].slice(0, 2);
  }
  // 限制首位只能输入一个0
  if (value.startsWith("0") && value.length > 1 && value[1] === "0") {
    // 如果首位是0，且第二位也是0，将第二个0及之后的内容清空
    value = "0";
  }
  return value;
}

/**
 * 将手机号中间四位替换为*号
 * @param {*} phone
 * @returns
 */
export function formatPhoneNumber(phone, isFormat = true) {
  if (isFormat) {
    return phone.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
  } else {
    return phone;
  }
}

/**
 * 获取订单详情
 * @param {*} orderId
 * @returns
 */
export async function getOrderByIdAjax(orderId) {
  try {
    if (!orderId) return;
    const res = await getOrderById({ orderId: orderId });

    let arr = [];
    for (let key in res.detailMap) {
      arr.push(res.detailMap[key]);
    }

    arr = arr.flat();
    arr.map((item) => {
      if (item.productType == "package" && item.proGroupInfo) {
        item.proGroupInfo = JSON.parse(item.proGroupInfo).flat();
      }
    });
    res.cartList = arr;
    return Promise.resolve(res);
  } catch (error) {
    console.log(error);
    return Promise.reject();
  }
}

/**
 * 将订单小票打印的数据组合起来
 * @param {*} orderDetail
 */
export function commOrderPrintData(orderInfo) {
  const userStore = useUser();
  let data = {
    title: orderInfo.title,
    isBefore: orderInfo.isBefore || false,
    isGuest: orderInfo.isGuest || false,
    shop_name: userStore.shopInfo.shopName,
    loginAccount: userStore.userInfo.name,
    carts: [],
    discountAllAmount: formatDecimal(+orderInfo.discountAllAmount),
    orderAmount: formatDecimal(+orderInfo.orderAmount),
    amount: formatDecimal(+orderInfo.payAmount),
    originAmount: formatDecimal(+orderInfo.originAmount),
    discountAmount:
      orderInfo.status == "unpaid"
        ? "0.00"
        : formatDecimal(orderInfo.originAmount - orderInfo.orderAmount),
    discount: orderInfo.discountRatio,
    remark: orderInfo.remark,
    orderInfo: orderInfo,
    outNumber: orderInfo.tableCode,
    createdAt: orderInfo.createTime,
    printTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
  };

  if (orderInfo.isGuest) {
    // 如果是客看单，只展示当前下单的菜品
    orderInfo.detailMap[0].map((item) => {
      let price = 0
      if (item.discountSaleAmount > 0) {
        price = item.discountSaleAmount
      } else {
        price = item.price
      }

      data.carts.push({
        categoryId: item.categoryId,
        name: item.isGift === 1 ? `[赠]${item.productName}` : item.productName,
        number: item.num - item.returnNum,
        skuName: item.skuName,
        salePrice: formatDecimal(+price),
        totalAmount: formatDecimal(+item.payAmount),
        proGroupInfo: item.proGroupInfo
          ? item.proGroupInfo.map((item) => item.goods).flat()
          : "",
      });
    });
  } else {
    orderInfo.cartList.map((item) => {
      let price = 0
      if (item.discountSaleAmount > 0) {
        price = item.discountSaleAmount
      } else {
        price = item.price
      }
      data.carts.push({
        categoryId: item.categoryId,
        name: item.isGift === 1 ? `[赠]${item.productName}` : item.productName,
        number: item.num - item.returnNum,
        skuName: item.skuName,
        salePrice: formatDecimal(+price),
        totalAmount: formatDecimal((item.num - item.returnNum) * price),
        proGroupInfo: item.proGroupInfo
          ? item.proGroupInfo.map((item) => item.goods).flat()
          : "",
      });
    });
  }

  if (orderInfo.dineMode == 'dine-in') {
    if (orderInfo.seatAmount > 0 && orderInfo.isGuest && orderInfo.placeNum == 1 && !orderInfo.isRefundDish) {
      data.carts.push({
        categoryId: '',
        name: '餐位费',
        number: orderInfo.seatNum,
        skuName: '',
        salePrice: formatDecimal(orderInfo.seatAmount / orderInfo.seatNum),
        totalAmount: orderInfo.seatAmount,
        proGroupInfo: "",
      })
    }

    if (orderInfo.seatAmount > 0 && !orderInfo.isGuest && !orderInfo.isRefundDish) {
      data.carts.push({
        categoryId: '',
        name: '餐位费',
        number: orderInfo.seatNum,
        skuName: '',
        salePrice: formatDecimal(orderInfo.seatAmount / orderInfo.seatNum),
        totalAmount: orderInfo.seatAmount,
        proGroupInfo: "",
      })
    }
  }

  if (orderInfo.packFee > 0 && !orderInfo.isRefundDish) {
    let packNum = 0;
    orderInfo.cartList.forEach(item => {
      packNum += item.packNumber
    })
    data.carts.push({
      categoryId: '',
      name: '打包费',
      number: packNum,
      skuName: '',
      salePrice: '',
      totalAmount: formatDecimal(orderInfo.packFee),
      proGroupInfo: "",
    })
  }

  console.log('最终组合打印数据===', data);
  return data;
}

/**
 * 校验手机号
 * @param {*} phone
 * @returns
 */
export function regPhone(phone) {
  let reg = /^(?:(?:\+|00)86)?1\d{10}$/;
  return reg.test(phone);
}
