function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
import React, { createContext, useContext, useEffect, useMemo, useState } from 'react';
import { useMemoizedFn } from 'ahooks';
import { getPetsData } from "../../../components/ticketBooking/serve";
import { isWalkIn } from "../../../components/booking/utils";
import { SalesSdkContext } from "./SalesSdkContext";
import { buildHolderListRequestParams, resolveHolderDisplayConfig } from "../utils/enrichCartLineHolderDisplay";
import { formatHolderOptions, mergeHolderOptions } from "../utils/formatHolderOptions";
import { registerHolderOptionsSyncBridge } from "../utils/holderOptionsSyncBridge";
export var SalesSdkHolderContext = /*#__PURE__*/createContext(null);
SalesSdkHolderContext.displayName = 'SalesSdkHolderContext';
var EMPTY_HOLDER_OPTIONS = [];
var DEFAULT_DISPLAY_CONFIG = resolveHolderDisplayConfig(null);
function resolveHolderCustomerId(bookingTicket) {
  var _bookingTicket$getOrd, _bookingTicket$getTem;
  var fromSnapshot = bookingTicket === null || bookingTicket === void 0 || (_bookingTicket$getOrd = bookingTicket.getOrderCustomerSnapshot) === null || _bookingTicket$getOrd === void 0 || (_bookingTicket$getOrd = _bookingTicket$getOrd.call(bookingTicket)) === null || _bookingTicket$getOrd === void 0 ? void 0 : _bookingTicket$getOrd.id;
  var fromTempOrder = bookingTicket === null || bookingTicket === void 0 || (_bookingTicket$getTem = bookingTicket.getTempOrder) === null || _bookingTicket$getTem === void 0 || (_bookingTicket$getTem = _bookingTicket$getTem.call(bookingTicket)) === null || _bookingTicket$getTem === void 0 ? void 0 : _bookingTicket$getTem.customer_id;
  var resolved = fromSnapshot !== null && fromSnapshot !== void 0 ? fromSnapshot : fromTempOrder;
  if (resolved === undefined || resolved === null || resolved === '') return undefined;
  return resolved;
}

/**
 * 按当前 customer + bookingConfig 拉取可选 Holder 列表，供 Cart 展示 enrich 使用。
 */
export var SalesSdkHolderProvider = function SalesSdkHolderProvider(_ref) {
  var _sales$bookingTicket, _bookingTicket$getBoo, _bookingTicket$getBoo2;
  var children = _ref.children;
  var sales = useContext(SalesSdkContext);
  var bookingTicket = (_sales$bookingTicket = sales === null || sales === void 0 ? void 0 : sales.bookingTicket) !== null && _sales$bookingTicket !== void 0 ? _sales$bookingTicket : null;
  var _useState = useState(EMPTY_HOLDER_OPTIONS),
    _useState2 = _slicedToArray(_useState, 2),
    serverHolderOptions = _useState2[0],
    setServerHolderOptions = _useState2[1];
  var _useState3 = useState(EMPTY_HOLDER_OPTIONS),
    _useState4 = _slicedToArray(_useState3, 2),
    optimisticHolderOptions = _useState4[0],
    setOptimisticHolderOptions = _useState4[1];
  var _useState5 = useState(false),
    _useState6 = _slicedToArray(_useState5, 2),
    loading = _useState6[0],
    setLoading = _useState6[1];
  var _useState7 = useState(0),
    _useState8 = _slicedToArray(_useState7, 2),
    reloadToken = _useState8[0],
    setReloadToken = _useState8[1];
  var bookingConfig = (_bookingTicket$getBoo = bookingTicket === null || bookingTicket === void 0 || (_bookingTicket$getBoo2 = bookingTicket.getBookingConfig) === null || _bookingTicket$getBoo2 === void 0 ? void 0 : _bookingTicket$getBoo2.call(bookingTicket)) !== null && _bookingTicket$getBoo !== void 0 ? _bookingTicket$getBoo : null;
  var customerId = resolveHolderCustomerId(bookingTicket);
  var holderConfigKey = useMemo(function () {
    var _bookingConfig$config, _holder$form, _holder$form2;
    var subject = bookingConfig === null || bookingConfig === void 0 || (_bookingConfig$config = bookingConfig.config) === null || _bookingConfig$config === void 0 || (_bookingConfig$config = _bookingConfig$config.basic) === null || _bookingConfig$config === void 0 ? void 0 : _bookingConfig$config.appointment_subject;
    var holder = bookingConfig === null || bookingConfig === void 0 ? void 0 : bookingConfig.holder;
    return [subject === null || subject === void 0 ? void 0 : subject.type, subject === null || subject === void 0 ? void 0 : subject.form_id, holder === null || holder === void 0 ? void 0 : holder.data_range, holder === null || holder === void 0 || (_holder$form = holder.form) === null || _holder$form === void 0 ? void 0 : _holder$form.id, holder === null || holder === void 0 || (_holder$form2 = holder.form) === null || _holder$form2 === void 0 ? void 0 : _holder$form2.is_franchisor].join('|');
  }, [bookingConfig]);
  var displayConfig = useMemo(function () {
    return resolveHolderDisplayConfig(bookingConfig);
  }, [holderConfigKey]);
  var holderOptions = useMemo(function () {
    return mergeHolderOptions(optimisticHolderOptions, serverHolderOptions);
  }, [optimisticHolderOptions, serverHolderOptions]);

  // 客户 / 配置切换时清空乐观缓存，避免跨客户残留
  useEffect(function () {
    setOptimisticHolderOptions(EMPTY_HOLDER_OPTIONS);
  }, [holderConfigKey, customerId]);
  var reload = useMemoizedFn(function () {
    setReloadToken(function (token) {
      return token + 1;
    });
  });
  var upsertHolderOptions = useMemoizedFn(function (rawHolders) {
    var incoming = formatHolderOptions(rawHolders);
    if (incoming.length === 0) return;
    setOptimisticHolderOptions(function (prev) {
      return mergeHolderOptions(prev, incoming);
    });
  });
  useEffect(function () {
    return registerHolderOptionsSyncBridge({
      upsertHolderOptions: upsertHolderOptions,
      reload: reload
    });
  }, [upsertHolderOptions, reload]);
  useEffect(function () {
    if (!bookingTicket) {
      setServerHolderOptions(EMPTY_HOLDER_OPTIONS);
      return;
    }
    var holder = bookingConfig === null || bookingConfig === void 0 ? void 0 : bookingConfig.holder;
    if (!holder) {
      setServerHolderOptions(EMPTY_HOLDER_OPTIONS);
      return;
    }
    if ((holder === null || holder === void 0 ? void 0 : holder.data_range) === 'customer' && isWalkIn(customerId)) {
      setServerHolderOptions(EMPTY_HOLDER_OPTIONS);
      return;
    }
    var params = buildHolderListRequestParams({
      bookingConfig: bookingConfig,
      customerId: customerId
    });
    if (!params) {
      setServerHolderOptions(EMPTY_HOLDER_OPTIONS);
      return;
    }
    var cancelled = false;
    setLoading(true);
    getPetsData(params).then(function (data) {
      if (cancelled) return;
      var fromServer = formatHolderOptions((data === null || data === void 0 ? void 0 : data.list) || []);
      setServerHolderOptions(fromServer);
      var serverIds = new Set(fromServer.map(function (option) {
        return String(option.id);
      }));
      setOptimisticHolderOptions(function (prev) {
        return prev.filter(function (option) {
          return !serverIds.has(String(option.id));
        });
      });
    }).catch(function (err) {
      if (cancelled) return;
      console.warn('[SalesSdk] load holderOptions failed', err);
      setServerHolderOptions(EMPTY_HOLDER_OPTIONS);
    }).finally(function () {
      if (!cancelled) setLoading(false);
    });
    return function () {
      cancelled = true;
    };
  }, [bookingTicket, holderConfigKey, customerId, reloadToken]);
  useEffect(function () {
    var _bookingTicket$effect, _bookingTicket$effect2;
    if (!bookingTicket) return;
    var refresh = function refresh() {
      return reload();
    };
    var offs = [(_bookingTicket$effect = bookingTicket.effectsOn) === null || _bookingTicket$effect === void 0 ? void 0 : _bookingTicket$effect.call(bookingTicket, 'onOrderCustomerChange', refresh), (_bookingTicket$effect2 = bookingTicket.effectsOn) === null || _bookingTicket$effect2 === void 0 ? void 0 : _bookingTicket$effect2.call(bookingTicket, 'onSalesOrderLoaded', refresh)].filter(Boolean);
    return function () {
      offs.forEach(function (off) {
        try {
          off === null || off === void 0 || off();
        } catch (_unused) {
          /* swallow on teardown */
        }
      });
    };
  }, [bookingTicket, reload]);
  var value = useMemo(function () {
    return {
      holderOptions: holderOptions,
      loading: loading,
      displayConfig: displayConfig,
      reload: reload,
      upsertHolderOptions: upsertHolderOptions
    };
  }, [holderOptions, loading, displayConfig, reload, upsertHolderOptions]);
  return /*#__PURE__*/React.createElement(SalesSdkHolderContext.Provider, {
    value: value
  }, children);
};

/**
 * 读取 SDK 级 Holder 字典（须在 SalesSdkHolderProvider 内调用）。
 */
export function useSalesSdkHolder() {
  var ctx = useContext(SalesSdkHolderContext);
  if (!ctx) {
    throw new Error('[SalesSdk] useSalesSdkHolder 必须在 <SalesSdkHolderProvider> 内调用');
  }
  return ctx;
}

/**
 * CartProvider 内部使用：Provider 未挂载时返回空字典，避免硬依赖。
 */
export function useSalesSdkHolderOptional() {
  var ctx = useContext(SalesSdkHolderContext);
  return ctx !== null && ctx !== void 0 ? ctx : {
    holderOptions: EMPTY_HOLDER_OPTIONS,
    loading: false,
    displayConfig: DEFAULT_DISPLAY_CONFIG,
    reload: function reload() {
      return undefined;
    },
    upsertHolderOptions: function upsertHolderOptions() {
      return undefined;
    }
  };
}