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 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); }
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, { forwardRef, useContext, useImperativeHandle, useRef, useState } from 'react';
import { useMemoizedFn } from 'ahooks';
import SkuDetailModal from "../../../../../pro/skuDetailModal";
import { Context } from "../../../info/model";
import { setProductPrice } from "../editService/utils";
import { formatDataKey } from "../../../../ticketBooking/components/addServiceVariant/utils";
import { getProductTotalPrice } from "../../../utils";
import { cloneDeep } from 'lodash';
import useCartChangeEffect from "../../../../ticketBooking/hooks/pisellos/useCartChangeEffect";
var EditNormalService = /*#__PURE__*/forwardRef(function (props, ref) {
  var _ref = useContext(Context),
    state = _ref.state,
    dispatch = _ref.dispatch;
  var _useCartChangeEffect = useCartChangeEffect(),
    onCartChange = _useCartChangeEffect.onCartChange;
  var modalRef = useRef(null);
  var createPayloadRef = useRef(null);
  /**
   * @description 记录最后一次打开弹窗时外部传入的 onClose，用于关闭时回调清理外部状态
   */
  var openOnCloseRef = useRef(undefined);
  /**
   * @description 记录 edit 模式下的 callback，用于编辑完成后回调
   */
  var editCallbackRef = useRef(undefined);
  var _useState = useState(null),
    _useState2 = _slicedToArray(_useState, 2),
    skuDetailConfig = _useState2[0],
    setSkuDetailConfig = _useState2[1];
  useImperativeHandle(ref, function () {
    return {
      init: function init(payload) {
        setSkuDetailConfig((payload === null || payload === void 0 ? void 0 : payload.skuDetailConfig) || {});
        openOnCloseRef.current = payload === null || payload === void 0 ? void 0 : payload.onClose;
        // create 模式：用于 ticketBooking addServiceVariant 的新增流程
        if ((payload === null || payload === void 0 ? void 0 : payload.mode) === 'create') {
          createPayloadRef.current = payload;
          editCallbackRef.current = undefined;
          modalRef.current.open({
            id: payload.productId,
            date: payload.date,
            is_eject: payload.isEject,
            productData: payload.productData,
            skuDetailConfig: (payload === null || payload === void 0 ? void 0 : payload.skuDetailConfig) || {}
          });
          return;
        }

        // edit 模式（兼容两种入口：payload 或旧的 cacheItem）
        createPayloadRef.current = null;
        editCallbackRef.current = payload === null || payload === void 0 ? void 0 : payload.callback;
        if ((payload === null || payload === void 0 ? void 0 : payload.mode) === 'edit') {
          // 如果有 skuDetailConfig，将其合并到 cacheItem 中
          var cacheItemWithConfig = _objectSpread(_objectSpread({}, payload.cacheItem), {}, {
            skuDetailConfig: (payload === null || payload === void 0 ? void 0 : payload.skuDetailConfig) || {}
          });
          modalRef.current.open(cacheItemWithConfig);
          return;
        }
        modalRef.current.open(payload);
      }
    };
  });
  var handleRemove = useMemoizedFn(function (productData) {
    var _ref2, _state$service;
    var newProducts = (_ref2 = (state === null || state === void 0 || (_state$service = state.service) === null || _state$service === void 0 ? void 0 : _state$service.value) || []) === null || _ref2 === void 0 ? void 0 : _ref2.filter(function (item) {
      return item._id !== productData._id;
    });
    dispatch({
      type: 'setService',
      payload: {
        editModal: false,
        value: newProducts,
        edit: true,
        cacheItem: null
      }
    });

    // 如果有自定义移除回调，则调用
    if (skuDetailConfig !== null && skuDetailConfig !== void 0 && skuDetailConfig.onRemove) {
      skuDetailConfig === null || skuDetailConfig === void 0 || skuDetailConfig.onRemove(productData);
    }
  });
  var handleConfirm = useMemoizedFn(function (data) {
    var _data8, _ref3, _state$service2;
    // create 模式：将结果回传给 addServiceVariant 的 callback，后续走原有 addService 流程
    if (createPayloadRef.current) {
      var _data, _data2, _data3, _data$_extend$origin_, _data4, _data5, _data6, _data7, _data$_extend;
      var payload = createPayloadRef.current;
      createPayloadRef.current = null;
      var skuValue = ((_data = data) === null || _data === void 0 || (_data = _data._extend) === null || _data === void 0 ? void 0 : _data.skuValue) || {
        product_id: payload.productId,
        product_variant_id: 0,
        bundle: [],
        option: []
      };
      var quantity = Number(((_data2 = data) === null || _data2 === void 0 || (_data2 = _data2._extend) === null || _data2 === void 0 ? void 0 : _data2.quantity) || 1);

      // 这里的 data._extend.total 在 SkuDetailModal 中被定义为“单价覆盖值”
      // const unitPrice = Number(data?._extend?.total ?? data?.price ?? 0);
      var detail = _objectSpread(_objectSpread({}, data || {}), {}, {
        id: payload.productId,
        product_id: payload.productId,
        _extend: _objectSpread(_objectSpread({}, ((_data3 = data) === null || _data3 === void 0 ? void 0 : _data3._extend) || {}), {}, {
          origin_total: (_data$_extend$origin_ = (_data4 = data) === null || _data4 === void 0 || (_data4 = _data4._extend) === null || _data4 === void 0 ? void 0 : _data4.origin_total) !== null && _data$_extend$origin_ !== void 0 ? _data$_extend$origin_ : (_data5 = data) === null || _data5 === void 0 || (_data5 = _data5._extend) === null || _data5 === void 0 ? void 0 : _data5.total,
          quantity: quantity,
          skuValue: cloneDeep(((_data6 = data) === null || _data6 === void 0 || (_data6 = _data6._extend) === null || _data6 === void 0 ? void 0 : _data6.skuValue) || {})
        })
      });
      data._extend.total = getProductTotalPrice(data);
      detail = setProductPrice(detail, {
        newTotal: (_data7 = data) === null || _data7 === void 0 || (_data7 = _data7._extend) === null || _data7 === void 0 ? void 0 : _data7.total,
        origin_total: (_data$_extend = data._extend) === null || _data$_extend === void 0 ? void 0 : _data$_extend.origin_total
      });
      var e = _objectSpread(_objectSpread({
        product_id: payload.productId
      }, detail._extend.other), {}, {
        quantity: quantity
      });
      e = formatDataKey(e);
      payload.callback(e, undefined, detail, false);

      // ✅ create 模式下也需要调用自定义确认回调
      if (skuDetailConfig !== null && skuDetailConfig !== void 0 && skuDetailConfig.onConfirm) {
        skuDetailConfig === null || skuDetailConfig === void 0 || skuDetailConfig.onConfirm(data);
      }
      return;
    }
    console.log('handleConfirm', data, (_data8 = data) === null || _data8 === void 0 || (_data8 = _data8._extend) === null || _data8 === void 0 ? void 0 : _data8.origin_total);
    var newProducts = (_ref3 = (state === null || state === void 0 || (_state$service2 = state.service) === null || _state$service2 === void 0 ? void 0 : _state$service2.value) || []) === null || _ref3 === void 0 ? void 0 : _ref3.map(function (item) {
      if (item._id == data._id) {
        var _data$_extend$origin_2, _data$_extend2, _data9, _data10, _data$_extend3, _data$_extend4;
        var total = getProductTotalPrice(data);
        data._extend.total = total;
        data._extend.origin_total = (_data$_extend$origin_2 = (_data$_extend2 = data._extend) === null || _data$_extend2 === void 0 ? void 0 : _data$_extend2.origin_total) !== null && _data$_extend$origin_2 !== void 0 ? _data$_extend$origin_2 : total;
        if ((_data9 = data) !== null && _data9 !== void 0 && _data9.is_bundle) {
          data._extend.bundle_edit = 1;
        }
        // 用于在购物车里唤醒 sku 弹窗时，复原商品的选择数据
        // 因为下面 setProduct 可能会去修改option 之类的 price 字段，所以这里必须先 cloneDeep 一次，再次打开 SKU 弹窗时，应该使用没有修改的价格才对
        data._extend._skuValue = cloneDeep(((_data10 = data) === null || _data10 === void 0 || (_data10 = _data10._extend) === null || _data10 === void 0 ? void 0 : _data10.skuValue) || {});
        data = setProductPrice(data, {
          newTotal: total,
          origin_total: (_data$_extend3 = data._extend) === null || _data$_extend3 === void 0 ? void 0 : _data$_extend3.origin_total
        });
        data.note = (_data$_extend4 = data._extend) === null || _data$_extend4 === void 0 ? void 0 : _data$_extend4.note;
        return data;
      }
      return item;
    });

    // edit 模式下，如果有 callback，则调用
    if (editCallbackRef.current) {
      editCallbackRef.current(data);
      editCallbackRef.current = undefined;
    }

    // 如果有自定义确认回调，则调用
    if (skuDetailConfig !== null && skuDetailConfig !== void 0 && skuDetailConfig.onConfirm) {
      skuDetailConfig === null || skuDetailConfig === void 0 || skuDetailConfig.onConfirm(data);
      return;
    }
    onCartChange('update', newProducts);
    dispatch({
      type: 'setService',
      payload: {
        editModal: false,
        value: newProducts,
        edit: true,
        cacheItem: null
      }
    });
  });
  var handleClose = useMemoizedFn(function () {
    var _openOnCloseRef$curre;
    dispatch({
      type: 'setService',
      payload: {
        editModal: false,
        cacheItem: null,
        changeService: false
      }
    });
    if (skuDetailConfig !== null && skuDetailConfig !== void 0 && skuDetailConfig.onClose) {
      skuDetailConfig === null || skuDetailConfig === void 0 || skuDetailConfig.onClose();
    }

    // 避免下次打开时拿到旧引用
    createPayloadRef.current = null;
    editCallbackRef.current = undefined;
    (_openOnCloseRef$curre = openOnCloseRef.current) === null || _openOnCloseRef$curre === void 0 || _openOnCloseRef$curre.call(openOnCloseRef);
    openOnCloseRef.current = undefined;
  });
  return /*#__PURE__*/React.createElement(SkuDetailModal, {
    onClose: handleClose,
    onConfirm: handleConfirm,
    onRemove: handleRemove,
    ref: modalRef
  });
});
export default EditNormalService;