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 _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 { useEffect, useMemo, useState } from 'react';
import { useMemoizedFn } from 'ahooks';
import { getPetsData } from "../../../components/ticketBooking/serve";
import { getFormDetail } from "../../../components/booking/info/pet/serve";
import { request as bookingRequest } from "../../../components/booking/utils";
import { request as utilsRequest } from "../../../utils";
import { isWalkIn } from "../../../components/booking/utils";
import { buildHolderListRequestKey } from "../utils/enrichCartLineHolderDisplay";
function buildHolderFormDataConfig(holder) {
  var _holder$form, _holder$form2;
  if (!holder) return null;
  return _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: []
  });
}
function getMinorLinkedTableId(formDataConfig) {
  var _formDataConfig$form_, _detail$setting$linke, _detail$setting;
  if ((formDataConfig === null || formDataConfig === void 0 ? void 0 : formDataConfig.form_type) !== 'minors') return null;
  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';
  });
  return (_detail$setting$linke = detail === null || detail === void 0 || (_detail$setting = detail.setting) === null || _detail$setting === void 0 ? void 0 : _detail$setting.linkedTable) !== null && _detail$setting$linke !== void 0 ? _detail$setting$linke : null;
}

/**
 * SalesSdk 编辑抽屉内 Holder / selectHolderModal 所需的 pet 局部状态（替代 miniRedux setPet）。
 */
export function useBookingEditPetState(open, baseBookingState, setRequest, holderSeed, holderSeedRequestKey) {
  var _baseBookingState$boo3, _baseBookingState$boo4, _baseBookingState$cli2;
  var _useState = useState({}),
    _useState2 = _slicedToArray(_useState, 2),
    pet = _useState2[0],
    setPet = _useState2[1];
  var apis = useMemo(function () {
    return {
      getPetsData: getPetsData
    };
  }, []);
  var dispatch = useMemoizedFn(function (cmd) {
    if (cmd.type === 'setPet' && cmd.payload) {
      setPet(function (prev) {
        return _objectSpread(_objectSpread({}, prev), cmd.payload);
      });
    }
  });
  useEffect(function () {
    var _baseBookingState$boo, _baseBookingState$boo2, _baseBookingState$cli, _holder$form3;
    if (!open) {
      setPet({});
      return;
    }
    var holder = (_baseBookingState$boo = baseBookingState.bookingConfig) === null || _baseBookingState$boo === void 0 ? void 0 : _baseBookingState$boo.holder;
    var formDataConfig = buildHolderFormDataConfig(holder);
    if (!formDataConfig) {
      setPet({});
      return;
    }
    setPet({
      formData: [formDataConfig]
    });
    if (setRequest) {
      bookingRequest.setRequest(setRequest);
      utilsRequest.setRequest(setRequest);
    }
    var appointmentSubject = ((_baseBookingState$boo2 = baseBookingState.bookingConfig) === null || _baseBookingState$boo2 === void 0 || (_baseBookingState$boo2 = _baseBookingState$boo2.config) === null || _baseBookingState$boo2 === void 0 || (_baseBookingState$boo2 = _baseBookingState$boo2.basic) === null || _baseBookingState$boo2 === void 0 ? void 0 : _baseBookingState$boo2.appointment_subject) || {};
    var customerId = (_baseBookingState$cli = baseBookingState.client) === null || _baseBookingState$cli === void 0 || (_baseBookingState$cli = _baseBookingState$cli.value) === null || _baseBookingState$cli === void 0 ? void 0 : _baseBookingState$cli.id;
    var isWalkInCustomer = isWalkIn(customerId);
    if ((holder === null || holder === void 0 ? void 0 : holder.data_range) === 'customer' && isWalkInCustomer) {
      return;
    }
    var params = {
      form_id: appointmentSubject.form_id,
      source_shop_customer: holder === null || holder === void 0 || (_holder$form3 = holder.form) === null || _holder$form3 === void 0 ? void 0 : _holder$form3.is_franchisor,
      customer_id: (holder === null || holder === void 0 ? void 0 : holder.data_range) === 'customer' ? customerId : undefined,
      skip: 1,
      num: 100
    };
    var requestKey = buildHolderListRequestKey(params);
    if (holderSeed !== null && holderSeed !== void 0 && holderSeed.length && holderSeedRequestKey === requestKey) {
      // Holder 弹窗可复用 SDK 级 Holder 字典，避免同一客户同一 form 重复请求。
      setPet(function (prev) {
        return _objectSpread(_objectSpread({}, prev), {}, {
          holders: holderSeed
        });
      });
      return;
    }
    getPetsData(params).then(function (data) {
      setPet(function (prev) {
        return _objectSpread(_objectSpread({}, prev), {}, {
          holders: (data === null || data === void 0 ? void 0 : data.list) || []
        });
      });
    }).catch(function (err) {
      console.warn('[SalesSdk] load holders failed', err);
    });
    var linkedTableId = getMinorLinkedTableId(formDataConfig);
    if (linkedTableId) {
      getFormDetail(linkedTableId).then(function (res) {
        setPet(function (prev) {
          return _objectSpread(_objectSpread({}, prev), {}, {
            waiverForm: res
          });
        });
      }).catch(function (err) {
        console.warn('[SalesSdk] load waiver form failed', err);
      });
    }
  }, [open, (_baseBookingState$boo3 = baseBookingState.bookingConfig) === null || _baseBookingState$boo3 === void 0 ? void 0 : _baseBookingState$boo3.holder, (_baseBookingState$boo4 = baseBookingState.bookingConfig) === null || _baseBookingState$boo4 === void 0 || (_baseBookingState$boo4 = _baseBookingState$boo4.config) === null || _baseBookingState$boo4 === void 0 || (_baseBookingState$boo4 = _baseBookingState$boo4.basic) === null || _baseBookingState$boo4 === void 0 ? void 0 : _baseBookingState$boo4.appointment_subject, (_baseBookingState$cli2 = baseBookingState.client) === null || _baseBookingState$cli2 === void 0 || (_baseBookingState$cli2 = _baseBookingState$cli2.value) === null || _baseBookingState$cli2 === void 0 ? void 0 : _baseBookingState$cli2.id, setRequest, holderSeed, holderSeedRequestKey]);
  return {
    pet: pet,
    dispatch: dispatch,
    apis: apis
  };
}