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 _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, { useCallback, useMemo, useState } from 'react';
import { flushSync } from 'react-dom';
import { Button, Dropdown, Popover } from 'antd';
import classNames from 'classnames';
import { CheckOutlined } from '@ant-design/icons';
import SwitchVertical01 from '@pisell/icon/es/SwitchVertical01';
import { isMobile } from "../../utils/platform";
import { getText } from "../../locales";
import InlineMenu from "./components/InlineMenu";
import "./index.less";
var prefix = 'pisell-lowcode-';

/** 二级项 key 必含 `:asc` / `:desc`；点一级仅展开子菜单时不应触发排序回调，否则会写入半套 sort 并触发重绘，下拉子菜单会闪一下 */
function isSortLeafMenuKey(key) {
  var s = key == null ? '' : String(key);
  return /:(asc|desc)(:|$)/.test(s);
}
var Label = function Label(_ref) {
  var content = _ref.content;
  return /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefix, "sort-menu-item-label")
  }, /*#__PURE__*/React.createElement("span", null, content), /*#__PURE__*/React.createElement(CheckOutlined, null));
};
var sortChildrenMap = {
  date: function date(key, isLocal) {
    return [{
      key: "".concat(key, ":asc").concat(isLocal ? ':date' : ''),
      label: /*#__PURE__*/React.createElement(Label, {
        content: getText('sort-oldest-to-newest')
      })
    }, {
      key: "".concat(key, ":desc").concat(isLocal ? ':date' : ''),
      label: /*#__PURE__*/React.createElement(Label, {
        content: getText('sort-newest-to-oldest')
      })
    }];
  },
  time: function time(key, isLocal) {
    return [{
      key: "".concat(key, ":desc").concat(isLocal ? ':time' : ''),
      label: /*#__PURE__*/React.createElement(Label, {
        content: getText('sort-from-morning-to-night')
      })
    }, {
      key: "".concat(key, ":asc").concat(isLocal ? ':time' : ''),
      label: /*#__PURE__*/React.createElement(Label, {
        content: getText('sort-from-evening-to-morning')
      })
    }];
  },
  string: function string(key, isLocal) {
    return [{
      key: "".concat(key, ":asc").concat(isLocal ? ':string' : ''),
      label: /*#__PURE__*/React.createElement(Label, {
        content: getText('sort-a-z')
      })
    }, {
      key: "".concat(key, ":desc").concat(isLocal ? ':string' : ''),
      label: /*#__PURE__*/React.createElement(Label, {
        content: getText('sort-z-a')
      })
    }];
  },
  number: function number(key, isLocal) {
    return [{
      key: "".concat(key, ":asc").concat(isLocal ? ':number' : ''),
      label: /*#__PURE__*/React.createElement(Label, {
        content: getText('sort-0-9')
      })
    }, {
      key: "".concat(key, ":desc").concat(isLocal ? ':number' : ''),
      label: /*#__PURE__*/React.createElement(Label, {
        content: getText('sort-9-0')
      })
    }];
  },
  option: function option(key, isLocal) {
    return [{
      key: "".concat(key, ":asc").concat(isLocal ? ':option' : ''),
      label: /*#__PURE__*/React.createElement(Label, {
        content: getText('sort-first-last')
      })
    }, {
      key: "".concat(key, ":desc").concat(isLocal ? ':option' : ''),
      label: /*#__PURE__*/React.createElement(Label, {
        content: getText('sort-last-first')
      })
    }];
  }
};
var Sort = function Sort(_ref2) {
  var _ref2$list = _ref2.list,
    list = _ref2$list === void 0 ? [] : _ref2$list,
    onChange = _ref2.onChange,
    button = _ref2.button,
    style = _ref2.style,
    value = _ref2.value,
    placement = _ref2.placement,
    localPagination = _ref2.localPagination;
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    dropdownOpen = _useState2[0],
    setDropdownOpen = _useState2[1];
  var sortItems = useMemo(function () {
    return list.map(function (d) {
      var children = d.getSortItems ? d.getSortItems(d.name).map(function (_ref3) {
        var key = _ref3.key,
          label = _ref3.label;
        return {
          key: key,
          label: /*#__PURE__*/React.createElement(Label, {
            content: label
          })
        };
      }) : sortChildrenMap[d.type](d.name, !!(d !== null && d !== void 0 && d.localFilter));
      return {
        key: d.name,
        label: d.label,
        children: children,
        popupClassName: "".concat(prefix, "sort-sub-menu-popup-wrap ").concat(prefix, "dropdown-css-var"),
        className: "".concat(d.isHidden ? "".concat(prefix, "sort-menu-wrap-hide") : '')
      };
    });
  }, [list, localPagination]);
  var onMenuClick = useCallback(function (detail) {
    var _detail$keyPath;
    var leaf = (_detail$keyPath = detail.keyPath) === null || _detail$keyPath === void 0 ? void 0 : _detail$keyPath[0];
    if (!isSortLeafMenuKey(leaf)) {
      return;
    }
    var leafStr = String(leaf);
    /** 先同步收起浮层再通知上层，避免 sort 更新导致 Menu 重绘与关窗动画叠在一起出现「闪两下」 */
    flushSync(function () {
      setDropdownOpen(false);
    });
    if (leafStr === value) {
      onChange === null || onChange === void 0 || onChange('', detail);
      return;
    }
    onChange === null || onChange === void 0 || onChange(leafStr, detail);
  }, [value, onChange]);
  var dropdownMenu = useMemo(function () {
    return {
      items: sortItems,
      onClick: onMenuClick,
      selectable: true,
      selectedKeys: value != null && value !== '' ? [value] : []
    };
  }, [sortItems, onMenuClick, value]);
  var isMobileBool = isMobile();
  var btnContent = useMemo(function () {
    return button || /*#__PURE__*/React.createElement(Button, {
      icon: /*#__PURE__*/React.createElement(SwitchVertical01, null),
      style: style,
      className: classNames(_defineProperty({}, "".concat(prefix, "sort-button-active"), !!value)),
      size: "large"
    }, isMobileBool ? null : getText('sort-button-text'));
  }, [button, style, value, isMobileBool]);
  var content = useMemo(function () {
    return /*#__PURE__*/React.createElement(InlineMenu, {
      items: sortItems,
      value: value || '',
      onChange: onChange
    });
  }, [value, sortItems, onChange]);
  if (isMobile()) {
    return /*#__PURE__*/React.createElement(Popover, {
      placement: placement,
      content: content,
      arrow: false,
      overlayClassName: "".concat(prefix, "mobile-sort-overlay"),
      trigger: ['click']
    }, btnContent);
  }
  return /*#__PURE__*/React.createElement(Dropdown, {
    trigger: ['click'],
    placement: placement,
    menu: dropdownMenu,
    open: dropdownOpen,
    onOpenChange: setDropdownOpen
  }, btnContent);
};
export default Sort;