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/utils/holderAssignmentConfirmModal.tsx
var holderAssignmentConfirmModal_exports = {};
__export(holderAssignmentConfirmModal_exports, {
  HolderAssignmentConfirmModal: () => HolderAssignmentConfirmModal,
  showHolderAssignmentConfirmModal: () => showHolderAssignmentConfirmModal
});
module.exports = __toCommonJS(holderAssignmentConfirmModal_exports);
var import_react = __toESM(require("react"));
var import_antd = require("antd");
var import_ahooks = require("ahooks");
var import_utils = require("@pisell/utils");
var import_materials = require("@pisell/materials");
var import_Lists = __toESM(require("../info/service/Lists"));
var import_model = require("../info/model");
var import_utils2 = require("../info/service2/utils");
var import_selectHolderModal = require("./selectHolderModal");
var import_utils3 = require("../../ticketBooking/utils");
var import_confirmHolderModal = require("./confirmHolderModal.less");
var activeHolderAssignmentConfirm = null;
var holderAssignmentConfirmSubscribers = /* @__PURE__ */ new Set();
function notifyHolderAssignmentConfirmHost(request) {
  let handledCount = 0;
  holderAssignmentConfirmSubscribers.forEach((subscriber) => {
    if (subscriber(request)) {
      handledCount += 1;
    }
  });
  return handledCount;
}
function settleHolderAssignmentConfirmRequest(request, shouldContinue) {
  if (request.settled) {
    return;
  }
  request.settled = true;
  if (activeHolderAssignmentConfirm === request) {
    activeHolderAssignmentConfirm = null;
  }
  request.resolve(shouldContinue);
  notifyHolderAssignmentConfirmHost(null);
}
function calculateUnassignedHolderCount(state) {
  var _a;
  const unassignedProducts = (((_a = state == null ? void 0 : state.service) == null ? void 0 : _a.value) || []).filter(
    (item) => {
      var _a2, _b, _c;
      return (!((_a2 = item._extend) == null ? void 0 : _a2.holder_id) || ((_c = (_b = item._extend) == null ? void 0 : _b.holder_id) == null ? void 0 : _c.length) === 0) && !(0, import_utils2.isNormalProductByDurationSchedule)(item);
    }
  );
  const arr = [];
  unassignedProducts.forEach((item) => {
    var _a2;
    if ((_a2 = item == null ? void 0 : item._extend) == null ? void 0 : _a2.groupId) {
      if (!arr.some((sub) => {
        var _a3, _b;
        return ((_a3 = sub == null ? void 0 : sub._extend) == null ? void 0 : _a3.groupId) === ((_b = item == null ? void 0 : item._extend) == null ? void 0 : _b.groupId);
      })) {
        arr.push(item);
      }
    } else {
      arr.push(item);
    }
  });
  return arr.reduce((sum, item) => {
    var _a2;
    return sum + (((_a2 = item._extend) == null ? void 0 : _a2.quantity) || 1);
  }, 0);
}
function hasHolderId(item) {
  var _a;
  const holderId = (_a = item == null ? void 0 : item._extend) == null ? void 0 : _a.holder_id;
  return Array.isArray(holderId) ? holderId.length > 0 : Boolean(holderId);
}
function updateProductHolder(state, currentItem, holderIds) {
  var _a, _b, _c, _d, _e, _f, _g;
  const list = [...((_a = state == null ? void 0 : state.service) == null ? void 0 : _a.value) || []];
  const cacheItem = {
    ...currentItem,
    _extend: {
      ...(currentItem == null ? void 0 : currentItem._extend) || {},
      holder_id: holderIds
    }
  };
  if ((_b = cacheItem == null ? void 0 : cacheItem._extend) == null ? void 0 : _b.groupId) {
    const groupId = cacheItem._extend.groupId;
    list.forEach((item, index) => {
      var _a2;
      if (((_a2 = item == null ? void 0 : item._extend) == null ? void 0 : _a2.groupId) === groupId) {
        list[index] = {
          ...item,
          _extend: {
            ...item._extend || {},
            holder_id: holderIds
          }
        };
      }
    });
  } else {
    const index = list.findIndex((item) => item._id === cacheItem._id);
    if (index !== -1) {
      list[index] = cacheItem;
    }
  }
  if (((_d = (_c = cacheItem._extend) == null ? void 0 : _c.holder_id) == null ? void 0 : _d.length) > 1 || ((_e = cacheItem._extend) == null ? void 0 : _e.quantity) > 1 && ((_g = (_f = cacheItem._extend) == null ? void 0 : _f.holder_id) == null ? void 0 : _g.length) >= 1) {
    let remainingHolderIds = cacheItem._extend.holder_id;
    cacheItem._extend.holder_id = [remainingHolderIds[0]];
    remainingHolderIds = remainingHolderIds.slice(1);
    cacheItem._holderKey = (0, import_utils3.genHolderKey)(cacheItem);
    remainingHolderIds.forEach((holderId) => {
      const newItem = {
        ...cacheItem,
        _id: (0, import_utils.getUniqueId)(),
        _extend: {
          ...cacheItem._extend,
          holder_id: [holderId],
          quantity: 1
        }
      };
      newItem._holderKey = (0, import_utils3.genHolderKey)(newItem);
      list.unshift(newItem);
      cacheItem._extend.quantity -= 1;
    });
    if (cacheItem._extend.quantity > 1) {
      const newItem = {
        ...cacheItem,
        _id: (0, import_utils.getUniqueId)(),
        _extend: {
          ...cacheItem._extend,
          holder_id: void 0,
          quantity: cacheItem._extend.quantity - 1
        }
      };
      newItem._holderKey = (0, import_utils3.genHolderKey)(newItem);
      list.unshift(newItem);
      cacheItem._extend.quantity = 1;
    }
  }
  return list.sort((a, b) => {
    if (!hasHolderId(a) && hasHolderId(b)) return -1;
    if (hasHolderId(a) && !hasHolderId(b)) return 1;
    return 0;
  });
}
var HolderAssignmentConfirmContent = ({ state, dispatch, open, onResolve, onStateChange }) => {
  var _a, _b, _c;
  const handleClose = () => {
    if (!open) {
      return;
    }
    import_antd.Modal.confirm({
      title: import_utils.locales.getText("pisell2.text.deposit-delete-message-title"),
      content: import_utils.locales.getText("pisell2.text.close-confirm-message"),
      okText: import_utils.locales.getText("pisell2.text.confirm"),
      cancelText: import_utils.locales.getText("pisell2.text.cancel"),
      centered: true,
      onOk: onResolve
    });
  };
  const { run: debouncedHandleClose } = (0, import_ahooks.useDebounceFn)(handleClose, {
    wait: 500,
    leading: true,
    trailing: false
  });
  const syncServiceValueChange = (nextServiceState) => {
    const nextValue = nextServiceState == null ? void 0 : nextServiceState.value;
    if (!Array.isArray(nextValue)) {
      return false;
    }
    const nextService = {
      ...state.service,
      ...nextServiceState,
      value: nextValue,
      edit: true
    };
    const nextState = {
      ...state,
      service: nextService
    };
    dispatch({
      type: "setService",
      payload: nextService
    });
    onStateChange(nextState);
    return true;
  };
  const handleListChange = async (nextServiceState) => {
    var _a2, _b2, _c2;
    const hasSyncedServiceValue = syncServiceValueChange(nextServiceState);
    if (hasSyncedServiceValue) {
      return;
    }
    if (!(state == null ? void 0 : state.isBookingTicket2)) {
      return;
    }
    const currentItem = nextServiceState == null ? void 0 : nextServiceState.cacheItem;
    if (!currentItem) {
      return;
    }
    const holderConfig = ((_a2 = state == null ? void 0 : state.bookingConfig) == null ? void 0 : _a2.holder) || {};
    const currentMaxSelectedCount = (holderConfig == null ? void 0 : holderConfig.maxSelectedCount) || ((_b2 = currentItem == null ? void 0 : currentItem._extend) == null ? void 0 : _b2.quantity) || 1;
    const currentHolderId = (_c2 = currentItem == null ? void 0 : currentItem._extend) == null ? void 0 : _c2.holder_id;
    const initialValue = currentHolderId ? Array.isArray(currentHolderId) ? currentHolderId : [currentHolderId] : void 0;
    const result = await (0, import_selectHolderModal.selectHolderModal)({
      state,
      dispatch,
      initialValue,
      maxSelectedCount: currentMaxSelectedCount
    });
    if (!(result == null ? void 0 : result.length)) {
      return;
    }
    const nextValue = updateProductHolder(state, currentItem, result);
    const nextState = {
      ...state,
      service: {
        ...state.service,
        value: nextValue,
        edit: true
      }
    };
    dispatch({
      type: "setService",
      payload: nextState.service
    });
    onStateChange(nextState);
  };
  if (!open) {
    return null;
  }
  const unassignedCount = calculateUnassignedHolderCount(state);
  const title = import_utils.locales.getText("pisell2.text.holder-unassigned")(unassignedCount);
  const hintText = import_utils.locales.getText("pisell2.text.press-card-assign-holder");
  return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement(
    import_materials.PisellContainer,
    {
      renderType: "modal",
      props: {
        open,
        onCancel: debouncedHandleClose,
        title,
        footer: null,
        platform: "pc",
        width: 800,
        destroyOnClose: true,
        maskClosable: false,
        closable: true
      }
    },
    /* @__PURE__ */ import_react.default.createElement("div", { className: "confirm-holder-modal-content" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "confirm-holder-modal-hint" }, hintText), /* @__PURE__ */ import_react.default.createElement("div", { className: "confirm-holder-modal-service" }, /* @__PURE__ */ import_react.default.createElement(
      import_Lists.default,
      {
        isParallelResource: true,
        isShowDelete: false,
        isShowAmountFooter: false,
        onChange: handleListChange
      }
    )), /* @__PURE__ */ import_react.default.createElement("div", { className: "confirm-holder-modal-footer" }, ((_c = (_b = (_a = state == null ? void 0 : state.bookingConfig) == null ? void 0 : _a.config) == null ? void 0 : _b.basic) == null ? void 0 : _c.subject_require) !== "require" ? /* @__PURE__ */ import_react.default.createElement(import_antd.Button, { onClick: onResolve, className: "skip-button", size: "large" }, import_utils.locales.getText("pisell2.text.skip-for-now")) : null, /* @__PURE__ */ import_react.default.createElement(import_antd.Button, { type: "primary", onClick: onResolve, className: "confirm-button" }, import_utils.locales.getText("pisell2.text.confirm"))))
  ), !(state == null ? void 0 : state.isBookingTicket2) ? /* @__PURE__ */ import_react.default.createElement(import_selectHolderModal.SelectHolderModal, null) : null);
};
var HolderAssignmentConfirmModal = () => {
  const bookingContext = (0, import_react.useContext)(import_model.Context);
  const [open, setOpen] = (0, import_react.useState)(false);
  const [request, setRequest] = (0, import_react.useState)(
    null
  );
  const [modalState, setModalState] = (0, import_react.useState)(null);
  const requestRef = (0, import_react.useRef)(null);
  const bookingContextRef = (0, import_react.useRef)(bookingContext);
  requestRef.current = request;
  bookingContextRef.current = bookingContext;
  const handleResolve = () => {
    setOpen(false);
    const currentRequest = requestRef.current;
    if (currentRequest) {
      settleHolderAssignmentConfirmRequest(currentRequest, true);
    }
    setTimeout(() => {
      setRequest(null);
    }, 300);
  };
  (0, import_react.useLayoutEffect)(() => {
    const subscriber = (nextRequest) => {
      var _a;
      if (!nextRequest) {
        setOpen(false);
        setTimeout(() => {
          setRequest(null);
        }, 300);
        return false;
      }
      if (nextRequest.state !== ((_a = bookingContextRef.current) == null ? void 0 : _a.state)) {
        return false;
      }
      setRequest(nextRequest);
      setModalState(nextRequest.state);
      setOpen(true);
      return true;
    };
    holderAssignmentConfirmSubscribers.add(subscriber);
    return () => {
      holderAssignmentConfirmSubscribers.delete(subscriber);
      const currentRequest = requestRef.current;
      if (currentRequest) {
        settleHolderAssignmentConfirmRequest(currentRequest, false);
      }
    };
  }, []);
  if (!request || !modalState) {
    return null;
  }
  return /* @__PURE__ */ import_react.default.createElement(import_model.Context.Provider, { value: { state: modalState, dispatch: bookingContext == null ? void 0 : bookingContext.dispatch } }, /* @__PURE__ */ import_react.default.createElement(
    HolderAssignmentConfirmContent,
    {
      state: modalState,
      dispatch: bookingContext == null ? void 0 : bookingContext.dispatch,
      open,
      onResolve: handleResolve,
      onStateChange: setModalState
    }
  ));
};
function showHolderAssignmentConfirmModal(state) {
  if (activeHolderAssignmentConfirm) {
    settleHolderAssignmentConfirmRequest(activeHolderAssignmentConfirm, false);
  }
  return new Promise((resolve) => {
    const request = {
      id: Symbol("HolderAssignmentConfirmRequest"),
      state,
      resolve,
      settled: false
    };
    activeHolderAssignmentConfirm = request;
    const handledCount = notifyHolderAssignmentConfirmHost(request);
    if (handledCount === 0) {
      console.warn(
        "HolderAssignmentConfirmModal host is not mounted. Please render <HolderAssignmentConfirmModal /> in your booking component tree."
      );
      settleHolderAssignmentConfirmRequest(request, false);
    }
  });
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  HolderAssignmentConfirmModal,
  showHolderAssignmentConfirmModal
});
