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, { useMemo, useState, useRef } from 'react';
import { locales } from '@pisell/utils';
import { PisellToast } from '@pisell/materials';
import { SKUCard } from "../../../../pro/Cards";
import { useStore } from "../../hooks";
import { calculateOptionItem, transformOptionGroup } from "../../utils";
import OptionsModal from "../OptionsModal";
import OptionItemCard from "./OptionItemCard";
import "./index.less";
var OptionsCard = function OptionsCard(props) {
  var _props$dataSource, _props$parentDataSour2, _props$optionItemValu2, _props$dataSource3, _props$optionItemValu4, _props$dataSource4;
  var _ref = (props === null || props === void 0 ? void 0 : props.dataSource) || {},
    uniqueKey = _ref._key,
    selected = _ref.selected,
    disabled = _ref.disabled;
  var _ref2 = (props === null || props === void 0 || (_props$dataSource = props.dataSource) === null || _props$dataSource === void 0 ? void 0 : _props$dataSource._original) || {},
    cover = _ref2.cover,
    title = _ref2.title,
    name = _ref2.name,
    product_subtitle = _ref2.product_subtitle,
    price = _ref2.price,
    price_type = _ref2.price_type,
    option_group = _ref2.option_group;
  var symbol = useStore(function (s) {
    return s.symbol;
  });
  var skuCardConfig = useStore(function (s) {
    return s.skuCardConfig;
  });
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    isOpen = _useState2[0],
    setIsOpen = _useState2[1];
  var _useState3 = useState([]),
    _useState4 = _slicedToArray(_useState3, 2),
    modalDataSource = _useState4[0],
    setModalDataSource = _useState4[1];
  var _useState5 = useState({}),
    _useState6 = _slicedToArray(_useState5, 2),
    modalValue = _useState6[0],
    setModalValue = _useState6[1];
  // 当前编辑的key
  var currentEditIndexRef = useRef(-1);
  var _useState7 = useState(-1),
    _useState8 = _slicedToArray(_useState7, 2),
    currentEditIndex = _useState8[0],
    setCurrentEditIndex = _useState8[1];
  var _indicator = /*#__PURE__*/React.cloneElement(props === null || props === void 0 ? void 0 : props.indicator);

  // 根据当前Selector已选择了多少选项计算剩余可选数量
  // 全局最大值 - 所有已选项的数量总和
  var selectorRemainingCount = useMemo(function () {
    var _props$parentDataSour;
    var globalMax = (props === null || props === void 0 || (_props$parentDataSour = props.parentDataSource) === null || _props$parentDataSour === void 0 || (_props$parentDataSour = _props$parentDataSour.ruleConfig) === null || _props$parentDataSour === void 0 ? void 0 : _props$parentDataSour.max) || 0;
    if (globalMax <= 0) return Infinity; // 无限制

    var values = Array.isArray(props === null || props === void 0 ? void 0 : props.values) ? props === null || props === void 0 ? void 0 : props.values : [props === null || props === void 0 ? void 0 : props.values];
    var totalSelected = values.reduce(function (sum, i) {
      return sum + ((i === null || i === void 0 ? void 0 : i.quantity) || 0);
    }, 0) || 0;
    return Math.max(0, globalMax - totalSelected);
  }, [props === null || props === void 0 || (_props$parentDataSour2 = props.parentDataSource) === null || _props$parentDataSour2 === void 0 || (_props$parentDataSour2 = _props$parentDataSour2.ruleConfig) === null || _props$parentDataSour2 === void 0 ? void 0 : _props$parentDataSour2.max, props === null || props === void 0 ? void 0 : props.values]);

  // 当前选项剩余可选数量 = min(全局剩余, 选项自己的剩余)
  var optionRemainingCount = useMemo(function () {
    var _props$optionItemValu, _props$dataSource2;
    var currentQuantity = (props === null || props === void 0 || (_props$optionItemValu = props.optionItemValue) === null || _props$optionItemValu === void 0 ? void 0 : _props$optionItemValu.quantity) || 0;
    var optionMax = (props === null || props === void 0 || (_props$dataSource2 = props.dataSource) === null || _props$dataSource2 === void 0 || (_props$dataSource2 = _props$dataSource2.ruleConfig) === null || _props$dataSource2 === void 0 ? void 0 : _props$dataSource2.max) || 0;

    // 选项自己的剩余数量（0表示无限制）
    var optionRemaining = optionMax > 0 ? optionMax - currentQuantity : Infinity;

    // 取Selector剩余和当前选项剩余的最小值
    return Math.max(0, Math.min(selectorRemainingCount, optionRemaining));
  }, [props === null || props === void 0 || (_props$optionItemValu2 = props.optionItemValue) === null || _props$optionItemValu2 === void 0 ? void 0 : _props$optionItemValu2.quantity, selectorRemainingCount, props === null || props === void 0 || (_props$dataSource3 = props.dataSource) === null || _props$dataSource3 === void 0 || (_props$dataSource3 = _props$dataSource3.ruleConfig) === null || _props$dataSource3 === void 0 ? void 0 : _props$dataSource3.max]);

  // 弹窗剩余可选数量：如果是单选场景下，新增数据时，optionRemainingCount在小于等于0时，设置为1，用于单选能能够切换选择
  var modalRemainingCount = useMemo(function () {
    if ((props === null || props === void 0 ? void 0 : props.mode) === 'single' && currentEditIndex === -1) {
      return optionRemainingCount <= 0 ? 1 : optionRemainingCount;
    }
    return optionRemainingCount;
  }, [props === null || props === void 0 ? void 0 : props.mode, optionRemainingCount, currentEditIndex]);

  // 价格文本
  var priceText = useMemo(function () {
    return "".concat(price_type === 'markdown' ? '-' : '').concat(symbol).concat(Math.abs(Number(price || 0)));
  }, [price, price_type, symbol]);

  // 已选择的选项值
  var selectedOptions = useMemo(function () {
    var _props$optionItemValu3;
    return (props === null || props === void 0 || (_props$optionItemValu3 = props.optionItemValue) === null || _props$optionItemValu3 === void 0 || (_props$optionItemValu3 = _props$optionItemValu3.data) === null || _props$optionItemValu3 === void 0 ? void 0 : _props$optionItemValu3._data) || [];
  }, [props === null || props === void 0 || (_props$optionItemValu4 = props.optionItemValue) === null || _props$optionItemValu4 === void 0 || (_props$optionItemValu4 = _props$optionItemValu4.data) === null || _props$optionItemValu4 === void 0 ? void 0 : _props$optionItemValu4._data]);
  var transformDataSource = function transformDataSource() {
    if (!!(option_group !== null && option_group !== void 0 && option_group.length)) {
      var renderOptionGroup = transformOptionGroup(option_group);
      setModalDataSource(renderOptionGroup || []);
    }
  };
  var handleClick = function handleClick() {
    if (disabled) {
      console.log('handleClick_disabled>>>>>', disabled);
      return;
    }
    var needShowToast = false;
    // 如果是单选场景下，如果剩余可选量小于等于0，但是点击的不是已选中选项，则不禁止用户点击，用于单选能能够切换选择
    if (optionRemainingCount <= 0) {
      if ((props === null || props === void 0 ? void 0 : props.mode) === 'single' && !selected) {
        needShowToast = false;
      } else {
        needShowToast = true;
      }
    } else {
      needShowToast = false;
    }
    if (needShowToast) {
      PisellToast({
        content: locales.getText('pisell2.skuOptionsSelection.optionItemCard.overSelected')
      });
      return;
    }
    setModalValue({});
    currentEditIndexRef.current = -1;
    setCurrentEditIndex(-1);
    setIsOpen(true);
    transformDataSource();
  };
  var handleUpdateClick = function handleUpdateClick(index) {
    var _props$optionItemValu5;
    currentEditIndexRef.current = index;
    setCurrentEditIndex(index);
    setIsOpen(true);
    setModalValue((props === null || props === void 0 || (_props$optionItemValu5 = props.optionItemValue) === null || _props$optionItemValu5 === void 0 || (_props$optionItemValu5 = _props$optionItemValu5.data) === null || _props$optionItemValu5 === void 0 || (_props$optionItemValu5 = _props$optionItemValu5._data) === null || _props$optionItemValu5 === void 0 ? void 0 : _props$optionItemValu5[index]) || {});
    transformDataSource();
  };
  var handleConfirm = function handleConfirm(v) {
    var _props$actions;
    console.log('onConfirm_v>>>>>', v, props === null || props === void 0 ? void 0 : props.optionItemValue, props === null || props === void 0 ? void 0 : props.values);
    var _calculateOptionItem = calculateOptionItem({
        editIndex: currentEditIndexRef.current,
        optionItemValue: props === null || props === void 0 ? void 0 : props.optionItemValue,
        optionItemDataSource: props === null || props === void 0 ? void 0 : props.dataSource,
        data: v
      }),
      _calculateOptionItem2 = _slicedToArray(_calculateOptionItem, 3),
      newOriginal = _calculateOptionItem2[0],
      totalPrice = _calculateOptionItem2[1],
      totalQuantity = _calculateOptionItem2[2];
    props === null || props === void 0 || (_props$actions = props.actions) === null || _props$actions === void 0 || _props$actions.update(uniqueKey, {
      quantity: totalQuantity,
      totalPrice: totalPrice,
      data: newOriginal
    });
    setIsOpen(false);
    setModalValue({});
  };
  var handleQuantityChange = function handleQuantityChange(_index, _quantity) {
    var _props$optionItemValu6, _props$actions2;
    var currentData = (props === null || props === void 0 || (_props$optionItemValu6 = props.optionItemValue) === null || _props$optionItemValu6 === void 0 || (_props$optionItemValu6 = _props$optionItemValu6.data) === null || _props$optionItemValu6 === void 0 || (_props$optionItemValu6 = _props$optionItemValu6._data) === null || _props$optionItemValu6 === void 0 ? void 0 : _props$optionItemValu6[_index]) || {};
    var _calculateOptionItem3 = calculateOptionItem({
        editIndex: _index,
        optionItemValue: props === null || props === void 0 ? void 0 : props.optionItemValue,
        optionItemDataSource: props === null || props === void 0 ? void 0 : props.dataSource,
        data: _objectSpread(_objectSpread({}, currentData), {}, {
          quantity: _quantity
        })
      }),
      _calculateOptionItem4 = _slicedToArray(_calculateOptionItem3, 3),
      newOriginal = _calculateOptionItem4[0],
      totalPrice = _calculateOptionItem4[1],
      totalQuantity = _calculateOptionItem4[2];
    props === null || props === void 0 || (_props$actions2 = props.actions) === null || _props$actions2 === void 0 || _props$actions2.update(uniqueKey, {
      quantity: totalQuantity,
      totalPrice: totalPrice,
      data: newOriginal
    });
  };
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
    className: "pisell-plus-sku-options-card",
    onClick: handleClick
  }, /*#__PURE__*/React.createElement("div", {
    onClick: function onClick(e) {
      e.stopPropagation();
      // 如果当前是选中状态，再点击则直接取消选中
      if (selected) {
        var _props$actions3;
        props === null || props === void 0 || (_props$actions3 = props.actions) === null || _props$actions3 === void 0 || _props$actions3.update(uniqueKey, {
          quantity: 0
        });
      } else {
        handleClick();
      }
    },
    className: "pisell-plus-sku-options-card-indicator-wrapper"
  }, _indicator, /*#__PURE__*/React.createElement("div", {
    className: "pisell-plus-sku-options-card-indicator-wrapper-overlay"
  })), /*#__PURE__*/React.createElement(SKUCard, {
    cover: cover,
    title: title || name || '',
    subtitle: product_subtitle,
    price: priceText,
    arrow: true,
    selected: selected,
    disabled: disabled,
    skuCardConfig: skuCardConfig,
    skuDisabled: (props === null || props === void 0 || (_props$dataSource4 = props.dataSource) === null || _props$dataSource4 === void 0 || (_props$dataSource4 = _props$dataSource4._extra) === null || _props$dataSource4 === void 0 ? void 0 : _props$dataSource4.disabled) === true
  })), (selectedOptions === null || selectedOptions === void 0 ? void 0 : selectedOptions.length) > 0 && /*#__PURE__*/React.createElement(OptionItemCard, {
    optionItemValue: props === null || props === void 0 ? void 0 : props.optionItemValue,
    parentDataSource: props === null || props === void 0 ? void 0 : props.parentDataSource,
    dataSource: props === null || props === void 0 ? void 0 : props.dataSource,
    data: selectedOptions,
    remainingCount: optionRemainingCount,
    onEdit: handleUpdateClick,
    onQuantityChange: handleQuantityChange
  }), isOpen && /*#__PURE__*/React.createElement(OptionsModal, {
    parentDataSource: props === null || props === void 0 ? void 0 : props.parentDataSource,
    dataSource: props === null || props === void 0 ? void 0 : props.dataSource,
    modalDataSource: modalDataSource,
    values: props === null || props === void 0 ? void 0 : props.values,
    optionItemValue: props === null || props === void 0 ? void 0 : props.optionItemValue,
    modalValue: modalValue,
    remainingCount: modalRemainingCount,
    open: isOpen,
    title: title || name || '',
    onCancel: function onCancel() {
      return setIsOpen(false);
    },
    onConfirm: handleConfirm
  }));
};
export default OptionsCard;