var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/plus/salesSdk/bookingEditService/useBookingEditPetState.ts
var useBookingEditPetState_exports = {};
__export(useBookingEditPetState_exports, {
  useBookingEditPetState: () => useBookingEditPetState
});
module.exports = __toCommonJS(useBookingEditPetState_exports);
var import_react = require("react");
var import_ahooks = require("ahooks");
var import_serve = require("../../../components/ticketBooking/serve");
var import_utils = require("../../../components/booking/utils");
var import_utils2 = require("../../../utils");
var import_waiverFormDetailCache = require("../../../components/booking/utils/waiverFormDetailCache");
var import_enrichCartLineHolderDisplay = require("../utils/enrichCartLineHolderDisplay");
var import_productHolderConfig = require("../utils/productHolderConfig");
var import_productHolderFormDetailCache = require("../utils/productHolderFormDetailCache");
function buildHolderFormDataConfig(holder, holderSource, holderFormDetail) {
  if (!holder) return null;
  const productFormId = (0, import_productHolderConfig.getProductHolderFormId)(holderSource);
  const holderForm = (holder == null ? void 0 : holder.form) || {};
  const currentForm = holderFormDetail || holderForm;
  const formField = (currentForm == null ? void 0 : currentForm.form_field) ?? (currentForm == null ? void 0 : currentForm.field) ?? (holderForm == null ? void 0 : holderForm.form_field);
  return {
    ...holder,
    ...holderForm,
    ...currentForm,
    options: [],
    form_id: productFormId ?? (currentForm == null ? void 0 : currentForm.id) ?? (currentForm == null ? void 0 : currentForm.form_id) ?? (holderForm == null ? void 0 : holderForm.id),
    form_field: formField,
    field: formField,
    relation_type: "appointment_booking",
    form_record: []
  };
}
function getMinorLinkedTableId(formDataConfig) {
  var _a, _b;
  const detail = (_a = formDataConfig == null ? void 0 : formDataConfig.form_field) == null ? void 0 : _a.find(
    (item) => item.filed_type === "form_to_form" && item.status === "hide"
  );
  return ((_b = detail == null ? void 0 : detail.setting) == null ? void 0 : _b.linkedTable) ?? null;
}
function useBookingEditPetState(open, baseBookingState, setRequest, holderSeed, holderSeedRequestKey, holderSource) {
  var _a, _b, _c;
  const [pet, setPet] = (0, import_react.useState)({});
  const effectRunRef = (0, import_react.useRef)(0);
  const previousDepsRef = (0, import_react.useRef)({});
  const holderSourceFormId = (0, import_productHolderConfig.getProductHolderFormId)(holderSource);
  const stableHolderSource = (0, import_react.useMemo)(
    () => holderSourceFormId ? {
      holder_config: {
        status: "enable",
        resource_id: holderSourceFormId
      }
    } : void 0,
    [holderSourceFormId]
  );
  const apis = (0, import_react.useMemo)(
    () => ({
      getPetsData: import_serve.getPetsData
    }),
    []
  );
  const dispatch = (0, import_ahooks.useMemoizedFn)((cmd) => {
    if (cmd.type === "setPet" && cmd.payload) {
      setPet((prev) => ({ ...prev, ...cmd.payload }));
    }
  });
  (0, import_react.useEffect)(() => {
    var _a2, _b2, _c2, _d;
    effectRunRef.current += 1;
    const previousDeps = previousDepsRef.current;
    previousDepsRef.current = {
      holderSeed,
      holderSourceFormId,
      holder: (_a2 = baseBookingState.bookingConfig) == null ? void 0 : _a2.holder
    };
    if (!open) {
      setPet({});
      return;
    }
    const holder = (_b2 = baseBookingState.bookingConfig) == null ? void 0 : _b2.holder;
    const productHolderFormId = holderSourceFormId;
    const customerId = (_d = (_c2 = baseBookingState.client) == null ? void 0 : _c2.value) == null ? void 0 : _d.id;
    let cancelled = false;
    const syncHolderFormData = async () => {
      try {
        const holderFormDetail = productHolderFormId ? await (0, import_productHolderFormDetailCache.getCachedProductHolderFormDetail)(Number(productHolderFormId)) : null;
        if (cancelled) return;
        const formDataConfig = buildHolderFormDataConfig(
          holder,
          stableHolderSource,
          holderFormDetail
        );
        setPet((prev) => ({
          ...prev,
          ...formDataConfig ? { formData: [formDataConfig] } : {}
        }));
        const linkedTableId = getMinorLinkedTableId(formDataConfig);
        if (linkedTableId) {
          const waiverForm = await (0, import_waiverFormDetailCache.getCachedWaiverFormDetail)(Number(linkedTableId));
          if (cancelled) return;
          setPet((prev) => ({ ...prev, waiverForm }));
        }
      } catch (err) {
        console.warn("[SalesSdk] load holder form detail failed", err);
      }
    };
    if (setRequest) {
      import_utils.request.setRequest(setRequest);
      import_utils2.request.setRequest(setRequest);
    }
    const params = (0, import_enrichCartLineHolderDisplay.buildHolderListRequestParams)({
      bookingConfig: baseBookingState.bookingConfig,
      customerId,
      source: stableHolderSource
    });
    if (!params) return;
    const requestKey = (0, import_enrichCartLineHolderDisplay.buildHolderListRequestKey)(params);
    syncHolderFormData();
    const cleanup = () => {
      cancelled = true;
    };
    if ((holderSeed == null ? void 0 : holderSeed.length) && holderSeedRequestKey === requestKey) {
      setPet((prev) => ({
        ...prev,
        holders: holderSeed
      }));
      return cleanup;
    }
    (0, import_serve.getPetsData)(params).then((data) => {
      const list = Array.isArray(data == null ? void 0 : data.list) ? data.list : [];
      setPet((prev) => ({
        ...prev,
        holders: list
      }));
    }).catch((err) => {
      console.warn("[SalesSdk] load holders failed", err);
    });
    return cleanup;
  }, [
    open,
    (_a = baseBookingState.bookingConfig) == null ? void 0 : _a.holder,
    (_c = (_b = baseBookingState.client) == null ? void 0 : _b.value) == null ? void 0 : _c.id,
    setRequest,
    holderSeed,
    holderSeedRequestKey,
    holderSourceFormId,
    stableHolderSource
  ]);
  return { pet, dispatch, apis };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  useBookingEditPetState
});
