var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/components/booking/hooks/useQuotation.tsx
var useQuotation_exports = {};
__export(useQuotation_exports, {
  calculateTotalPrice: () => calculateTotalPrice,
  default: () => useQuotation_default
});
module.exports = __toCommonJS(useQuotation_exports);
var import_react = __toESM(require("react"));
var import_utils = require("../utils");
var import_useEngineContext = __toESM(require("../../../../es/hooks/useEngineContext"));
var import_utils2 = require("@pisell/utils");
var import_materials = require("@pisell/materials");
var import_serve = require("../info/service/serve");
var import_decimal = __toESM(require("decimal.js"));
var formatBundleItemMap = (product) => {
  return product.bundle_group.reduce((pre, cur) => {
    const curObj = {};
    cur.bundle_item.forEach((item) => {
      curObj[item.id] = item;
    });
    return {
      ...pre,
      ...curObj
    };
  }, {});
};
var calculateTotalPrice = (data) => {
  const _price = data.reduce((total, item) => {
    const _price2 = (item == null ? void 0 : item.price) || (item == null ? void 0 : item.add_price);
    return total + _price2 * item.num;
  }, 0);
  return parseFloat(_price);
};
var setNewCartValue = (cartValue, newProducts) => {
  if (!newProducts.length) {
    return {
      isChange: false,
      value: cartValue
    };
  }
  let isChange = false;
  let isBundleChange = false;
  let isNotFoundBundle = false;
  const notFoundProducts = [];
  const value = cartValue.map((item) => {
    var _a, _b, _c, _d;
    const newProduct = newProducts.find((newItem2) => newItem2.id === item.product_id);
    if (!newProduct) {
      return item;
    }
    let isChangePrice = newProduct.price != item.price;
    const bundleItemMap = formatBundleItemMap(newProduct);
    const newBundle = (((_b = (_a = item._extend) == null ? void 0 : _a.other) == null ? void 0 : _b.bundle) || []).map((bundle) => {
      if (!bundleItemMap[bundle.id]) {
        isNotFoundBundle = true;
        if (!notFoundProducts.some((p) => p._id === bundle._id)) {
          notFoundProducts.push(item);
        }
        return bundle;
      }
      if (bundle.price != bundleItemMap[bundle.id].price) {
        isChangePrice = true;
        isBundleChange = true;
      }
      if (bundleItemMap[bundle.id].price_type === "markdown") {
        bundleItemMap[bundle.id].price = new import_decimal.default(bundleItemMap[bundle.id].price || 0).mul(-1).toNumber();
      }
      const selectBundleInfo = item._extend.other.bundle.find((item2) => item2.id === bundle.id);
      const optionPrice = calculateTotalPrice((selectBundleInfo == null ? void 0 : selectBundleInfo.option) || []);
      return {
        ...bundle,
        base_price: bundleItemMap[bundle.id].base_price,
        price: new import_decimal.default(bundleItemMap[bundle.id].price || 0).add(optionPrice).toNumber()
        // product_price: bundleItemMap[item.id].product_price,
      };
    });
    if (!isChangePrice) {
      return item;
    } else {
      isChange = true;
    }
    const newItem = {
      ...item,
      original_price: newProduct.original_price,
      price: newProduct.price,
      base_price: newProduct.base_price,
      _extend: {
        ...item._extend,
        price: newProduct.price,
        // total: newProduct.total,
        bundle_edit: isBundleChange ? 1 : item._extend.bundle_edit,
        other: {
          ...item._extend.other,
          option: (_d = (_c = item._extend) == null ? void 0 : _c.other) == null ? void 0 : _d.option,
          bundle: newBundle
        }
      }
    };
    const total = (0, import_utils.getProductTotalPrice)(newItem);
    newItem._extend.total = total;
    newItem._extend.origin_total = total;
    return newItem;
  });
  return {
    isChange,
    value,
    isNotFoundBundle,
    notFoundProducts
  };
};
var useQuotation = (state, dispatch) => {
  var _a, _b;
  const context = (0, import_useEngineContext.default)();
  const [open, setOpen] = (0, import_react.useState)(false);
  const [products, setProducts] = (0, import_react.useState)([]);
  const cartValueRef = (0, import_react.useRef)(state.service.value || []);
  cartValueRef.current = state.service.value;
  const getCartQuotation = async (params) => {
    if (!cartValueRef.current.length) return;
    const data = await (0, import_serve.getProductPrice)({
      ids: cartValueRef.current.map((item) => item.product_id),
      schedule_date: params == null ? void 0 : params.schedule_date,
      customer_id: params == null ? void 0 : params.customer_id
    });
    return data;
  };
  const currentDate = (0, import_react.useMemo)(() => {
    return state.date.value.format("YYYY-MM-DD");
  }, [state.date.value]);
  const updateCartQuotation = async (params) => {
    const data = await getCartQuotation(params);
    if (!(data == null ? void 0 : data.data)) return;
    const { isChange, value: newCartValue, isNotFoundBundle, notFoundProducts } = setNewCartValue(cartValueRef.current, data.data);
    if (isNotFoundBundle) {
      setProducts(notFoundProducts);
      setOpen(true);
      return;
    }
    if (!isChange) return;
    dispatch({
      type: "setService",
      payload: {
        value: newCartValue,
        edit: true
      }
    });
  };
  const isEditClientOrDate = (0, import_react.useMemo)(() => {
    var _a2, _b2;
    return ((_a2 = state == null ? void 0 : state.client) == null ? void 0 : _a2.edit) || ((_b2 = state == null ? void 0 : state.date) == null ? void 0 : _b2.edit);
  }, [state]);
  (0, import_react.useEffect)(() => {
    var _a2, _b2, _c, _d, _e, _f, _g, _h, _i, _j;
    const isQuotation = (_d = (_c = (_b2 = (_a2 = context == null ? void 0 : context.appHelper) == null ? void 0 : _a2.utils) == null ? void 0 : _b2.businessUtils) == null ? void 0 : _c.getAppByModal) == null ? void 0 : _d.call(_c, "quotation");
    const isHolidayQuotation = (_h = (_g = (_f = (_e = context == null ? void 0 : context.appHelper) == null ? void 0 : _e.utils) == null ? void 0 : _f.businessUtils) == null ? void 0 : _g.getAppByModal) == null ? void 0 : _h.call(_g, "holidayquotation");
    if (!isQuotation && !isHolidayQuotation || !isEditClientOrDate) return;
    updateCartQuotation({
      customer_id: (_j = (_i = state.client) == null ? void 0 : _i.value) == null ? void 0 : _j.id,
      schedule_date: currentDate
    });
  }, [(_b = (_a = state.client) == null ? void 0 : _a.value) == null ? void 0 : _b.id, currentDate, isEditClientOrDate]);
  const dom = (0, import_react.useMemo)(() => {
    return /* @__PURE__ */ import_react.default.createElement(
      import_materials.PisellModal.Information,
      {
        open,
        platform: "pc",
        title: import_utils2.locales.getText("pisell2.text.quotation.product.change.title"),
        describe: /* @__PURE__ */ import_react.default.createElement("div", null, import_utils2.locales.getText("pisell2.text.quotation.product.change.describe"), products.map((item) => /* @__PURE__ */ import_react.default.createElement("div", null, item == null ? void 0 : item.product_title))),
        okText: import_utils2.locales.getText("pisell2.text.ok"),
        closable: true,
        cancelVisible: false,
        onOk: () => setOpen(false),
        onCancel: () => setOpen(false)
      }
    );
  }, [open, products]);
  return {
    dom
  };
};
var useQuotation_default = useQuotation;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  calculateTotalPrice
});
