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 _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 _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, { useEffect, useState, useMemo, useCallback } from 'react';
import { PisellModal, Button } from '@pisell/materials';
import { isMobile, locales } from '@pisell/utils';
import ErrorTip from "./components/ErrorTip";
import HolderItem from "./components/HolderItem";
import HolderList from "./components/HolderList";
import useEngineContext from "../../hooks/useEngineContext";
import localeTexts from "./locales";
import "./index.less";

// 类名前缀
export var PREFIX = 'pisell-lowcode-select-holder';
var PisellSelectHolder = function PisellSelectHolder(_ref) {
  var _context$engine;
  var dataSource = _ref.dataSource,
    _ref$open = _ref.open,
    open = _ref$open === void 0 ? true : _ref$open,
    onClose = _ref.onClose,
    onConfirm = _ref.onConfirm,
    onSkip = _ref.onSkip,
    onAdd = _ref.onAdd,
    value = _ref.value,
    modalConfig = _ref.modalConfig,
    displayConfig = _ref.displayConfig,
    _ref$allowAdd = _ref.allowAdd,
    allowAdd = _ref$allowAdd === void 0 ? true : _ref$allowAdd,
    _ref$horizontalGap = _ref.horizontalGap,
    horizontalGap = _ref$horizontalGap === void 0 ? 16 : _ref$horizontalGap,
    _ref$verticalGap = _ref.verticalGap,
    verticalGap = _ref$verticalGap === void 0 ? 16 : _ref$verticalGap,
    _ref$maxSelectedCount = _ref.maxSelectedCount,
    maxSelectedCount = _ref$maxSelectedCount === void 0 ? 2 : _ref$maxSelectedCount,
    _ref$isInline = _ref.isInline,
    isInline = _ref$isInline === void 0 ? false : _ref$isInline,
    className = _ref.className,
    style = _ref.style;
  var _useState = useState(''),
    _useState2 = _slicedToArray(_useState, 2),
    errorTip = _useState2[0],
    setErrorTip = _useState2[1];
  var _useState3 = useState([]),
    _useState4 = _slicedToArray(_useState3, 2),
    selectedValues = _useState4[0],
    setSelectedValues = _useState4[1];
  var mobile = useMemo(function () {
    return isMobile();
  }, []);
  var context = useEngineContext();
  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');
  useEffect(function () {
    var _value = [];
    if (Array.isArray(value)) {
      _value = value;
    } else {
      _value = value ? [value] : [];
    }
    setSelectedValues(_value);
  }, [value]);

  /**
   * @title: 单选模式默认选中第一个有效选项
   * @description: 当单选模式且没有选中值时，自动选中第一个带value的选项
   * @Author: Auto
   * @Date: 2025-01-XX
   */
  useEffect(function () {
    // 只在单选模式下生效
    if ((displayConfig === null || displayConfig === void 0 ? void 0 : displayConfig.selectType) !== 'single') {
      return;
    }

    // 如果已经有选中值，不执行默认选中
    if (selectedValues.length > 0) {
      return;
    }

    // 如果 value prop 有值，说明是外部传入的，不执行默认选中
    // 只有当 value 为空（undefined/null）时，才执行默认选中
    if (value !== undefined && value !== null && (value === null || value === void 0 ? void 0 : value.length) > 0) {
      return;
    }

    // 查找第一个有效的选项（value不为null且不为undefined）
    if (Array.isArray(dataSource) && dataSource.length > 0) {
      var firstValidOption = dataSource.find(function (item) {
        return (item === null || item === void 0 ? void 0 : item.value) !== null && (item === null || item === void 0 ? void 0 : item.value) !== undefined;
      });

      // 如果找到有效选项，自动选中
      if (firstValidOption) {
        handleClick(firstValidOption);
      }
    }
  }, [dataSource, displayConfig === null || displayConfig === void 0 ? void 0 : displayConfig.selectType, selectedValues.length, value]);

  /**
   * @title: 处理确认按钮点击
   * @description:
   * @param {*} useCallback
   * @return {*}
   * @Author: WangHan
   * @Date: 2025-10-10 21:32
   */
  var handleOk = useCallback(function () {
    onConfirm === null || onConfirm === void 0 || onConfirm(selectedValues);
  }, [selectedValues]);

  /**
   * @title: 处理选项点击
   * @description:
   * @return {*}
   * @Author: WangHan
   * @Date: 2025-10-10 21:28
   */
  var handleClick = useCallback(function (item) {
    if (!(item !== null && item !== void 0 && item.value)) {
      return onAdd === null || onAdd === void 0 ? void 0 : onAdd();
    }
    var selectType = (displayConfig === null || displayConfig === void 0 ? void 0 : displayConfig.selectType) || 'single';

    // 单选模式：直接设置选中的值
    if (selectType === 'single') {
      setSelectedValues(function (prev) {
        // 如果点击的是已选中的项，则取消选择（可选行为）
        // 如果需要保持选中状态，可以改为：return [item.value];
        return prev.includes(item.value) ? [] : [item.value];
      });
    } else {
      // 多选模式：如果已选中，则移除，否则添加
      setSelectedValues(function (prev) {
        var newValues = prev.includes(item.value) ? prev.filter(function (v) {
          return v !== item.value;
        }) : [].concat(_toConsumableArray(prev), [item.value]);
        return newValues;
      });
    }
  }, [displayConfig === null || displayConfig === void 0 ? void 0 : displayConfig.selectType]);
  var handleSkip = useCallback(function () {
    onSkip === null || onSkip === void 0 || onSkip();
  }, [onSkip]);

  /**
   * @title: 渲染添加项
   * @description:
   * @param {*} useCallback
   * @return {*}
   * @Author: WangHan
   * @Date: 2025-10-11 14:20
   */
  var addHolderLabel = locales.getText('pisell-select-holder-create');
  var renderAddItem = useCallback(function () {
    if (!allowAdd) return undefined;
    return /*#__PURE__*/React.createElement(HolderItem, {
      item: {
        label: addHolderLabel,
        value: null
      },
      isAddItem: true
    });
  }, [allowAdd]);

  /**
   * @title: 模态框样式类名
   * @description:
   * @param {*} useMemo
   * @return {*}
   * @Author: WangHan
   * @Date: 2025-10-11 14:20
   */
  var modalClassName = useMemo(function () {
    var classes = ["".concat(PREFIX, "-modal")];
    if (mobile) {
      classes.push("".concat(PREFIX, "-modal-mobile"));
    }
    return classes.join(' ');
  }, [mobile]);
  var okButtonProps = useMemo(function () {
    // 多选模式，禁用按钮当已选数量大于最大可选数量
    if ((displayConfig === null || displayConfig === void 0 ? void 0 : displayConfig.selectType) === 'multiple') {
      return {
        disabled: (selectedValues === null || selectedValues === void 0 ? void 0 : selectedValues.length) > maxSelectedCount
      };
    }
    return {
      disabled: !(selectedValues !== null && selectedValues !== void 0 && selectedValues.length)
    };
  }, [selectedValues, maxSelectedCount, displayConfig === null || displayConfig === void 0 ? void 0 : displayConfig.selectType]);

  /**
   * @title: 渲染底部按钮
   * @description:
   * @param {*} useMemo
   * @return {*}
   * @Author: WangHan
   * @Date: 2025-10-10 21:51
   */
  var footerCom = useMemo(function () {
    return /*#__PURE__*/React.createElement("div", {
      className: "".concat(PREFIX, "-footer")
    }, displayConfig !== null && displayConfig !== void 0 && displayConfig.isSkipable ? /*#__PURE__*/React.createElement(Button, {
      onClick: handleSkip
    }, locales.getText('pisell-select-holder-skip')) : null, /*#__PURE__*/React.createElement(Button, _extends({
      onClick: handleOk
    }, okButtonProps, {
      type: "primary"
    }), modalConfig === null || modalConfig === void 0 ? void 0 : modalConfig.confirmText));
  }, [displayConfig === null || displayConfig === void 0 ? void 0 : displayConfig.isSkipable, modalConfig === null || modalConfig === void 0 ? void 0 : modalConfig.confirmText, okButtonProps]);

  /**
   * @description: 渲染内容
   * @param {*} useMemo
   * @return {*}
   */
  var renderContent = useMemo(function () {
    return /*#__PURE__*/React.createElement(React.Fragment, null, mobile && modalConfig !== null && modalConfig !== void 0 && modalConfig.title ? /*#__PURE__*/React.createElement("div", {
      className: "".concat(PREFIX, "-modal-title")
    }, modalConfig === null || modalConfig === void 0 ? void 0 : modalConfig.title) : null, errorTip && /*#__PURE__*/React.createElement(ErrorTip, {
      text: errorTip
    }), (displayConfig === null || displayConfig === void 0 ? void 0 : displayConfig.selectType) === 'multiple' && maxSelectedCount ? /*#__PURE__*/React.createElement("div", {
      className: "".concat(PREFIX, "-selected-info ").concat(selectedValues.length === maxSelectedCount ? "".concat(PREFIX, "-selected-info-max") : '')
    }, locales.getText('pisell-select-holder-selected'), selectedValues.length, "/", maxSelectedCount, selectedValues.length > maxSelectedCount ? /*#__PURE__*/React.createElement("span", null, " ", locales.getText('pisell-select-holder-please-remove')(selectedValues.length - maxSelectedCount)) : null) : null, /*#__PURE__*/React.createElement(HolderList, {
      dataSource: dataSource,
      selectedValues: selectedValues,
      displayConfig: displayConfig,
      renderAddItem: renderAddItem,
      columns: mobile ? 2 : 3,
      horizontalGap: horizontalGap,
      verticalGap: verticalGap,
      allowAdd: allowAdd,
      onClick: handleClick
    }));
  }, [isInline, modalConfig, dataSource, errorTip, maxSelectedCount, selectedValues, displayConfig, renderAddItem, mobile, horizontalGap, verticalGap, allowAdd, handleClick]);

  // 直接页面上显示
  if (isInline) {
    return /*#__PURE__*/React.createElement("div", {
      className: "".concat(PREFIX, "-inline-wrap ").concat(className),
      style: style
    }, renderContent);
  }

  // 弹窗打开
  return /*#__PURE__*/React.createElement(PisellModal, {
    open: open,
    title: mobile ? '' : modalConfig === null || modalConfig === void 0 ? void 0 : modalConfig.title,
    platform: mobile ? 'h5' : 'pc',
    closable: modalConfig === null || modalConfig === void 0 ? void 0 : modalConfig.showClose,
    bodyStyle: {
      padding: mobile ? '0 16px 16px' : 20
    },
    mobileModalHeight: "auto",
    destroyOnClose: true,
    className: modalClassName,
    headerDivider: false,
    width: mobile ? '100%' : '640px',
    footer: footerCom,
    onCancel: onClose
  }, renderContent);
};
export default PisellSelectHolder;
// 导出 HolderList 组件供外部使用
export { default as HolderList } from "./components/HolderList";