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 _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 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 _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 _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; }
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
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, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import Decimal from 'decimal.js';
import classNames from 'classnames';
import { Button } from '@pisell/materials';
import dayjs from 'dayjs';
import { locales } from '@pisell/utils';
import SKUOptionsSelection from "../../plus/skuOptionsSelection";
// import PisellNumberSelector from '../../pro/pisellNumberSelector';
import useEngineContext from "../../hooks/useEngineContext";
import { getProductDetail } from "../booking/info/service/serve";
import localeTexts from "./locales";
import "./index.less";
import { request } from "../booking/utils";

/**
 * @description Kiosk 商品详情（参考 Figma: Kiosk / Launchpad screen）
 * - 默认从 URL query 读取商品 id（productId / product_id / id），内部通过 getProductDetail 拉取详情
 * - 中间区域用 SKUOptionsSelection 做 SKU 选择
 * - 底部用 PisellNumberSelector 做数量编辑
 */
function KioskSkuDetail(props) {
  var _ref, _context$appHelper, _context$engine, _context$appHelper2, _store$getState, _store$getState2, _store$getState3;
  var className = props.className,
    style = props.style,
    onAddToCart = props.onAddToCart;

  /**
   * @description 从 URL 中读取 productId（兼容 search / hash query）
   * - 支持 key: productId / product_id / id
   */
  var productIdFromUrl = useMemo(function () {
    return getQueryFirstMatch({
      keys: ['productId', 'product_id', 'id']
    });
  }, []);
  var initialProductId = (_ref = productIdFromUrl !== null && productIdFromUrl !== void 0 ? productIdFromUrl : props.productId) !== null && _ref !== void 0 ? _ref : null;

  /**
   * @description 目前 scheduleDate 暂时固定成“当天”
   * - 按本地时区格式化为 YYYY-MM-DD
   */
  var scheduleDate = useMemo(function () {
    return dayjs().format('YYYY-MM-DD');
  }, []);
  var stageScale = useDesignStageScale({
    designWidth: 1080,
    designHeight: 1800
  });
  var context = useEngineContext();
  var _ref2 = ((_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils) || {},
    interaction = _ref2.interaction;
  locales.init(localeTexts, (context === null || context === void 0 || (_context$engine = context.engine) === null || _context$engine === void 0 || (_context$engine = _context$engine.props) === null || _context$engine === void 0 ? void 0 : _context$engine.locale) || 'en');
  request.setRequest(context.appHelper.utils.request);
  var _ref3 = ((_context$appHelper2 = context.appHelper) === null || _context$appHelper2 === void 0 ? void 0 : _context$appHelper2.utils) || {},
    store = _ref3.store,
    getData = _ref3.getData,
    Toast = _ref3.Toast;
  var state = store === null || store === void 0 || (_store$getState = store.getState) === null || _store$getState === void 0 ? void 0 : _store$getState.call(store);
  var symbol = (store === null || store === void 0 || (_store$getState2 = store.getState) === null || _store$getState2 === void 0 || (_store$getState2 = _store$getState2.call(store)) === null || _store$getState2 === void 0 || (_store$getState2 = _store$getState2.global) === null || _store$getState2 === void 0 ? void 0 : _store$getState2.symbol) || '$';
  var currency_code = (store === null || store === void 0 || (_store$getState3 = store.getState) === null || _store$getState3 === void 0 || (_store$getState3 = _store$getState3.call(store)) === null || _store$getState3 === void 0 || (_store$getState3 = _store$getState3.global) === null || _store$getState3 === void 0 ? void 0 : _store$getState3.currency_code) || 'AUD';
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    isLoading = _useState2[0],
    setIsLoading = _useState2[1];
  var _useState3 = useState(null),
    _useState4 = _slicedToArray(_useState3, 2),
    errorText = _useState4[0],
    setErrorText = _useState4[1];
  var _useState5 = useState(null),
    _useState6 = _slicedToArray(_useState5, 2),
    productData = _useState6[0],
    setProductData = _useState6[1];
  var _useState7 = useState(1),
    _useState8 = _slicedToArray(_useState7, 2),
    quantity = _useState8[0],
    setQuantity = _useState8[1];
  var _useState9 = useState({
      product_id: 0,
      product_variant_id: 0,
      bundle: [],
      option: []
    }),
    _useState10 = _slicedToArray(_useState9, 2),
    skuValue = _useState10[0],
    setSkuValue = _useState10[1];
  var _useState11 = useState({
      product_id: 0,
      product_variant_id: 0,
      bundle: [],
      option: []
    }),
    _useState12 = _slicedToArray(_useState11, 2),
    skuDefaultValue = _useState12[0],
    setSkuDefaultValue = _useState12[1];
  var _useState13 = useState(false),
    _useState14 = _slicedToArray(_useState13, 2),
    isEdit = _useState14[0],
    setIsEdit = _useState14[1];
  var skuOptionsSelectionRef = useRef(null);
  /**
   * @description 防止“原生多次初始化/快速切换”导致请求乱序覆盖
   */
  var requestSeqRef = useRef(0);
  var resetForInit = useCallback(function () {
    setProductData(null);
    setErrorText(null);
    setQuantity(1);
    setSkuValue({
      product_id: 0,
      product_variant_id: 0,
      bundle: [],
      option: []
    });
    setSkuDefaultValue({
      product_id: 0,
      product_variant_id: 0,
      bundle: [],
      option: []
    });
  }, []);
  var loadByProductId = useCallback( /*#__PURE__*/function () {
    var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(productId) {
      var options,
        reqId,
        _context$engine2,
        open_deposit,
        _params,
        res,
        apiData,
        normalizedProductId,
        minNumUnit,
        defaultVariantId,
        initialSkuValue,
        _args = arguments;
      return _regeneratorRuntime().wrap(function _callee$(_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            options = _args.length > 1 && _args[1] !== undefined ? _args[1] : {};
            console.log('准备 load', productId);
            if (!(productId === null || typeof productId === 'undefined' || productId === '')) {
              _context.next = 4;
              break;
            }
            return _context.abrupt("return");
          case 4:
            reqId = ++requestSeqRef.current;
            setIsLoading(true);
            setErrorText(null);
            _context.prev = 7;
            open_deposit = (getData === null || getData === void 0 ? void 0 : getData('bookingv2_deposit')) || 0;
            _params = {
              open_deposit: open_deposit,
              'translate-locale': (context === null || context === void 0 || (_context$engine2 = context.engine) === null || _context$engine2 === void 0 || (_context$engine2 = _context$engine2.props) === null || _context$engine2 === void 0 ? void 0 : _context$engine2.locale) || 'en'
            };
            _params.schedule_date = scheduleDate;
            _context.next = 13;
            return getProductDetail(String(productId), _params);
          case 13:
            res = _context.sent;
            console.log('详情接口');
            console.log(JSON.stringify(res));
            apiData = (res !== null && res !== void 0 && res.id ? res : res === null || res === void 0 ? void 0 : res.data) || {};
            if (!(reqId !== requestSeqRef.current)) {
              _context.next = 19;
              break;
            }
            return _context.abrupt("return");
          case 19:
            setProductData(apiData);
            console.log('已设置 productData');
            normalizedProductId = Number((apiData === null || apiData === void 0 ? void 0 : apiData.product_id) || (apiData === null || apiData === void 0 ? void 0 : apiData.id) || productId || 0);
            minNumUnit = Number((apiData === null || apiData === void 0 ? void 0 : apiData.min_num_unit) || 1);
            if (options.shouldInitQuantity !== false) {
              setQuantity(minNumUnit > 0 ? minNumUnit : 1);
            }

            /**
             * @description 默认选中第一个 variant（如果接口返回了 variant 且有数据）
             * 注意：本组件内部用 variant 的 `id` 来匹配 `skuValue.product_variant_id`
             */
            defaultVariantId = function (_apiData$variant) {
              var firstVariantId = Array.isArray(apiData === null || apiData === void 0 ? void 0 : apiData.variant) ? Number((apiData === null || apiData === void 0 || (_apiData$variant = apiData.variant) === null || _apiData$variant === void 0 || (_apiData$variant = _apiData$variant[0]) === null || _apiData$variant === void 0 ? void 0 : _apiData$variant.id) || 0) : 0;
              return Number.isFinite(firstVariantId) ? firstVariantId : 0;
            }();
            initialSkuValue = {
              product_id: normalizedProductId,
              product_variant_id: defaultVariantId,
              bundle: [],
              option: []
            };
            if (options.shouldInitSku !== false) {
              setSkuValue(initialSkuValue);
              setSkuDefaultValue(initialSkuValue);
              setTimeout(function () {
                if (initialSkuValue.product_variant_id) {
                  var _skuOptionsSelectionR;
                  (_skuOptionsSelectionR = skuOptionsSelectionRef.current) === null || _skuOptionsSelectionR === void 0 || _skuOptionsSelectionR.validate();
                }
              }, 0);
            }
            _context.next = 33;
            break;
          case 29:
            _context.prev = 29;
            _context.t0 = _context["catch"](7);
            console.error(_context.t0);
            setErrorText('Failed to load product detail');
          case 33:
            _context.prev = 33;
            if (!(reqId !== requestSeqRef.current)) {
              _context.next = 36;
              break;
            }
            return _context.abrupt("return");
          case 36:
            setIsLoading(false);
            return _context.finish(33);
          case 38:
          case "end":
            return _context.stop();
        }
      }, _callee, null, [[7, 29, 33, 38]]);
    }));
    return function (_x) {
      return _ref4.apply(this, arguments);
    };
  }(), [getData, scheduleDate]);

  // 避免 mountFunction 回调捕获旧的 loadByProductId（不用额外 useEffect）
  var loadRef = useRef(loadByProductId);
  loadRef.current = loadByProductId;
  useEffect(function () {
    var _interaction$utils, _interaction$utils$po, _interaction$utils2, _interaction$utils2$m, _interaction$utils3, _interaction$utils3$m;
    // 通知原生初始化
    interaction === null || interaction === void 0 || (_interaction$utils = interaction.utils) === null || _interaction$utils === void 0 || (_interaction$utils$po = _interaction$utils.postMessageToApp) === null || _interaction$utils$po === void 0 || _interaction$utils$po.call(_interaction$utils, {
      module: 'wallet_pass',
      key: 'page_load'
    });
    // 原生初始化调用-新购流程
    interaction === null || interaction === void 0 || (_interaction$utils2 = interaction.utils) === null || _interaction$utils2 === void 0 || (_interaction$utils2$m = _interaction$utils2.mountFunction) === null || _interaction$utils2$m === void 0 || _interaction$utils2$m.call(_interaction$utils2, 'wallet_pass', 'restore_buy_wallet_pass', function (id) {
      console.log('重置状态', id);
      console.log('宽', window.innerWidth);
      console.log('高', window.innerHeight);
      console.log('设备像素比', window.devicePixelRatio);
      // 原生会预渲染页面，真正展示时再调用这里；该方法可能被多次调用
      resetForInit();

      // 原生回调入参就是 productId：直接触发加载（不走“state→effect”链）
      if (id || id === 0) loadRef.current(id);
      setIsEdit(false);
    });
    // 原生初始化调用-购物车编辑
    interaction === null || interaction === void 0 || (_interaction$utils3 = interaction.utils) === null || _interaction$utils3 === void 0 || (_interaction$utils3$m = _interaction$utils3.mountFunction) === null || _interaction$utils3$m === void 0 || _interaction$utils3$m.call(_interaction$utils3, 'wallet_pass', 'edit_buy_wallet_pass', function (data) {
      console.log('编辑状态', data);
      var productData = JSON.parse(data);
      /**
       * @description 编辑态原生只会触发 edit_buy_wallet_pass
       * - 这里需要主动 load 一次拿到最新详情（尤其是 variant 列表/价格）
       * - 但不能覆盖原生传入的 variantId / quantity
       */
      // setProductData(productData.productDetail);
      loadRef.current(productData.productId, {
        shouldInitSku: false,
        shouldInitQuantity: false
      });
      setSkuValue({
        product_id: productData.productId,
        product_variant_id: Number(productData.variantId),
        bundle: [],
        option: []
      });
      setSkuDefaultValue({
        product_id: productData.productId,
        product_variant_id: Number(productData.variantId),
        bundle: [],
        option: []
      });
      setIsEdit(true);
    });

    // URL 有 productId：挂载时只加载一次
    if (initialProductId || initialProductId === 0) loadRef.current(initialProductId);
  }, []);
  var coverUrl = useMemo(function () {
    return (productData === null || productData === void 0 ? void 0 : productData.cover) || (productData === null || productData === void 0 ? void 0 : productData.image) || '';
  }, [productData]);
  var titleText = useMemo(function () {
    var _productData$_extend;
    return (productData === null || productData === void 0 ? void 0 : productData.title) || (productData === null || productData === void 0 || (_productData$_extend = productData._extend) === null || _productData$_extend === void 0 ? void 0 : _productData$_extend.product_name) || (productData === null || productData === void 0 ? void 0 : productData.product_name) || '';
  }, [productData]);
  var descriptionText = useMemo(function () {
    var _productData$_extend2;
    return (productData === null || productData === void 0 ? void 0 : productData.description) || (productData === null || productData === void 0 ? void 0 : productData.sub_title) || (productData === null || productData === void 0 || (_productData$_extend2 = productData._extend) === null || _productData$_extend2 === void 0 ? void 0 : _productData$_extend2.sub_title) || '';
  }, [productData]);
  var unitPrice = useMemo(function () {
    // 优先取已选 variant 的价格
    var selectedVariantId = Number((skuValue === null || skuValue === void 0 ? void 0 : skuValue.product_variant_id) || 0);
    if (selectedVariantId && Array.isArray(productData === null || productData === void 0 ? void 0 : productData.variant)) {
      var matched = productData.variant.find(function (item) {
        return Number(item === null || item === void 0 ? void 0 : item.id) === selectedVariantId;
      });
      var vPrice = Number((matched === null || matched === void 0 ? void 0 : matched.price) || 0);
      if (!Number.isNaN(vPrice) && vPrice !== 0) return vPrice;
    }
    return Number((productData === null || productData === void 0 ? void 0 : productData.price) || 0);
  }, [productData, skuValue === null || skuValue === void 0 ? void 0 : skuValue.product_variant_id]);
  var priceRangeText = useMemo(function () {
    var variantPrices = Array.isArray(productData === null || productData === void 0 ? void 0 : productData.variant) ? productData.variant.map(function (v) {
      return Number((v === null || v === void 0 ? void 0 : v.price) || 0);
    }).filter(function (n) {
      return !Number.isNaN(n) && n > 0;
    }) : [];
    var base = Number((productData === null || productData === void 0 ? void 0 : productData.price) || 0);
    var all = [].concat(_toConsumableArray(variantPrices), _toConsumableArray(base > 0 ? [base] : []));
    if (all.length === 0) return '';
    var min = Math.min.apply(Math, _toConsumableArray(all));
    var max = Math.max.apply(Math, _toConsumableArray(all));
    if (min === max) return "".concat(symbol).concat(min.toFixed(2));
    return "".concat(symbol).concat(min.toFixed(2), "-").concat(symbol).concat(max.toFixed(2));
  }, [productData, symbol]);
  var itemTotal = useMemo(function () {
    var deUnit = new Decimal(unitPrice || 0);
    var deQty = new Decimal(quantity || 0);
    return deUnit.mul(deQty).toNumber();
  }, [quantity, unitPrice]);

  /**
   * @description 用于展示的总价文案（参考 SkuDetailModal 的 totalText 逻辑）
   * - 统一处理负数符号
   * - 统一保留两位小数
   */
  var itemTotalText = useMemo(function () {
    var deTotal = new Decimal(itemTotal || 0);
    var priceSign = deTotal.toNumber() < 0 ? '-' : '';
    return "".concat(priceSign).concat(symbol).concat(deTotal.abs().toNumber().toFixed(2));
  }, [itemTotal, symbol]);
  var handleAddToCart = function handleAddToCart() {
    var _skuOptionsSelectionR2;
    if (!productData) return;
    (_skuOptionsSelectionR2 = skuOptionsSelectionRef.current) === null || _skuOptionsSelectionR2 === void 0 || _skuOptionsSelectionR2.validate();
    if (!skuValue.product_variant_id) {
      Toast.info(locales.getText('pisell2.text.kiosk.sku.detail.toast.select.variant'));
      return;
    }
    ;
    var obj = {
      productDetail: productData,
      quantity: quantity,
      variantId: skuValue.product_variant_id,
      pricePerUnit: unitPrice,
      isWebBuyWalletPass: true
    };
    interaction.utils.postMessageToApp({
      module: 'wallet_pass',
      key: 'buy_wallet_pass',
      data: {
        // 把洗好的数据放这里
        productData: obj,
        isEdit: isEdit
      }
    });
  };
  var onBack = function onBack() {
    interaction.utils.postMessageToApp({
      module: "wallet_pass",
      key: "back"
    });
  };
  var stageStyle = useMemo(function () {
    return _objectSpread(_objectSpread({}, style || {}), {}, {
      width: 1080,
      height: 1800,
      transform: "translateX(-50%) scale(".concat(stageScale, ")"),
      transformOrigin: 'top center'
    });
  }, [stageScale, style]);
  return /*#__PURE__*/React.createElement("div", {
    className: "pisell-kiosk-sku-detail-viewport"
  }, /*#__PURE__*/React.createElement("div", {
    className: classNames('pisell-kiosk-sku-detail', className),
    style: stageStyle
  }, /*#__PURE__*/React.createElement("div", {
    className: "pisell-kiosk-sku-detail__content"
  }, /*#__PURE__*/React.createElement("div", {
    className: "pisell-kiosk-sku-detail__hero"
  }, coverUrl ? /*#__PURE__*/React.createElement("img", {
    className: "pisell-kiosk-sku-detail__hero-img",
    src: coverUrl,
    alt: titleText || 'product'
  }) : /*#__PURE__*/React.createElement("div", {
    className: "pisell-kiosk-sku-detail__hero-placeholder"
  })), /*#__PURE__*/React.createElement("div", {
    className: "pisell-kiosk-sku-detail__header"
  }, /*#__PURE__*/React.createElement("div", {
    className: "pisell-kiosk-sku-detail__title"
  }, titleText || (isLoading ? 'Loading…' : '')), !!descriptionText && /*#__PURE__*/React.createElement("div", {
    className: "pisell-kiosk-sku-detail__desc"
  }, /*#__PURE__*/React.createElement("div", {
    // descriptionText 为 HTML 字符串，需要按 HTML 渲染
    dangerouslySetInnerHTML: {
      __html: descriptionText
    }
  })), !!priceRangeText && /*#__PURE__*/React.createElement("div", {
    className: "pisell-kiosk-sku-detail__price-range"
  }, priceRangeText, " ", currency_code), !!errorText && /*#__PURE__*/React.createElement("div", {
    className: "pisell-kiosk-sku-detail__error"
  }, errorText)), /*#__PURE__*/React.createElement("div", {
    className: "pisell-kiosk-sku-detail__options-card"
  }, productData && Array.isArray(productData === null || productData === void 0 ? void 0 : productData.variant) && productData.variant.length > 0 ? /*#__PURE__*/React.createElement(SKUOptionsSelection, {
    ref: skuOptionsSelectionRef,
    dataSource: productData,
    value: skuDefaultValue,
    skuCardConfig: {
      price: {
        visible: true
      },
      variantPriceVisible: true
    },
    onChange: function onChange(v) {
      setSkuValue(v);
    },
    customScrollParent: ".pisell-kiosk-sku-detail"
  }) : /*#__PURE__*/React.createElement("div", {
    className: "pisell-kiosk-sku-detail__options-loading"
  }, isLoading ? locales.getText('pisell2.text.kiosk.sku.detail.loading.options') : ''))), /*#__PURE__*/React.createElement("div", {
    className: "pisell-kiosk-sku-detail__footer"
  }, /*#__PURE__*/React.createElement(Button, {
    className: "pisell-kiosk-sku-detail__back-btn",
    size: "large",
    onClick: onBack
  }, locales.getText('pisell2.text.kiosk.sku.detail.btn.back')), /*#__PURE__*/React.createElement("div", {
    className: "pisell-kiosk-sku-detail__footer-center"
  }, /*#__PURE__*/React.createElement("div", {
    className: "pisell-kiosk-sku-detail__item-total"
  }, locales.getText('pisell2.text.kiosk.sku.detail.item.total'), ":", ' ', itemTotalText)), /*#__PURE__*/React.createElement(Button, {
    type: "primary",
    className: "pisell-kiosk-sku-detail__add-btn",
    size: "large",
    onClick: handleAddToCart,
    disabled: !productData || isLoading
  }, locales.getText(isEdit ? 'pisell2.text.kiosk.sku.detail.btn.update' : 'pisell2.text.kiosk.sku.detail.btn.add.to.cart')))));
}
export default KioskSkuDetail;

/**
 * @description 从当前页面 URL 中读取 query 参数（兼容 hash router）
 * - search: ?a=b
 * - hash: #/path?a=b
 */
function getQueryFirstMatch(params) {
  var _params$keys;
  if (typeof window === 'undefined') return null;
  if (!(params !== null && params !== void 0 && (_params$keys = params.keys) !== null && _params$keys !== void 0 && _params$keys.length)) return null;
  var keys = params.keys;
  var tryRead = function tryRead(raw) {
    if (!raw) return null;
    var normalized = raw.startsWith('?') ? raw.slice(1) : raw;
    var searchParams = new URLSearchParams(normalized);
    var _iterator = _createForOfIteratorHelper(keys),
      _step;
    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var key = _step.value;
        var value = searchParams.get(key);
        if (value) return value;
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }
    return null;
  };
  var fromSearch = tryRead(window.location.search || '');
  if (fromSearch) return fromSearch;
  var hash = window.location.hash || '';
  var queryIndex = hash.indexOf('?');
  if (queryIndex === -1) return null;
  return tryRead(hash.slice(queryIndex + 1));
}

/**
 * @description 按设计稿基准尺寸（默认 1080x1800）计算页面缩放比例
 * - scale = min(viewportW/designW, viewportH/designH, 1)
 */
function useDesignStageScale(params) {
  var designWidth = params.designWidth;
  var designHeight = params.designHeight;
  var _useState15 = useState(1),
    _useState16 = _slicedToArray(_useState15, 2),
    scale = _useState16[0],
    setScale = _useState16[1];
  useEffect(function () {
    var update = function update() {
      var viewportWidth = window.innerWidth || designWidth;
      var viewportHeight = window.innerHeight || designHeight;
      var nextScale = Math.min(viewportWidth / designWidth, viewportHeight / designHeight, 1);
      setScale(nextScale);
    };
    update();
    window.addEventListener('resize', update);
    return function () {
      return window.removeEventListener('resize', update);
    };
  }, [designHeight, designWidth]);
  return scale;
}

/**
 * @description 从原生回调 payload 中提取 productId
 */