"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _react = _interopRequireWildcard(require("react"));
var _icon = _interopRequireDefault(require("@teamix/icon"));
var _components = require("@alicloudfe/components");
var _utils = require("@teamix/utils");
require("./index.scss");
var _hooks = require("@teamix/hooks");
var _field = _interopRequireDefault(require("../../../field"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
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 ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
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(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
var CheckboxItem = _components.Menu.CheckboxItem;
var cls = (0, _utils.usePrefixCls)('teamix-pro-table-toolbar-filter');
var RadioItem = _components.Menu.RadioItem;
var Filter = function Filter(props) {
  var _urlState$split, _urlState, _urlState$split2;
  var column = props.column,
    actionRef = props.actionRef,
    switchCardView = props.switchCardView,
    bindUrlProps = props.bindUrlProps,
    bindUrl = props.bindUrl;
  var _column$filtersWidth = column.filtersWidth,
    filtersWidth = _column$filtersWidth === void 0 ? 130 : _column$filtersWidth;
  var _ref = bindUrl ? (0, _hooks.useUrlState)() : [],
    _ref2 = _slicedToArray(_ref, 2),
    urlState = _ref2[0],
    setUrlState = _ref2[1];
  // 选中过滤项
  var _useState = (0, _react.useState)((_urlState$split = urlState === null || urlState === void 0 ? void 0 : (_urlState = urlState["filter".concat(column === null || column === void 0 ? void 0 : column.dataIndex)]) === null || _urlState === void 0 ? void 0 : (_urlState$split2 = _urlState.split) === null || _urlState$split2 === void 0 ? void 0 : _urlState$split2.call(_urlState, ',')) !== null && _urlState$split !== void 0 ? _urlState$split : []),
    _useState2 = _slicedToArray(_useState, 2),
    selected = _useState2[0],
    setSelected = _useState2[1];
  var _useState3 = (0, _react.useState)(false),
    _useState4 = _slicedToArray(_useState3, 2),
    visible = _useState4[0],
    setVisible = _useState4[1];
  (0, _react.useEffect)(function () {
    var _actionRef$current$ge, _actionRef$current, _actionRef$current$ge2, _actionRef$current$ge3, _actionRef$current$ge4, _actionRef$current$ge5;
    // 从全局状态中读取上次存储的条件
    var rules = (_actionRef$current$ge = (_actionRef$current = actionRef.current) === null || _actionRef$current === void 0 ? void 0 : (_actionRef$current$ge2 = _actionRef$current.getState) === null || _actionRef$current$ge2 === void 0 ? void 0 : (_actionRef$current$ge3 = _actionRef$current$ge2.call(_actionRef$current)) === null || _actionRef$current$ge3 === void 0 ? void 0 : (_actionRef$current$ge4 = _actionRef$current$ge3.filterRules) === null || _actionRef$current$ge4 === void 0 ? void 0 : (_actionRef$current$ge5 = _actionRef$current$ge4[column.dataIndex]) === null || _actionRef$current$ge5 === void 0 ? void 0 : _actionRef$current$ge5.rules) !== null && _actionRef$current$ge !== void 0 ? _actionRef$current$ge : [];
    // 全局状态中需要有值才赋值。优先级：全局状态 > urlState
    if (rules && rules.length > 0) {
      setSelected(rules);
    }
  }, []);
  // 获取过滤项
  var filters = (0, _react.useMemo)(function () {
    if (Array.isArray(column.filters)) {
      return column.filters;
    }
    var filters = column.dataSource;
    // 转换 valueEnum 为 options
    if (!Array.isArray(column.dataSource)) {
      filters = Object.entries(column.dataSource).map(function (_ref3) {
        var _nv$label, _nv$color;
        var _ref4 = _slicedToArray(_ref3, 2),
          k = _ref4[0],
          v = _ref4[1];
        var nv = v;
        return _objectSpread(_objectSpread({
          value: k
        }, nv), {}, {
          label: (_nv$label = nv.label) !== null && _nv$label !== void 0 ? _nv$label : k,
          color: (_nv$color = nv.color) !== null && _nv$color !== void 0 ? _nv$color : k
        });
      });
    }
    // console.log(filters);
    return filters;
  }, [column]);
  // 点击确定回调
  var onFilterOk = function onFilterOk() {
    var _actionRef$current2, _actionRef$current2$f, _actionRef$current$ge6, _actionRef$current3, _actionRef$current3$g, _actionRef$current3$g2, _actionRef$current4, _actionRef$current4$s, _actionRef$current5, _actionRef$current7, _actionRef$current7$r, _actionRef$current8, _actionRef$current8$r, _actionRef$current9, _actionRef$current9$c;
    (_actionRef$current2 = actionRef.current) === null || _actionRef$current2 === void 0 ? void 0 : (_actionRef$current2$f = _actionRef$current2.filterDataSource) === null || _actionRef$current2$f === void 0 ? void 0 : _actionRef$current2$f.call(_actionRef$current2, column.dataIndex);
    // 先获取此列的param
    var param = '';
    if (column.beforeFilter) {
      var _column$beforeFilter;
      param = (_column$beforeFilter = column.beforeFilter) === null || _column$beforeFilter === void 0 ? void 0 : _column$beforeFilter.call(column, selected);
    } else {
      param = selected.join(',');
    }
    // 需要带上其他所有的信息
    var rules = (_actionRef$current$ge6 = (_actionRef$current3 = actionRef.current) === null || _actionRef$current3 === void 0 ? void 0 : (_actionRef$current3$g = _actionRef$current3.getState) === null || _actionRef$current3$g === void 0 ? void 0 : (_actionRef$current3$g2 = _actionRef$current3$g.call(_actionRef$current3)) === null || _actionRef$current3$g2 === void 0 ? void 0 : _actionRef$current3$g2.filterRules) !== null && _actionRef$current$ge6 !== void 0 ? _actionRef$current$ge6 : {};
    // 再设置所有的列筛选状态
    (_actionRef$current4 = actionRef.current) === null || _actionRef$current4 === void 0 ? void 0 : (_actionRef$current4$s = _actionRef$current4.setFilterRules) === null || _actionRef$current4$s === void 0 ? void 0 : _actionRef$current4$s.call(_actionRef$current4, _objectSpread(_objectSpread({}, rules), {}, _defineProperty({}, column.dataIndex, {
      rules: selected,
      params: param
    })));
    var targetPageKey = 'currentPage';
    var pageInfo = (_actionRef$current5 = actionRef.current) === null || _actionRef$current5 === void 0 ? void 0 : _actionRef$current5.pageInfo;
    if (pageInfo && (pageInfo === null || pageInfo === void 0 ? void 0 : pageInfo.targetPageKey)) {
      targetPageKey = pageInfo === null || pageInfo === void 0 ? void 0 : pageInfo.targetPageKey;
    }
    if (switchCardView === 'card') {
      var _actionRef$current6, _actionRef$current6$s;
      (_actionRef$current6 = actionRef.current) === null || _actionRef$current6 === void 0 ? void 0 : (_actionRef$current6$s = _actionRef$current6.setData) === null || _actionRef$current6$s === void 0 ? void 0 : _actionRef$current6$s.call(_actionRef$current6, []);
    }
    // 发送请求
    (_actionRef$current7 = actionRef.current) === null || _actionRef$current7 === void 0 ? void 0 : (_actionRef$current7$r = _actionRef$current7.request) === null || _actionRef$current7$r === void 0 ? void 0 : _actionRef$current7$r.call(_actionRef$current7, _defineProperty({}, targetPageKey, 1));
    (_actionRef$current8 = actionRef.current) === null || _actionRef$current8 === void 0 ? void 0 : (_actionRef$current8$r = _actionRef$current8.resetPage) === null || _actionRef$current8$r === void 0 ? void 0 : _actionRef$current8$r.call(_actionRef$current8);
    // 清空表格选择
    (_actionRef$current9 = actionRef.current) === null || _actionRef$current9 === void 0 ? void 0 : (_actionRef$current9$c = _actionRef$current9.clearRowSelection) === null || _actionRef$current9$c === void 0 ? void 0 : _actionRef$current9$c.call(_actionRef$current9);
    setVisible(false);
    // 设置 url
    if (bindUrl && (bindUrlProps === null || bindUrlProps === void 0 ? void 0 : bindUrlProps.headerFilters) !== false && (urlState === null || urlState === void 0 ? void 0 : urlState["filter".concat(column === null || column === void 0 ? void 0 : column.dataIndex)]) !== selected.join(',')) {
      setUrlState === null || setUrlState === void 0 ? void 0 : setUrlState(_defineProperty({}, "filter".concat(column === null || column === void 0 ? void 0 : column.dataIndex), selected.join(',')));
    }
  };
  // 重置回调
  var onFilterReset = function onFilterReset() {
    var _actionRef$current$ge7, _actionRef$current10, _actionRef$current10$, _actionRef$current10$2, _actionRef$current11, _actionRef$current11$, _actionRef$current12, _actionRef$current12$;
    setSelected([]);
    var rules = (_actionRef$current$ge7 = (_actionRef$current10 = actionRef.current) === null || _actionRef$current10 === void 0 ? void 0 : (_actionRef$current10$ = _actionRef$current10.getState) === null || _actionRef$current10$ === void 0 ? void 0 : (_actionRef$current10$2 = _actionRef$current10$.call(_actionRef$current10)) === null || _actionRef$current10$2 === void 0 ? void 0 : _actionRef$current10$2.filterRules) !== null && _actionRef$current$ge7 !== void 0 ? _actionRef$current$ge7 : {};
    (_actionRef$current11 = actionRef.current) === null || _actionRef$current11 === void 0 ? void 0 : (_actionRef$current11$ = _actionRef$current11.setFilterRules) === null || _actionRef$current11$ === void 0 ? void 0 : _actionRef$current11$.call(_actionRef$current11, _objectSpread(_objectSpread({}, rules), {}, _defineProperty({}, column.dataIndex, {
      rules: [],
      params: ''
    })));
    (_actionRef$current12 = actionRef.current) === null || _actionRef$current12 === void 0 ? void 0 : (_actionRef$current12$ = _actionRef$current12.filterDataSource) === null || _actionRef$current12$ === void 0 ? void 0 : _actionRef$current12$.call(_actionRef$current12, column.dataIndex);
    if (selected.length > 0) {
      var _actionRef$current13, _actionRef$current14, _actionRef$current14$, _actionRef$current15, _actionRef$current15$, _actionRef$current16, _actionRef$current16$;
      var targetPageKey = 'currentPage';
      var pageInfo = (_actionRef$current13 = actionRef.current) === null || _actionRef$current13 === void 0 ? void 0 : _actionRef$current13.pageInfo;
      if (pageInfo && (pageInfo === null || pageInfo === void 0 ? void 0 : pageInfo.targetPageKey)) {
        targetPageKey = pageInfo === null || pageInfo === void 0 ? void 0 : pageInfo.targetPageKey;
      }
      // 发送请求
      (_actionRef$current14 = actionRef.current) === null || _actionRef$current14 === void 0 ? void 0 : (_actionRef$current14$ = _actionRef$current14.request) === null || _actionRef$current14$ === void 0 ? void 0 : _actionRef$current14$.call(_actionRef$current14, _defineProperty({}, targetPageKey, 1));
      (_actionRef$current15 = actionRef.current) === null || _actionRef$current15 === void 0 ? void 0 : (_actionRef$current15$ = _actionRef$current15.resetPage) === null || _actionRef$current15$ === void 0 ? void 0 : _actionRef$current15$.call(_actionRef$current15);
      // 清空表格选择
      (_actionRef$current16 = actionRef.current) === null || _actionRef$current16 === void 0 ? void 0 : (_actionRef$current16$ = _actionRef$current16.clearRowSelection) === null || _actionRef$current16$ === void 0 ? void 0 : _actionRef$current16$.call(_actionRef$current16);
      if (bindUrl && (bindUrlProps === null || bindUrlProps === void 0 ? void 0 : bindUrlProps.headerFilters) !== false) {
        setUrlState === null || setUrlState === void 0 ? void 0 : setUrlState(_defineProperty({}, "filter".concat(column === null || column === void 0 ? void 0 : column.dataIndex), undefined));
      }
    }
  };
  // 渲染单选
  var renderSingle = function renderSingle() {
    return filters === null || filters === void 0 ? void 0 : filters.map(function (_ref5) {
      var _value$toString;
      var label = _ref5.label,
        value = _ref5.value;
      var valueStr = (_value$toString = value === null || value === void 0 ? void 0 : value.toString()) !== null && _value$toString !== void 0 ? _value$toString : '';
      return /*#__PURE__*/_react.default.createElement(RadioItem, {
        id: valueStr,
        checked: selected.includes(valueStr),
        key: valueStr,
        onChange: function onChange(check) {
          setSelected([valueStr]);
        }
      }, /*#__PURE__*/_react.default.createElement(_field.default, {
        type: "text",
        value: label,
        render: {
          ellipsis: true
        }
      }));
    });
  };
  // 渲染多选
  var renderMultiple = function renderMultiple() {
    return filters === null || filters === void 0 ? void 0 : filters.map(function (_ref6) {
      var _value$toString2;
      var label = _ref6.label,
        value = _ref6.value;
      var valueStr = (_value$toString2 = value === null || value === void 0 ? void 0 : value.toString()) !== null && _value$toString2 !== void 0 ? _value$toString2 : '';
      return /*#__PURE__*/_react.default.createElement(CheckboxItem, {
        key: valueStr,
        checked: selected.includes(valueStr),
        onChange: function onChange(check) {
          if (check) {
            setSelected([].concat(_toConsumableArray(selected), [valueStr]));
          } else {
            setSelected(selected.filter(function (item) {
              return item !== valueStr;
            }));
          }
        }
      }, /*#__PURE__*/_react.default.createElement(_field.default, {
        type: "text",
        value: label,
        render: {
          ellipsis: true
        }
      }));
    });
  };
  // 渲染选择区域
  var renderSelect = function renderSelect() {
    if (column.filterMode === 'multiple') {
      return renderMultiple();
    }
    return renderSingle();
  };
  return /*#__PURE__*/_react.default.createElement(_components.Dropdown, {
    trigger: /*#__PURE__*/_react.default.createElement(_icon.default, {
      size: "small",
      type: selected.length > 0 && visible === false ? 'filter-fill' : 'filter-line',
      className: cls({
        icon: true,
        'icon-selected': selected.length > 0
      }),
      onClick: function onClick() {
        setVisible(!visible);
      }
    }),
    triggerType: ['click'],
    align: "tl bl",
    visible: visible,
    onVisibleChange: function onVisibleChange() {
      return setVisible(false);
    }
  }, /*#__PURE__*/_react.default.createElement("div", {
    className: cls(),
    style: {
      width: filtersWidth
    }
  }, /*#__PURE__*/_react.default.createElement(_components.Menu, null, renderSelect(), /*#__PURE__*/_react.default.createElement("div", {
    className: cls({
      'btn-box': true
    })
  }, /*#__PURE__*/_react.default.createElement(_components.Button, {
    type: "primary",
    size: "small",
    className: cls({
      btn: true
    }),
    onClick: onFilterOk
  }, (0, _utils.getMessage)('ok')), /*#__PURE__*/_react.default.createElement(_components.Button, {
    type: "normal",
    size: "small",
    className: cls({
      btn: true
    }),
    onClick: onFilterReset
  }, (0, _utils.getMessage)('reset'))))));
};
var _default = /*#__PURE__*/(0, _react.memo)(Filter);
exports.default = _default;