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/info2/service/addTimeModal/index.tsx
var addTimeModal_exports = {};
__export(addTimeModal_exports, {
  default: () => addTimeModal_default
});
module.exports = __toCommonJS(addTimeModal_exports);
var import_react = __toESM(require("react"));
var import_drawer = __toESM(require("../../../components/drawer"));
var import_model = require("../../../info/model");
var import_antd = require("antd");
var import_addTimeModal = require("../../../info/service/addTimeModal/index.less");
var import_utils = require("@pisell/utils");
var import_ahooks = require("ahooks");
var import_footer = __toESM(require("../../../components/footer"));
var import_serve = require("./serve");
var import_utils2 = require("./utils");
var import_classnames = __toESM(require("classnames"));
var import_browserSelect = __toESM(require("../../../components/browserSelect"));
var import_utils3 = require("../../../utils");
var import_utilsByBooking = require("../../utilsByBooking");
var import_useEngineContext = __toESM(require("../../../../../hooks/useEngineContext"));
var import_utils4 = require("../../../info/utils");
var numberList = (0, import_utils.createArray)(100, (d, i) => {
  let item = {
    label: i + 1,
    value: i + 1
  };
  return item;
});
var AddTimeModal = () => {
  var _a, _b, _c, _d, _e, _f, _g, _h;
  const { state, dispatch } = (0, import_react.useContext)(import_model.Context);
  const [isEdit, setIsEdit] = (0, import_react.useState)(false);
  const loadingRef = (0, import_react.useRef)(false);
  const [loading, setLoading] = (0, import_react.useState)("");
  const [recordKey, setRecordKey] = (0, import_react.useState)("");
  const [number, setNumber] = (0, import_react.useState)(1);
  const originServices = (0, import_react.useRef)([]);
  const [renderList, setRenderList] = (0, import_react.useState)([]);
  const context = (0, import_useEngineContext.default)();
  const { interaction } = (_a = context.appHelper) == null ? void 0 : _a.utils;
  const statusMap = {
    available: {
      label: import_utils.locales.getText("page.booking.text.available"),
      color: "#079455"
    },
    fully_booked: {
      label: import_utils.locales.getText("page.booking.text.fully-booked"),
      color: "#DC6803"
    },
    unavailable: {
      label: import_utils.locales.getText("page.booking.text.unavailable"),
      color: "#98A2B3"
    }
  };
  const updateServices = (0, import_ahooks.useDebounceFn)(
    () => {
      createNewServices();
    },
    { wait: 200 }
  );
  const transaction_habit_selection = (0, import_react.useMemo)(() => {
    var _a2, _b2, _c2;
    return ((_c2 = (_b2 = (_a2 = state == null ? void 0 : state.bookingConfig) == null ? void 0 : _a2.config) == null ? void 0 : _b2.information_tab) == null ? void 0 : _c2.transaction_habit_selection) || {
      type: "service_now_pay_later",
      button_rows: 1
    };
  }, [(_c = (_b = state == null ? void 0 : state.bookingConfig) == null ? void 0 : _b.config) == null ? void 0 : _c.information_tab]);
  const currentProductId = (0, import_react.useMemo)(() => {
    return import_utils2.addTimeRowKey.getValue(recordKey).product_id;
  }, [recordKey]);
  const currentTime = (0, import_react.useMemo)(() => {
    let _time = import_utils2.addTimeRowKey.getValue(recordKey).time || "";
    return _time;
  }, [recordKey]);
  const currentProduct = (0, import_react.useMemo)(() => {
    return (renderList || []).find((d) => d.id == currentProductId);
  }, [renderList, currentProductId]);
  console.log("renderList", renderList);
  const currentTimeItem = (0, import_react.useMemo)(() => {
    var _a2;
    return ((_a2 = currentProduct == null ? void 0 : currentProduct.times) == null ? void 0 : _a2.find((d) => d.value == currentTime)) || {
      price: 0
    };
  }, [currentTime, currentProduct]);
  const currentResource = (0, import_react.useMemo)(() => {
    var _a2, _b2;
    const resource = (_b2 = (_a2 = state.service.cacheItem) == null ? void 0 : _a2._extend) == null ? void 0 : _b2.resource;
    let arr = [];
    for (let form_id in resource) {
      arr = [
        ...arr,
        ...resource[form_id].map((d) => {
          var _a3, _b3, _c2, _d2, _e2;
          return (_e2 = (_d2 = (_c2 = (_b3 = (_a3 = state.service.cacheItem) == null ? void 0 : _a3._data) == null ? void 0 : _b3.resourceMaps) == null ? void 0 : _c2[form_id]) == null ? void 0 : _d2.renderListMaps) == null ? void 0 : _e2[d.relation_id];
        })
      ];
    }
    return arr.filter(Boolean);
  }, [(_f = (_e = (_d = state.service) == null ? void 0 : _d.cacheItem) == null ? void 0 : _e._extend) == null ? void 0 : _f.resource]);
  const getTimeUsableStatus = (time) => {
    var _a2, _b2;
    if (!((_a2 = state.service.cacheItem) == null ? void 0 : _a2._extend) || !currentResource.length) {
      return { status: statusMap.unavailable };
    }
    try {
      let _extend = { ...state.service.cacheItem._extend };
      _extend.endDate = _extend.endDate.add(time, "minutes");
      _extend.start_date = _extend.startDate;
      _extend.end_date = _extend.endDate;
      _extend.end_time = _extend.endDate.format("HH:mm");
      _extend.start_time = _extend.startDate.format("HH:mm");
      _extend.duration = import_utils3.flexibleObj.add(_extend.duration, time);
      if ((0, import_utils3.isNowTime)(_extend.start_time)) {
        _extend.start_time = (0, import_utils3.getNowTime)();
      }
      const startText = _extend.startDate.format("hh:mm A");
      let endText = _extend.endDate.format("hh:mm A");
      if (_extend.endDate.isAfter(_extend.startDate, "day")) {
        endText = import_utils.locales.getText("pisell1.text.tomorrow") + endText;
      }
      let errorList = [];
      for (let resourceItem of currentResource) {
        let timeItem = resourceItem == null ? void 0 : resourceItem.times.find(
          (_time) => _time.item_id === resourceItem.id
        );
        const res = (0, import_utilsByBooking.getResourceTimeIsUsable)(
          timeItem,
          {
            ...state.service.cacheItem,
            _extend: {
              ...state.service.cacheItem._extend,
              ..._extend
            }
          },
          resourceItem
        );
        if (!((_b2 = res._extend) == null ? void 0 : _b2.isUsable)) {
          errorList.push(resourceItem);
        }
      }
      if (errorList.length) {
        return {
          // maxEndTime:
          status: statusMap.unavailable,
          message: `${errorList.map((d) => d.labelText).join(", ")} ${import_utils.locales.getText(
            "pisell2.text.status.service-error-2"
          )}`
        };
      }
    } catch (err) {
    }
    return { status: statusMap.available };
  };
  const _getAddTimeProducts = async () => {
    var _a2, _b2, _c2, _d2;
    const data = await (0, import_serve.getAddTimeProducts)(
      {
        skip: 1,
        num: 500,
        open_quotation: 1,
        schedule_date: state.date.value.format("YYYY-MM-DD"),
        customer_id: (0, import_utils3.isWalkIn)((_b2 = (_a2 = state.client) == null ? void 0 : _a2.value) == null ? void 0 : _b2.id) ? void 0 : (_d2 = (_c2 = state.client) == null ? void 0 : _c2.value) == null ? void 0 : _d2.id,
        extension_type: ["product_add_time"],
        status: "published"
      },
      {
        useCache: true,
        retry: {
          count: 3,
          delay: 500
        }
      }
    );
    return (data == null ? void 0 : data.list) || [];
  };
  const getTimeProducts = async () => {
    setLoading("list");
    const newList = await _getAddTimeProducts();
    let list = newList.map((d) => {
      let isUsable = (0, import_utils2.isUsableProduct)(d.add_time, state.service.cacheItem);
      return {
        ...d,
        usable: isUsable,
        // 可用的商品生成加时列表
        times: isUsable ? (0, import_utils2.getAddTimeSplits)(d, state.service.cacheItem).map((time) => {
          return {
            ...time,
            status: getTimeUsableStatus(time.value)
          };
        }) : void 0
      };
    }).filter((d) => d.usable && d.times.length).sort((a, b) => b.sort - a.sort);
    setRenderList(list);
    if (list.length) {
      setDefaultProduct(list);
    }
    setLoading("");
    setIsEdit(true);
  };
  const setDefaultProduct = (list) => {
    try {
      let productId = list[0].id;
      let time = list[0].times[0].value;
      setRecordKey(import_utils2.addTimeRowKey.create(productId, time));
      updateServices.run();
    } catch (err) {
    }
  };
  (0, import_ahooks.useUpdateEffect)(() => {
    if (state.service.addTimeModal) {
      getTimeProducts();
      loadingRef.current = false;
      originServices.current = state.service;
    } else {
      updateServices.run();
    }
  }, [state.service.addTimeModal]);
  const onSelectItem = (pItem, item) => {
    setRecordKey(import_utils2.addTimeRowKey.create(pItem.id, item.value));
    setIsEdit(true);
    updateServices.run();
  };
  const newService = (0, import_react.useMemo)(() => {
    if (!currentProduct || !state.service.cacheItem) {
      return null;
    }
    const relation_product = {
      product_add_schedule_time: currentTime,
      num: number,
      price: currentTimeItem.price || 0,
      product_id: currentProduct.id,
      discount_amount: 0,
      product_discount_reason: "",
      is_charge_tax: currentProduct.is_charge_tax,
      discountway: "num",
      discount_type: "discount"
    };
    let _extend = { ...state.service.cacheItem._extend };
    let relation_products = [relation_product];
    _extend.endDate = _extend.endDate.add(
      relation_product.product_add_schedule_time,
      "minutes"
    );
    const start_date = _extend.startDate.format("YYYY-MM-DD");
    const end_date = _extend.endDate.format("YYYY-MM-DD");
    const end_time = _extend.endDate.format("HH:mm");
    let start_time = _extend.startDate.format("HH:mm");
    let duration = import_utils3.flexibleObj.add(
      _extend.duration,
      relation_product.product_add_schedule_time
    );
    if ((0, import_utils3.isNowTime)(_extend.start_time)) {
      start_time = (0, import_utils3.getNowTime)();
    }
    _extend.relation_details = (_extend.relation_details || []).concat(
      relation_products
    );
    _extend.duration = duration;
    _extend.start_time = start_time;
    _extend.end_time = end_time;
    _extend.start_date = start_date;
    _extend.end_date = end_date;
    let data = {
      id: _extend.id,
      relation_id: _extend.relation_id,
      like_status: _extend.like_status,
      relation_type: _extend.relation_type,
      is_all: _extend.is_all,
      schedule_id: _extend.schedule_id,
      end_time,
      sub_type: _extend.sub_type,
      select_date: start_date,
      start_time,
      end_date,
      start_date,
      duration,
      number: _extend.number || 1,
      relation_products,
      _extend,
      resources: _extend.event_resources,
      metadata: _extend.metadata
    };
    return data;
  }, [
    currentTime,
    state.service.cacheItem,
    currentProduct,
    number,
    currentTimeItem
  ]);
  const resetService = () => {
    var _a2, _b2;
    let _val = ((_a2 = originServices.current) == null ? void 0 : _a2.value) || [];
    let _edit = (_b2 = originServices.current) == null ? void 0 : _b2.edit;
    originServices.current = null;
    dispatch({
      type: "setService",
      payload: {
        value: _val,
        edit: _edit
      }
    });
  };
  const createNewServices = () => {
    var _a2;
    let _list = ((_a2 = state.service) == null ? void 0 : _a2.value) || [];
    if (!originServices.current) {
      return;
    }
    if (state.service.addTimeModal) {
      _list = _list.map((d) => {
        let _item = {
          ...d
        };
        if (_item._extend.id === (newService == null ? void 0 : newService.id)) {
          _item = {
            ..._item,
            ...newService || {},
            _extend: newService == null ? void 0 : newService._extend
          };
        }
        return _item;
      });
      dispatch({
        type: "setService",
        payload: {
          value: _list,
          edit: true
        }
      });
    } else {
      resetService();
    }
  };
  const goCheckout = async () => {
    var _a2, _b2;
    if (state.isTerminal) {
      return (_b2 = (_a2 = interaction == null ? void 0 : interaction.utils) == null ? void 0 : _a2.postMessageToApp) == null ? void 0 : _b2.call(_a2, {
        module: "booking",
        key: "booking_checkout",
        data: {
          order_id: state.bookingId
        }
      });
    }
    state.action({
      type: "pisell1.handlePayment",
      data: {
        orderId: state.bookingId
      },
      callback: () => {
        state == null ? void 0 : state.callback();
      }
    });
  };
  const handleCheckout = async () => {
    if (isEdit) {
      await handleSave("checkout");
    }
    goCheckout();
  };
  const handleSave = async (loadingType = "save") => {
    var _a2, _b2, _c2, _d2, _e2, _f2;
    if (currentTime === null) {
      return;
    }
    if (loadingRef.current) {
      return;
    }
    loadingRef.current = true;
    setLoading(loadingType);
    const api = (0, import_utils4.isBooking4Shop)(
      (_e2 = (_d2 = (_c2 = (_b2 = (_a2 = context.appHelper.utils.store) == null ? void 0 : _a2.getState) == null ? void 0 : _b2.call(_a2)) == null ? void 0 : _c2.global) == null ? void 0 : _d2.globalConfig) == null ? void 0 : _e2.id,
      state.renderType,
      (_f2 = context.appHelper.utils) == null ? void 0 : _f2.businessUtils
    ) ? import_serve.saveAddTimeProduct2 : import_serve.saveAddTimeProduct;
    try {
      await api({
        orderId: state.bookingId,
        params: {
          ...newService,
          _extend: void 0
        }
      });
      loadingRef.current = false;
    } catch (err) {
      loadingRef.current = false;
    }
    setLoading("");
    import_antd.message.success(import_utils.locales.getText("page.booking.text.add-time-success"));
    onCancel();
    if (loadingType === "checkout") {
      return;
    }
    state == null ? void 0 : state.action("init");
  };
  (0, import_react.useEffect)(() => {
    if (!state.modalOpen) {
      onCancel();
    }
  }, [state.modalOpen]);
  const onCancel = () => {
    setIsEdit(false);
    setRecordKey("");
    resetService();
    setTimeout(() => {
      dispatch({
        type: "setService",
        payload: {
          addTimeModal: false
        }
      });
    }, 50);
  };
  const updateTime = (0, import_react.useMemo)(() => {
    if (!newService) {
      return "";
    }
    let startTime = newService.start_time;
    let endTime = newService.end_time;
    let hours = (0, import_utils3.getDiscountTime)(import_utils3.flexibleObj.getValue(newService.duration));
    if (newService.start_date !== newService.end_date) {
      const locale = state.locale;
      const format = locale === "en" || locale === "en-US" ? "HH:mm DD/MM" : "MM-DD HH:mm";
      startTime = (0, import_utils.formatDate)(
        `${newService.start_date} ${newService.start_time}`,
        format
      );
      endTime = (0, import_utils.formatDate)(
        `${newService.end_date} ${newService.end_time}`,
        format
      );
    }
    return `${import_utils.locales.getText(
      "page.booking.text.update-time"
    )}: ${startTime} ~ ${endTime} (${hours})`;
  }, [newService, state.locale]);
  return /* @__PURE__ */ import_react.default.createElement(
    import_drawer.default,
    {
      titleNoWrap: true,
      open: state.service.addTimeModal,
      title: import_utils.locales.getText("page.booking.text.add-time"),
      rootClassName: "booking-server-wrap",
      onClose: onCancel,
      footerStyle: { padding: "10px 32px 20px" },
      hideScrollBar: false,
      bodyStyle: { position: "relative" },
      footer: /* @__PURE__ */ import_react.default.createElement("div", null, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__booking-add-time-total-wrap" }, currentTimeItem && ((_g = currentTimeItem == null ? void 0 : currentTimeItem.status) == null ? void 0 : _g.message) ? /* @__PURE__ */ import_react.default.createElement(
        import_antd.Alert,
        {
          message: currentTimeItem.status.message,
          type: "warning",
          showIcon: true,
          style: { marginBottom: 12 }
        }
      ) : null, newService ? /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__booking-add-time-summary-wrap" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__booking-add-time-summary" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__booking-add-time-summary-time" }, updateTime), /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__booking-add-time-summary-total" }, import_utils.locales.getText("pisell1.text.subtotal"), ":", " ", (0, import_utils.formatAmount)(
        (currentTimeItem.price || 0) * number,
        2,
        state.amountSymbol
      ))), ((_h = currentProduct == null ? void 0 : currentProduct.add_time) == null ? void 0 : _h.calculate_type) === "select_quantity" && /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__booking-add-time-quantity-wrap" }, /* @__PURE__ */ import_react.default.createElement("span", { className: "pisell-lowcode__booking-add-time-quantity" }, import_utils.locales.getText("page.booking.text.quantity")), " ", /* @__PURE__ */ import_react.default.createElement(
        import_browserSelect.default,
        {
          value: number,
          onChange: (e) => {
            setNumber(Number(e.target.value));
            updateServices.run();
          },
          className: "pisell-lowcode__booking-add-time-quantity-select",
          options: numberList
        }
      ))) : null), /* @__PURE__ */ import_react.default.createElement(
        import_footer.default,
        {
          state,
          dispatch,
          source: "addTime",
          buttons: [
            /* @__PURE__ */ import_react.default.createElement(
              import_antd.Button,
              {
                className: "pisell-lowcode__booking-footer-buttons-item",
                type: transaction_habit_selection.type === "service_now_pay_later" ? "default" : "primary",
                disabled: loading === "list" || !isEdit || !currentTime,
                onClick: handleCheckout,
                loading: loading === "checkout"
              },
              import_utils.locales.getText("pisell2.text.checkout")
            ),
            /* @__PURE__ */ import_react.default.createElement(
              import_antd.Button,
              {
                className: "pisell-lowcode__booking-footer-buttons-item",
                type: transaction_habit_selection.type === "service_now_pay_later" ? "primary" : "default",
                disabled: loading === "list" || !isEdit || !currentTime,
                loading: loading === "save",
                onClick: () => {
                  handleSave("save");
                }
              },
              import_utils.locales.getText("pisell2.text.save")
            )
          ]
        }
      ))
    },
    /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__booking-add-time-body" }, /* @__PURE__ */ import_react.default.createElement(import_antd.Skeleton, { loading: loading === "list", active: true, round: true }, /* @__PURE__ */ import_react.default.createElement("div", { className: "" }, renderList.map((d) => {
      return /* @__PURE__ */ import_react.default.createElement("div", { className: "" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__booking-add-time-hours" }, d.title), d.times ? /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__booking-add-time-child-card-list" }, d.times.map((child) => {
        var _a2, _b2, _c2, _d2;
        return /* @__PURE__ */ import_react.default.createElement(
          "div",
          {
            className: (0, import_classnames.default)(
              "pisell-lowcode__booking-add-time-child-card",
              {
                "pisell-lowcode__booking-add-time-child-card-active": recordKey === import_utils2.addTimeRowKey.create(d.id, child.value)
              }
            ),
            onClick: () => {
              if (!child.value) {
                return;
              }
              onSelectItem(d, child);
            }
          },
          /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__booking-add-time-child-card-left" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__booking-add-time-child-card-left-time" }, child.label), /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__booking-add-time-child-card-left-price" }, (0, import_utils.formatAmount)(
            child.price,
            2,
            state.amountSymbol
          ))),
          /* @__PURE__ */ import_react.default.createElement(
            "div",
            {
              className: "pisell-lowcode__booking-add-time-child-card-right",
              style: {
                color: (_b2 = (_a2 = child.status) == null ? void 0 : _a2.status) == null ? void 0 : _b2.color
              }
            },
            (_d2 = (_c2 = child.status) == null ? void 0 : _c2.status) == null ? void 0 : _d2.label
          )
        );
      })) : null);
    }))), /* @__PURE__ */ import_react.default.createElement("div", { className: "" }))
  );
};
var addTimeModal_default = AddTimeModal;
