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); }
var _excluded = ["show", "render"],
  _excluded2 = ["disabled", "size", "style"];
function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
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 _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
import React, { useEffect, useImperativeHandle, forwardRef } from 'react';
import { Tag, Select } from 'antd';
import classNames from 'classnames';
import { CheckCircleOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
// @ts-ignore
import { locales } from '@pisell/utils';
import localeTexts from "./locales";
import Indicator from "./components/Indicator";
import LayoutContainer from "./components/LayoutContainer";
import NumericStepper from "../NumericStepper";
import useSelectionController from "./hooks/useSelectionController";
import usePresetProps from "./hooks/usePresetProps";
import useEngineContext from "../../hooks/useEngineContext";
import useThemeTokens from "../../hooks/useThemeTokens";
import Item from "./Item";
import "./selector.less";
var ATag = Tag;
export var SelectorContext = /*#__PURE__*/React.createContext({
  disabled: false,
  mode: 'single',
  itemLayout: 'horizontal',
  valueType: 'primitive',
  variant: 'default',
  itemProps: {},
  preset: {}
});
var Selector = /*#__PURE__*/forwardRef(function (props, ref) {
  var _context$appHelper;
  var disabled = props.disabled,
    fieldNames = props.fieldNames,
    layout = props.layout,
    indicatorProps = props.indicatorProps,
    itemProps = props.itemProps,
    _props$itemLayout = props.itemLayout,
    itemLayout = _props$itemLayout === void 0 ? 'horizontal' : _props$itemLayout,
    _props$mode = props.mode,
    mode = _props$mode === void 0 ? 'single' : _props$mode,
    _props$preset = props.preset,
    preset = _props$preset === void 0 ? {} : _props$preset,
    renderItem = props.renderItem,
    ruleConfig = props.ruleConfig,
    _props$valueType = props.valueType,
    valueType = _props$valueType === void 0 ? 'primitive' : _props$valueType,
    _props$variant = props.variant,
    variant = _props$variant === void 0 ? 'default' : _props$variant;
  var _useThemeTokens = useThemeTokens(props.theme),
    colorPrimary = _useThemeTokens.colorPrimary,
    colorPrimaryBg = _useThemeTokens.colorPrimaryBg;
  var context = useEngineContext();
  locales.init(localeTexts, (context === null || context === void 0 || (_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 || (_context$appHelper = _context$appHelper.utils) === null || _context$appHelper === void 0 || (_context$appHelper = _context$appHelper.storage) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.get('umi_locale')) || 'en');
  var _useSelectionControll = useSelectionController(props),
    state = _useSelectionControll.state,
    actions = _useSelectionControll.actions;
  var options = state.options,
    errors = state.errors,
    validated = state.validated,
    quantityInfo = state.quantityInfo;
  var showQuantity = quantityInfo.showQuantity,
    remainingCount = quantityInfo.remainingCount;
  var headerProps = props.headerProps || props.titleProps || {};

  // 根据预设配置计算 grid 和 indicatorProps
  var presetConfig = usePresetProps({
    mode: mode,
    preset: preset,
    itemLayout: itemLayout,
    variant: variant,
    layout: layout,
    indicatorProps: indicatorProps
  });

  // 使用预设后的配置
  var finalLayout = presetConfig.layout;
  var finalIndicatorProps = presetConfig.indicatorProps;
  useImperativeHandle(ref, function () {
    return {
      validate: actions.validate,
      reset: actions.reset,
      clear: actions.clear,
      getErrors: function getErrors() {
        return errors || [];
      }
    };
  });
  useEffect(function () {
    document.body.id = 'body';
  }, [actions]);

  // 选择指示器
  var renderIndicator = function renderIndicator(option, isDefault) {
    var _ref = finalIndicatorProps || {},
      _ref$show = _ref.show,
      show = _ref$show === void 0 ? true : _ref$show,
      render = _ref.render,
      rest = _objectWithoutProperties(_ref, _excluded);
    if ((finalIndicatorProps === null || finalIndicatorProps === void 0 ? void 0 : finalIndicatorProps.show) === false) return null;
    if ( /*#__PURE__*/React.isValidElement(finalIndicatorProps === null || finalIndicatorProps === void 0 ? void 0 : finalIndicatorProps.render)) {
      return finalIndicatorProps === null || finalIndicatorProps === void 0 ? void 0 : finalIndicatorProps.render;
    }
    if (typeof (finalIndicatorProps === null || finalIndicatorProps === void 0 ? void 0 : finalIndicatorProps.render) === 'function') {
      var _finalIndicatorProps$;
      return finalIndicatorProps === null || finalIndicatorProps === void 0 || (_finalIndicatorProps$ = finalIndicatorProps.render) === null || _finalIndicatorProps$ === void 0 ? void 0 : _finalIndicatorProps$.call(finalIndicatorProps, _objectSpread({
        option: option,
        selected: option.selected,
        disabled: disabled || option.disabled,
        actions: actions
      }, rest));
    }
    return /*#__PURE__*/React.createElement(Indicator, _extends({}, rest, {
      mode: mode,
      checked: option.selected,
      disabled: disabled || option.disabled,
      onChange: function onChange(e) {
        if (e.target.checked) {
          actions.update(option._key, {
            quantity: 1
          });
        } else {
          actions.update(option._key, {
            quantity: 0
          });
        }
      },
      children: isDefault ? option._label : undefined
    }));
  };

  // 数量选择器
  var renderQuantitySelector = function renderQuantitySelector(option) {
    if (valueType === 'primitive') return null;
    if (props.showStepper === false) return null;
    if ((props.showStepper === 'auto' || props.showStepper === undefined) && !showQuantity) return null;
    return /*#__PURE__*/React.createElement(NumericStepper, _extends({}, props.stepperProps || {}, {
      min: option.effectiveMin,
      max: option.effectiveMax,
      value: option.quantity,
      disabled: disabled || option.disabled,
      onChange: function onChange(value) {
        actions.update(option._key, {
          quantity: value
        });
      }
    }));
  };

  // 单个选项
  var renderOption = function renderOption(option) {
    var _option$ruleConfig$mi, _option$ruleConfig, _ruleConfig$min, _option$ruleConfig$ma, _option$ruleConfig2;
    var optionItemValue = Array.isArray(state.values) ? state.values.find(function (item) {
      return (item === null || item === void 0 ? void 0 : item.value) === option._key;
    }) : [state.values].find(function (item) {
      return (item === null || item === void 0 ? void 0 : item.value) === option._key;
    });
    if ( /*#__PURE__*/React.isValidElement(renderItem)) {
      return renderItem;
    }

    // 计算有效最小值
    var configMin = (_option$ruleConfig$mi = option === null || option === void 0 || (_option$ruleConfig = option.ruleConfig) === null || _option$ruleConfig === void 0 ? void 0 : _option$ruleConfig.min) !== null && _option$ruleConfig$mi !== void 0 ? _option$ruleConfig$mi : 0;
    var groupMin = (_ruleConfig$min = ruleConfig === null || ruleConfig === void 0 ? void 0 : ruleConfig.min) !== null && _ruleConfig$min !== void 0 ? _ruleConfig$min : 0;
    // 当options.length < 2 时，如果ruleConfig.min > 0，则有效最小值为ruleConfig.min
    var effectiveMin = options.length < 2 && groupMin > 0 ? groupMin : configMin;

    // 综合判断最大值：取 remainingQuantity 和 ruleConfig.max 中的较小值
    var configMax = (_option$ruleConfig$ma = option === null || option === void 0 || (_option$ruleConfig2 = option.ruleConfig) === null || _option$ruleConfig2 === void 0 ? void 0 : _option$ruleConfig2.max) !== null && _option$ruleConfig$ma !== void 0 ? _option$ruleConfig$ma : Number.MAX_SAFE_INTEGER;
    var effectiveMax = remainingCount !== undefined ? Math.min(remainingCount + (option.quantity || 0), configMax) : configMax;

    // 挂载到option上
    option.effectiveMin = effectiveMin;
    option.effectiveMax = effectiveMax;
    if (typeof renderItem === 'function') {
      return renderItem({
        dataSource: option,
        actions: actions,
        optionItemValue: optionItemValue,
        indicator: renderIndicator(option),
        numberSelector: renderQuantitySelector(option),
        values: state.values,
        quantityInfo: quantityInfo
      });
    }
    var numberSelector = renderQuantitySelector(option);
    var indicator = renderIndicator(option);
    return /*#__PURE__*/React.createElement(Item, {
      key: option._key,
      dataSource: option,
      actions: actions,
      indicator: indicator,
      numberSelector: numberSelector,
      optionItemValue: optionItemValue,
      quantityInfo: quantityInfo,
      values: state.values
    });
  };
  var renderOptions = function renderOptions() {
    // Select 变体单独处理
    if (variant === 'select') {
      var _value = state.values;
      var _maxCount = ruleConfig === null || ruleConfig === void 0 ? void 0 : ruleConfig.max;
      var _ref2 = props.selectProps || {},
        selectDisabled = _ref2.disabled,
        _ref2$size = _ref2.size,
        size = _ref2$size === void 0 ? 'large' : _ref2$size,
        style = _ref2.style,
        rest = _objectWithoutProperties(_ref2, _excluded2);
      return /*#__PURE__*/React.createElement(Select, _extends({}, rest, {
        size: size,
        disabled: selectDisabled || disabled,
        style: style || {
          width: '100%'
        },
        mode: mode === 'multiple' ? 'multiple' : undefined,
        options: options,
        fieldNames: fieldNames,
        value: _value,
        onChange: function onChange(value) {
          return actions.setValue(value);
        },
        maxCount: _maxCount
      }));
    }
    return /*#__PURE__*/React.createElement(LayoutContainer, {
      className: "pisell-pro-selector_options-container",
      config: finalLayout
    }, options.map(renderOption));
  };
  var renderRequiredTag = function renderRequiredTag() {
    var _ref3 = ruleConfig || {},
      _ref3$required = _ref3.required,
      required = _ref3$required === void 0 ? false : _ref3$required;
    if (!required) return null;
    var style = {
      borderRadius: 16
    };
    var requiredError = errors.find(function (item) {
      return item.type === 'required' || item.type === 'min';
    });
    if (requiredError) {
      return /*#__PURE__*/React.createElement(ATag, {
        icon: /*#__PURE__*/React.createElement(ExclamationCircleOutlined, null),
        color: "error",
        style: style
      }, locales.getText('pisell2.pro.selector.required-tag'));
    }
    if (validated) {
      return /*#__PURE__*/React.createElement(ATag, {
        icon: /*#__PURE__*/React.createElement(CheckCircleOutlined, null),
        color: "success",
        style: style
      }, locales.getText('pisell2.pro.selector.required-tag'));
    }
    return /*#__PURE__*/React.createElement(ATag, {
      style: style
    }, locales.getText('pisell2.pro.selector.required-tag'));
  };
  var renderTip = function renderTip() {
    var _headerProps$tip2, _headerProps$tip3, _headerProps$tip4;
    if (Array.isArray(errors) && errors.length) {
      var _headerProps$tip;
      var error = errors[errors.length - 1];
      return /*#__PURE__*/React.createElement("span", {
        className: "pisell-pro-selector_tip",
        style: _objectSpread(_objectSpread({}, (headerProps === null || headerProps === void 0 || (_headerProps$tip = headerProps.tip) === null || _headerProps$tip === void 0 ? void 0 : _headerProps$tip.style) || {}), {}, {
          color: '#D92D20'
        })
      }, error === null || error === void 0 ? void 0 : error.message);
    }
    if ((headerProps === null || headerProps === void 0 || (_headerProps$tip2 = headerProps.tip) === null || _headerProps$tip2 === void 0 ? void 0 : _headerProps$tip2.visible) === false) return null;
    var text = headerProps === null || headerProps === void 0 || (_headerProps$tip3 = headerProps.tip) === null || _headerProps$tip3 === void 0 ? void 0 : _headerProps$tip3.text;
    if (ruleConfig !== null && ruleConfig !== void 0 && ruleConfig.min || ruleConfig !== null && ruleConfig !== void 0 && ruleConfig.max) {
      text = locales.getText('pisell2.pro.selector.tip.min-max-selection')(ruleConfig === null || ruleConfig === void 0 ? void 0 : ruleConfig.min, ruleConfig === null || ruleConfig === void 0 ? void 0 : ruleConfig.max);
    }
    if (!text) {
      if (mode === 'multiple') {
        text = locales.getText('pisell2.pro.selector.mode.multiple');
      } else {
        text = locales.getText('pisell2.pro.selector.tip.require-one-option');
      }
    }
    if (!text) return null;
    return /*#__PURE__*/React.createElement("span", {
      className: "pisell-pro-selector_tip",
      style: _objectSpread({}, (headerProps === null || headerProps === void 0 || (_headerProps$tip4 = headerProps.tip) === null || _headerProps$tip4 === void 0 ? void 0 : _headerProps$tip4.style) || {})
    }, "(", text, ")");
  };
  var renderHeader = function renderHeader() {
    var _headerProps$icon, _headerProps$icon2, _headerProps$icon3, _headerProps$icon4, _headerProps$title, _headerProps$title2, _headerProps$title3, _headerProps$title$te, _headerProps$title4;
    if ((headerProps === null || headerProps === void 0 ? void 0 : headerProps.visible) === false) return null;
    var _extraContent = headerProps !== null && headerProps !== void 0 && headerProps.renderExtra ? headerProps === null || headerProps === void 0 ? void 0 : headerProps.renderExtra({
      dataSource: options,
      values: state.values
    }) : null;
    return /*#__PURE__*/React.createElement("div", {
      className: "pisell-pro-selector_header",
      style: _objectSpread({}, (headerProps === null || headerProps === void 0 ? void 0 : headerProps.style) || {})
    }, /*#__PURE__*/React.createElement("div", {
      className: "pisell-pro-selector_header-content-wrapper"
    }, /*#__PURE__*/React.createElement("div", {
      className: "pisell-pro-selector_header-content",
      style: {
        display: 'flex',
        alignItems: 'center',
        gap: 8,
        flex: 1
      }
    }, (headerProps === null || headerProps === void 0 || (_headerProps$icon = headerProps.icon) === null || _headerProps$icon === void 0 ? void 0 : _headerProps$icon.visible) === false || !(headerProps !== null && headerProps !== void 0 && (_headerProps$icon2 = headerProps.icon) !== null && _headerProps$icon2 !== void 0 && _headerProps$icon2.icon) ? null : /*#__PURE__*/React.createElement("span", {
      style: headerProps === null || headerProps === void 0 || (_headerProps$icon3 = headerProps.icon) === null || _headerProps$icon3 === void 0 ? void 0 : _headerProps$icon3.style
    }, headerProps === null || headerProps === void 0 || (_headerProps$icon4 = headerProps.icon) === null || _headerProps$icon4 === void 0 ? void 0 : _headerProps$icon4.icon), (headerProps === null || headerProps === void 0 || (_headerProps$title = headerProps.title) === null || _headerProps$title === void 0 ? void 0 : _headerProps$title.visible) === false || !(headerProps !== null && headerProps !== void 0 && (_headerProps$title2 = headerProps.title) !== null && _headerProps$title2 !== void 0 && _headerProps$title2.text) && !props.title ? null : /*#__PURE__*/React.createElement("span", {
      className: "pisell-pro-selector_header-content-title",
      style: _objectSpread({}, (headerProps === null || headerProps === void 0 || (_headerProps$title3 = headerProps.title) === null || _headerProps$title3 === void 0 ? void 0 : _headerProps$title3.style) || {})
    }, (_headerProps$title$te = headerProps === null || headerProps === void 0 || (_headerProps$title4 = headerProps.title) === null || _headerProps$title4 === void 0 ? void 0 : _headerProps$title4.text) !== null && _headerProps$title$te !== void 0 ? _headerProps$title$te : props.title), renderRequiredTag()), renderTip()), _extraContent);
  };
  return /*#__PURE__*/React.createElement("div", {
    id: "pisell-pro-selector-".concat(props.id),
    className: classNames('pisell-pro-selector', props.className),
    style: _objectSpread(_objectSpread({}, props.style || {}), {}, _defineProperty(_defineProperty({}, '--color-primary', colorPrimary), '--color-primary-bg', colorPrimaryBg))
  }, renderHeader(), /*#__PURE__*/React.createElement(SelectorContext.Provider, {
    value: {
      mode: mode,
      disabled: disabled,
      valueType: valueType,
      variant: variant,
      itemLayout: itemLayout,
      itemProps: itemProps,
      preset: preset
    }
  }, renderOptions()));
});
export default Selector;