function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
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; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
import React, { useState, useEffect, useMemo, useRef } from 'react';
import { createPortal } from 'react-dom';
import { locales } from '@pisell/utils';
import { isWalkIn } from "../utils";
import PisellSelectHolder from "../../../plus/selectHolder";
import { reloadGlobalHolderOptions, syncHolderOptionsFromRaw } from "../../../plus/salesSdk/utils/holderOptionsSyncBridge";
// 全局状态管理
var modalState = null;

// 存储所有实例的 setState 函数
var allSetStateCallbacks = new Set();

// 当前渲染的实例 ID（确保只有一个实例渲染）
var renderingInstanceId = null;

// 通知所有实例更新状态
function notifyAllInstances(newState) {
  modalState = newState;
  allSetStateCallbacks.forEach(function (setState) {
    setState(newState);
  });
}

/**
 * 获取 formDataConfig 和 isMinorAndWaiver
 */
function getFormDataConfig(state) {
  var _state$bookingConfig, _holder$form, _holder$form2;
  var _holder = state === null || state === void 0 || (_state$bookingConfig = state.bookingConfig) === null || _state$bookingConfig === void 0 ? void 0 : _state$bookingConfig.holder;
  if (!_holder) {
    return {
      formDataConfig: null,
      isMinorAndWaiver: false
    };
  }
  var formDataConfig = _objectSpread(_objectSpread(_objectSpread({}, _holder), _holder === null || _holder === void 0 ? void 0 : _holder.form), {}, {
    options: [],
    form_id: _holder === null || _holder === void 0 || (_holder$form = _holder.form) === null || _holder$form === void 0 ? void 0 : _holder$form.id,
    field: _holder === null || _holder === void 0 || (_holder$form2 = _holder.form) === null || _holder$form2 === void 0 ? void 0 : _holder$form2.form_field,
    relation_type: 'appointment_booking',
    form_record: []
  });

  // 是Minor并且与Waiver关联
  var isMinorAndWaiver = false;
  if ((formDataConfig === null || formDataConfig === void 0 ? void 0 : formDataConfig.form_type) === 'minors') {
    var _formDataConfig$form_;
    var detail = formDataConfig === null || formDataConfig === void 0 || (_formDataConfig$form_ = formDataConfig.form_field) === null || _formDataConfig$form_ === void 0 ? void 0 : _formDataConfig$form_.find(function (item) {
      return item.filed_type === 'form_to_form' && item.status === 'hide';
    });
    if (detail) {
      var _detail$setting;
      isMinorAndWaiver = detail === null || detail === void 0 || (_detail$setting = detail.setting) === null || _detail$setting === void 0 ? void 0 : _detail$setting.linkedTable;
    }
  }
  return {
    formDataConfig: formDataConfig,
    isMinorAndWaiver: isMinorAndWaiver
  };
}

/**
 * 获取 holder 选项列表
 */
function getHolderOptions(state) {
  var _state$pet, _state$bookingConfig2, _state$pet2, _state$pet3;
  var holdersFromState = Array.isArray(state === null || state === void 0 || (_state$pet = state.pet) === null || _state$pet === void 0 ? void 0 : _state$pet.holders) ? state.pet.holders : [];
  var formId = (state === null || state === void 0 || (_state$bookingConfig2 = state.bookingConfig) === null || _state$bookingConfig2 === void 0 || (_state$bookingConfig2 = _state$bookingConfig2.config) === null || _state$bookingConfig2 === void 0 || (_state$bookingConfig2 = _state$bookingConfig2.basic) === null || _state$bookingConfig2 === void 0 || (_state$bookingConfig2 = _state$bookingConfig2.appointment_subject) === null || _state$bookingConfig2 === void 0 ? void 0 : _state$bookingConfig2.form_id) || 0;
  var holdersFromValue = Array.isArray(state === null || state === void 0 || (_state$pet2 = state.pet) === null || _state$pet2 === void 0 || (_state$pet2 = _state$pet2.value) === null || _state$pet2 === void 0 ? void 0 : _state$pet2[formId]) ? state === null || state === void 0 || (_state$pet3 = state.pet) === null || _state$pet3 === void 0 || (_state$pet3 = _state$pet3.value) === null || _state$pet3 === void 0 ? void 0 : _state$pet3[formId] : [];
  var rawList = holdersFromState.length > 0 ? holdersFromState : holdersFromValue;
  return rawList.map(function (item) {
    var id = (item === null || item === void 0 ? void 0 : item.id) || (item === null || item === void 0 ? void 0 : item.form_record_id) || (item === null || item === void 0 ? void 0 : item.value);
    if (id === undefined || id === null) return null;
    return {
      label: (item === null || item === void 0 ? void 0 : item.main_field) || (item === null || item === void 0 ? void 0 : item.label) || (item === null || item === void 0 ? void 0 : item.name) || locales.getText('pisell-select-holder-please-select'),
      value: id,
      avatar: item === null || item === void 0 ? void 0 : item.avatar,
      subtitle: (item === null || item === void 0 ? void 0 : item.subtitle) || (item === null || item === void 0 ? void 0 : item.second_field) || (item === null || item === void 0 ? void 0 : item.sub_field)
    };
  }).filter(Boolean);
}

/**
 * 构建 displayConfig
 */
function buildDisplayConfig(state, holderOptions) {
  var _state$bookingConfig3;
  var maxSelectedCount = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
  var selectType = maxSelectedCount > 1 ? 'multiple' : 'single';
  return {
    direction: 'vertical',
    selectType: selectType,
    showAvatar: true,
    showTitle: true,
    showSubtitle: Boolean(holderOptions.some(function (option) {
      return option.subtitle;
    })),
    isSkipable: (state === null || state === void 0 || (_state$bookingConfig3 = state.bookingConfig) === null || _state$bookingConfig3 === void 0 || (_state$bookingConfig3 = _state$bookingConfig3.config) === null || _state$bookingConfig3 === void 0 || (_state$bookingConfig3 = _state$bookingConfig3.basic) === null || _state$bookingConfig3 === void 0 ? void 0 : _state$bookingConfig3.subject_require) === 'optional'
  };
}

/**
 * SelectHolderModal 组件（单例模式）
 * 使用 Portal 在 body 上渲染，确保全局只有一个实例
 * 可以在多个地方挂载，但实际只会渲染一个实例
 */
export var SelectHolderModal = function SelectHolderModal() {
  var _useState = useState(modalState),
    _useState2 = _slicedToArray(_useState, 2),
    localState = _useState2[0],
    setLocalState = _useState2[1];
  var _useState3 = useState(null),
    _useState4 = _slicedToArray(_useState3, 2),
    container = _useState4[0],
    setContainer = _useState4[1];
  var instanceIdRef = useRef(Symbol('SelectHolderModal'));
  var isRenderingInstanceRef = useRef(false);
  useEffect(function () {
    // 创建或获取单例容器
    var containerElement = document.getElementById('select-holder-modal-container');
    if (!containerElement) {
      containerElement = document.createElement('div');
      containerElement.id = 'select-holder-modal-container';
      document.body.appendChild(containerElement);
    }
    setContainer(containerElement);

    // 如果还没有渲染实例，将当前实例设为渲染实例
    if (renderingInstanceId === null) {
      renderingInstanceId = instanceIdRef.current;
      isRenderingInstanceRef.current = true;
    } else {
      isRenderingInstanceRef.current = renderingInstanceId === instanceIdRef.current;
    }

    // 注册当前实例的 setState
    allSetStateCallbacks.add(setLocalState);

    // 初始化时同步一次状态
    if (modalState && modalState !== localState) {
      setLocalState(modalState);
    }
    return function () {
      // 移除当前实例的 setState
      allSetStateCallbacks.delete(setLocalState);
      // 如果当前实例是渲染实例，清理渲染实例标识
      if (isRenderingInstanceRef.current) {
        renderingInstanceId = null;
      }
    };
  }, []);

  // 如果 localState 不存在或 open 为 false，不渲染
  if (!localState || !localState.open || !container) {
    return null;
  }

  // 确保只有渲染实例才能渲染
  if (!isRenderingInstanceRef.current) {
    return null;
  }
  var state = localState.state,
    dispatch = localState.dispatch,
    initialValue = localState.initialValue,
    maxSelectedCount = localState.maxSelectedCount,
    resolve = localState.resolve;

  // 使用 Portal 渲染到 body，确保单例
  return /*#__PURE__*/createPortal( /*#__PURE__*/React.createElement(SelectHolderModalContent, {
    state: state,
    dispatch: dispatch,
    initialValue: initialValue,
    maxSelectedCount: maxSelectedCount,
    resolve: resolve,
    onClose: function onClose() {
      // 延迟清理全局状态，确保动画完成（300ms 动画 + 50ms 缓冲）
      setTimeout(function () {
        notifyAllInstances(null);
      }, 350);
    }
  }), container);
};

/**
 * SelectHolderModal 内容组件
 */
var SelectHolderModalContent = function SelectHolderModalContent(_ref) {
  var _stateRef$current2, _stateRef$current3, _holderConfig$form;
  var state = _ref.state,
    dispatch = _ref.dispatch,
    initialValue = _ref.initialValue,
    maxSelectedCount = _ref.maxSelectedCount,
    resolve = _ref.resolve,
    onClose = _ref.onClose;
  var _useState5 = useState(true),
    _useState6 = _slicedToArray(_useState5, 2),
    open = _useState6[0],
    setOpen = _useState6[1];
  var _useState7 = useState(function () {
      return getHolderOptions(state);
    }),
    _useState8 = _slicedToArray(_useState7, 2),
    holderOptions = _useState8[0],
    setHolderOptions = _useState8[1];
  var _useState9 = useState(function () {
      if (Array.isArray(initialValue)) {
        return initialValue.filter(function (item) {
          return item !== undefined && item !== null;
        });
      }
      if (initialValue === undefined || initialValue === null || initialValue === '') {
        return [];
      }
      return [initialValue];
    }),
    _useState10 = _slicedToArray(_useState9, 2),
    selectedValues = _useState10[0],
    setSelectedValues = _useState10[1];

  // 使用 ref 存储最新的 state，以便在组件内部访问
  var stateRef = {
    current: state
  };

  // 更新 stateRef
  useEffect(function () {
    stateRef.current = state;
    // 当 state 更新时，同步更新 holderOptions
    var newOptions = getHolderOptions(state);
    setHolderOptions(newOptions);
  }, [state]);
  var displayConfig = useMemo(function () {
    var _stateRef$current;
    return buildDisplayConfig(stateRef.current, holderOptions, maxSelectedCount || ((_stateRef$current = stateRef.current) === null || _stateRef$current === void 0 || (_stateRef$current = _stateRef$current.bookingConfig) === null || _stateRef$current === void 0 || (_stateRef$current = _stateRef$current.holder) === null || _stateRef$current === void 0 ? void 0 : _stateRef$current.maxSelectedCount) || 1);
  }, [holderOptions, maxSelectedCount, state]);

  // 获取 formDataConfig
  var _useMemo = useMemo(function () {
      return getFormDataConfig(stateRef.current);
    }, [(_stateRef$current2 = stateRef.current) === null || _stateRef$current2 === void 0 || (_stateRef$current2 = _stateRef$current2.bookingConfig) === null || _stateRef$current2 === void 0 ? void 0 : _stateRef$current2.holder]),
    formDataConfig = _useMemo.formDataConfig,
    isMinorAndWaiver = _useMemo.isMinorAndWaiver;
  var holderConfig = ((_stateRef$current3 = stateRef.current) === null || _stateRef$current3 === void 0 || (_stateRef$current3 = _stateRef$current3.bookingConfig) === null || _stateRef$current3 === void 0 ? void 0 : _stateRef$current3.holder) || {};
  var title = (holderConfig === null || holderConfig === void 0 || (_holderConfig$form = holderConfig.form) === null || _holderConfig$form === void 0 ? void 0 : _holderConfig$form.title) || (holderConfig === null || holderConfig === void 0 ? void 0 : holderConfig.title) || locales.getText('pisell2.text.holder');

  // 更新 state 中的 holders
  var updateStateHolders = function updateStateHolders(holders) {
    dispatch({
      type: 'setPet',
      payload: {
        holders: holders
      }
    });
  };
  var handleClose = function handleClose() {
    setOpen(false);
    // 先调用 resolve，再关闭
    if (resolve) {
      resolve(null);
    }
    // 延迟关闭，确保动画完成
    setTimeout(function () {
      onClose();
    }, 300);
  };
  var handleConfirm = function handleConfirm(nextValues) {
    setOpen(false);
    // 先调用 resolve，再关闭
    if (resolve) {
      if (nextValues && nextValues.length > 0) {
        var _currentState$pet;
        var selectedIds = nextValues.map(function (val) {
          return Number(val);
        });
        var currentState = stateRef.current;
        var holders = (currentState === null || currentState === void 0 || (_currentState$pet = currentState.pet) === null || _currentState$pet === void 0 ? void 0 : _currentState$pet.holders) || [];
        var matched = holders.filter(function (item) {
          var _ref2, _item$form_record_id;
          var id = (_ref2 = (_item$form_record_id = item === null || item === void 0 ? void 0 : item.form_record_id) !== null && _item$form_record_id !== void 0 ? _item$form_record_id : item === null || item === void 0 ? void 0 : item.id) !== null && _ref2 !== void 0 ? _ref2 : item === null || item === void 0 ? void 0 : item.value;
          return selectedIds.some(function (selectedId) {
            return String(selectedId) === String(id);
          });
        });
        if (matched.length) {
          syncHolderOptionsFromRaw(matched);
        }
        reloadGlobalHolderOptions();
        resolve(selectedIds);
      } else {
        resolve(null);
      }
    }
    // 延迟关闭，确保动画完成
    setTimeout(function () {
      onClose();
    }, 300);
  };
  var handleAdd = function handleAdd() {
    var _currentState$pet2, _currentState$client, _currentState$client2, _currentState$pet$for, _currentState$pet$for2;
    var currentState = stateRef.current;
    var waiverForm = currentState === null || currentState === void 0 || (_currentState$pet2 = currentState.pet) === null || _currentState$pet2 === void 0 ? void 0 : _currentState$pet2.waiverForm;
    currentState.action({
      type: 'pisell1.goCustomFormAddData',
      data: {
        zIndex: 1101,
        customerId: (_currentState$client = currentState.client) === null || _currentState$client === void 0 || (_currentState$client = _currentState$client.value) === null || _currentState$client === void 0 ? void 0 : _currentState$client.id,
        formDataConfig: isMinorAndWaiver ? _objectSpread(_objectSpread({}, waiverForm), {}, {
          customer_id: (_currentState$client2 = currentState.client) === null || _currentState$client2 === void 0 || (_currentState$client2 = _currentState$client2.value) === null || _currentState$client2 === void 0 ? void 0 : _currentState$client2.id,
          is_franchisor: (_currentState$pet$for = currentState.pet.formData) === null || _currentState$pet$for === void 0 || (_currentState$pet$for = _currentState$pet$for[0]) === null || _currentState$pet$for === void 0 ? void 0 : _currentState$pet$for.is_franchisor
        }) : _objectSpread({}, ((_currentState$pet$for2 = currentState.pet.formData) === null || _currentState$pet$for2 === void 0 ? void 0 : _currentState$pet$for2[0]) || {})
      },
      callback: function callback(res) {
        var _currentState$client3;
        var obj = {};
        var _iterator = _createForOfIteratorHelper(res),
          _step;
        try {
          for (_iterator.s(); !(_step = _iterator.n()).done;) {
            var item = _step.value;
            obj[item.key] = item.value;
          }
        } catch (err) {
          _iterator.e(err);
        } finally {
          _iterator.f();
        }
        var isWalkInBol = isWalkIn((_currentState$client3 = currentState.client) === null || _currentState$client3 === void 0 || (_currentState$client3 = _currentState$client3.value) === null || _currentState$client3 === void 0 ? void 0 : _currentState$client3.id);
        var newHolders = !isWalkInBol ? [obj].concat(_toConsumableArray(currentState.pet.holders || [])) : currentState.pet.holders || [];
        updateStateHolders(newHolders);

        // 更新 stateRef 和 holderOptions
        var updatedState = _objectSpread(_objectSpread({}, currentState), {}, {
          pet: _objectSpread(_objectSpread({}, currentState.pet), {}, {
            holders: newHolders
          })
        });
        stateRef.current = updatedState;

        // 更新 holderOptions
        var newOptions = getHolderOptions(updatedState);
        setHolderOptions(newOptions);
        syncHolderOptionsFromRaw([obj]);
      }
    });
    // 添加 holder 后，弹窗保持打开状态，等待用户选择新添加的 holder
  };
  var handleSkip = function handleSkip() {
    setOpen(false);
    // 先调用 resolve，再关闭
    if (resolve) {
      resolve(null);
    }
    // 延迟关闭，确保动画完成
    setTimeout(function () {
      onClose();
    }, 300);
  };
  return /*#__PURE__*/React.createElement(PisellSelectHolder, {
    open: open,
    modalConfig: {
      title: "".concat(locales.getText('pisell-select-holder-please-select'), " ").concat(maxSelectedCount || 1, " ").concat(title),
      confirmText: locales.getText('pisell2.text.confirm')
    },
    dataSource: holderOptions,
    value: selectedValues,
    displayConfig: displayConfig,
    maxSelectedCount: maxSelectedCount,
    allowAdd: true,
    onClose: handleClose,
    onConfirm: handleConfirm,
    onAdd: handleAdd,
    onSkip: handleSkip
  });
};

/**
 * 通过 await 调用的 Holder 选择弹窗
 * @param options 配置选项
 * @returns Promise，resolve 时返回选中的 holder ID 数组，或 null（用户取消时）
 */
export function selectHolderModal(options) {
  var state = options.state,
    dispatch = options.dispatch,
    initialValue = options.initialValue,
    maxSelectedCount = options.maxSelectedCount;
  return new Promise(function (resolve) {
    // 先清理之前的状态，确保没有残留的 resolve
    if (modalState && modalState.resolve) {
      // 如果之前的状态还有未完成的 resolve，先 resolve null
      modalState.resolve(null);
    }

    // 设置全局状态
    var newState = {
      open: true,
      state: state,
      dispatch: dispatch,
      initialValue: initialValue,
      maxSelectedCount: maxSelectedCount,
      resolve: resolve
    };

    // 通知所有实例更新状态
    notifyAllInstances(newState);
  });
}