"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 _components = require("@alicloudfe/components");

var _icon = _interopRequireDefault(require("@teamix/icon"));

var _utils = require("@teamix/utils");

var _react = _interopRequireWildcard(require("react"));

var _utils2 = require("../../utils");

var _field = require("../../../field");

require("./index.scss");

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 _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

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(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; }

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; }

var CheckboxItem = _components.Menu.CheckboxItem;
var Row = _components.Grid.Row,
    Col = _components.Grid.Col;
var cls = (0, _utils.usePrefixCls)('teamix-pro-table-toolbar-filter-column');

var processColumns = function processColumns(columns) {
  var _getGlobalConfig;

  var globalFilterColumns = (_getGlobalConfig = (0, _utils.getGlobalConfig)('ProTable')) === null || _getGlobalConfig === void 0 ? void 0 : _getGlobalConfig.filterColumns; // hidden 为 true 时不展示

  columns = columns.filter(function (item) {
    return (item === null || item === void 0 ? void 0 : item.hidden) !== true && (!globalFilterColumns || globalFilterColumns(item));
  });
  return columns.map(function (item) {
    if (item.columnFilters === false) {
      return item;
    }

    return _objectSpread(_objectSpread({}, item), {}, {
      columnFilters: true
    });
  });
};

var FilterColumnIcon = function FilterColumnIcon(props) {
  var _props$columns = props.columns,
      columns = _props$columns === void 0 ? [] : _props$columns,
      actionRef = props.actionRef,
      filterColumnType = props.filterColumnType;

  var _useState = (0, _react.useState)(true),
      _useState2 = _slicedToArray(_useState, 2),
      allVisible = _useState2[0],
      setAllVisible = _useState2[1];

  var _useState3 = (0, _react.useState)(false),
      _useState4 = _slicedToArray(_useState3, 2),
      indeterminate = _useState4[0],
      setIndeterminate = _useState4[1];

  var _useState5 = (0, _react.useState)(processColumns(columns)),
      _useState6 = _slicedToArray(_useState5, 2),
      newColumns = _useState6[0],
      setNewColumns = _useState6[1]; // const [fullscreen, setFullscreen] = useState<boolean>(false);
  // tooltip 开关


  var _useState7 = (0, _react.useState)(false),
      _useState8 = _slicedToArray(_useState7, 2),
      tooltipVisible = _useState8[0],
      setTooltipVisible = _useState8[1]; // dropdown 开关


  var _useState9 = (0, _react.useState)(false),
      _useState10 = _slicedToArray(_useState9, 2),
      dropdownVisible = _useState10[0],
      setDropdownVisible = _useState10[1]; // 视角


  var _useState11 = (0, _react.useState)('table'),
      _useState12 = _slicedToArray(_useState11, 2),
      cardView = _useState12[0],
      setCardView = _useState12[1];

  (0, _react.useEffect)(function () {
    _utils2.on === null || _utils2.on === void 0 ? void 0 : (0, _utils2.on)(function (stateFilterColumns) {
      if (stateFilterColumns && stateFilterColumns.length > 0) {
        var showDataIndex = stateFilterColumns.map(function (item) {
          return item.dataIndex;
        });
        var stateColumns = (0, _utils2.cloneDeep)(processColumns(columns)).map(function (item) {
          if (!showDataIndex.includes(item.dataIndex)) {
            item.columnFilters = false;
          }

          return item;
        });
        setNewColumns(stateColumns);
      }
    }, 'refreshFilterState');
    _utils2.on === null || _utils2.on === void 0 ? void 0 : (0, _utils2.on)(function (view) {
      setCardView(view);
    }, 'cardSwitchChange');
    return function () {
      (0, _utils2.off)('refreshFilterState');
      (0, _utils2.off)('cardSwitchChange');
    };
  });
  (0, _react.useEffect)(function () {
    setNewColumns(processColumns(columns));
  }, [columns]); // 全选

  var onChangeAllColumns = function onChangeAllColumns(check) {
    setAllVisible(check);
    var keyNewColumns = (0, _utils2.cloneDeep)(newColumns);
    keyNewColumns.map(function (item) {
      var _item$columnFiltersDi;

      item.columnFilters = (_item$columnFiltersDi = item.columnFiltersDisabled) !== null && _item$columnFiltersDi !== void 0 ? _item$columnFiltersDi : check;
      return item;
    });
    notifyTableRender(keyNewColumns);
  }; // 重置


  var restColumns = function restColumns(e) {
    e.stopPropagation();
    var keyNewColumns = processColumns(columns);
    notifyTableRender(keyNewColumns);
  }; // 修改


  var onChangeColumns = function onChangeColumns(check, dataIndex) {
    var keyNewColumns = (0, _utils2.cloneDeep)(newColumns);
    keyNewColumns.map(function (item) {
      if (item.dataIndex === dataIndex) {
        item.columnFilters = check;
      }

      return item;
    });
    notifyTableRender(keyNewColumns);
  }; // 修改：dialog


  var onChangeColumnsForDialog = function onChangeColumnsForDialog() {
    var keyNewColumns = (0, _utils2.cloneDeep)(newColumns);
    notifyTableRender(keyNewColumns);
    setDropdownVisible(false);
  }; // 向上


  var moveUp = function moveUp(e, dataIndex) {
    var _newColumns$filter, _newColumns$filter2;

    e.stopPropagation();
    var keyNewColumns = (0, _utils2.cloneDeep)(newColumns).filter(function (_ref) {
      var lock = _ref.lock;
      return !lock;
    });
    var headLock = (0, _utils2.cloneDeep)((_newColumns$filter = newColumns.filter(function (_ref2) {
      var lock = _ref2.lock;
      return lock === true || lock === 'left';
    })) !== null && _newColumns$filter !== void 0 ? _newColumns$filter : []);
    var tailLock = (0, _utils2.cloneDeep)((_newColumns$filter2 = newColumns.filter(function (_ref3) {
      var lock = _ref3.lock;
      return lock === 'right';
    })) !== null && _newColumns$filter2 !== void 0 ? _newColumns$filter2 : []);
    var index = keyNewColumns.findIndex(function (_ref4) {
      var index = _ref4.dataIndex;
      return index === dataIndex;
    });

    if (index != 0) {
      keyNewColumns[index] = keyNewColumns.splice(index - 1, 1, keyNewColumns[index])[0];
    } else {
      keyNewColumns.push(keyNewColumns.shift());
    }

    notifyTableRender([].concat(_toConsumableArray(headLock), _toConsumableArray(keyNewColumns), _toConsumableArray(tailLock)));
  }; // 向下


  var moveDown = function moveDown(e, dataIndex) {
    var _newColumns$filter3, _newColumns$filter4;

    e.stopPropagation();
    var keyNewColumns = (0, _utils2.cloneDeep)(newColumns).filter(function (_ref5) {
      var lock = _ref5.lock;
      return !lock;
    });
    var headLock = (0, _utils2.cloneDeep)((_newColumns$filter3 = newColumns.filter(function (_ref6) {
      var lock = _ref6.lock;
      return lock === true || lock === 'left';
    })) !== null && _newColumns$filter3 !== void 0 ? _newColumns$filter3 : []);
    var tailLock = (0, _utils2.cloneDeep)((_newColumns$filter4 = newColumns.filter(function (_ref7) {
      var lock = _ref7.lock;
      return lock === 'right';
    })) !== null && _newColumns$filter4 !== void 0 ? _newColumns$filter4 : []);
    var index = keyNewColumns.findIndex(function (_ref8) {
      var index = _ref8.dataIndex;
      return index === dataIndex;
    });

    if (index != keyNewColumns.length - 1) {
      keyNewColumns[index] = keyNewColumns.splice(index + 1, 1, keyNewColumns[index])[0];
    } else {
      keyNewColumns.unshift(keyNewColumns.splice(index, 1)[0]);
    }

    notifyTableRender([].concat(_toConsumableArray(headLock), _toConsumableArray(keyNewColumns), _toConsumableArray(tailLock)));
  }; // 通知表格渲染


  var notifyTableRender = function notifyTableRender(columns) {
    var _actionRef$current, _actionRef$current$se;

    calculateSelectAllState(columns);
    setNewColumns(columns);
    (_actionRef$current = actionRef.current) === null || _actionRef$current === void 0 ? void 0 : (_actionRef$current$se = _actionRef$current.setColumn) === null || _actionRef$current$se === void 0 ? void 0 : _actionRef$current$se.call(_actionRef$current, columns, false);
  }; // 计算全选状态


  var calculateSelectAllState = function calculateSelectAllState(columns) {
    var flag = columns.reduce(function (acc, cur) {
      if (cur.columnFilters === true) {
        acc++;
      }

      return acc;
    }, 0);

    if (flag === columns.length) {
      setAllVisible(true);
      setIndeterminate(false);
      return;
    }

    if (flag === 0) {
      setAllVisible(false);
      setIndeterminate(false);
      return;
    }

    setIndeterminate(true);
  };

  var renderDropdown = function renderDropdown() {
    return /*#__PURE__*/_react.default.createElement("span", null, /*#__PURE__*/_react.default.createElement(_components.Dropdown, {
      trigger: /*#__PURE__*/_react.default.createElement(_components.Button, {
        iconSize: "small",
        className: "teamix-pro-table-toolbar-icon"
      }, /*#__PURE__*/_react.default.createElement(_icon.default, {
        size: "small",
        type: "set-line"
      })),
      visible: dropdownVisible,
      onVisibleChange: function onVisibleChange(state) {
        setTooltipVisible(false);
        setDropdownVisible(state);
      },
      followTrigger: true,
      cache: true,
      triggerType: ['click'],
      align: "tr br"
    }, /*#__PURE__*/_react.default.createElement("div", {
      className: cls()
    }, /*#__PURE__*/_react.default.createElement(_components.Menu, {
      className: cls('all-select')
    }, /*#__PURE__*/_react.default.createElement(CheckboxItem, {
      indeterminate: indeterminate,
      checked: allVisible,
      onChange: onChangeAllColumns,
      disabled: cardView === 'card'
    }, (0, _utils.getMessage)('selectAll'), /*#__PURE__*/_react.default.createElement(_components.Button, {
      onClick: restColumns,
      className: cls({
        reset: true
      }),
      text: true,
      type: "primary"
    }, (0, _utils.getMessage)('reset'))), /*#__PURE__*/_react.default.createElement(_components.Menu.Divider, {
      key: "divider"
    })), /*#__PURE__*/_react.default.createElement(_components.Menu, {
      className: cls('checkbox-group')
    }, newColumns.map(function (_ref9, index) {
      var _newColumns$find;

      var dataIndex = _ref9.dataIndex,
          title = _ref9.title,
          columnFiltersDisabled = _ref9.columnFiltersDisabled,
          lock = _ref9.lock;
      return /*#__PURE__*/_react.default.createElement(CheckboxItem, {
        key: index,
        checked: (_newColumns$find = newColumns.find(function (_ref10) {
          var key = _ref10.dataIndex;
          return key === dataIndex;
        })) === null || _newColumns$find === void 0 ? void 0 : _newColumns$find.columnFilters,
        onChange: function onChange(check) {
          return onChangeColumns(check, dataIndex);
        },
        disabled: columnFiltersDisabled
      }, title, !lock && !columnFiltersDisabled && /*#__PURE__*/_react.default.createElement("div", {
        className: cls({
          sort: true
        })
      }, /*#__PURE__*/_react.default.createElement(_icon.default, {
        size: "small",
        type: "arrow-down-line",
        onClick: function onClick(e) {
          return moveDown(e, dataIndex);
        }
      }), /*#__PURE__*/_react.default.createElement(_icon.default, {
        size: "small",
        type: "arrow-up-line",
        onClick: function onClick(e) {
          return moveUp(e, dataIndex);
        }
      })));
    })))));
  };

  var renderDialog = function renderDialog() {
    // 对话框关闭
    var dialogOnClose = function dialogOnClose() {
      setDropdownVisible(false);
    };

    return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_components.Button, {
      iconSize: "small",
      className: "teamix-pro-table-toolbar-icon",
      onClick: function onClick() {
        setDropdownVisible(!dropdownVisible);
      }
    }, /*#__PURE__*/_react.default.createElement(_icon.default, {
      size: "small",
      type: "set-line"
    })), /*#__PURE__*/_react.default.createElement(_components.Dialog, {
      title: (0, _utils.getMessage)('customColumnSetting'),
      visible: dropdownVisible,
      onOk: onChangeColumnsForDialog,
      onCancel: dialogOnClose,
      onClose: dialogOnClose,
      width: 480,
      className: cls('dialog')
    }, /*#__PURE__*/_react.default.createElement(Row, {
      gutter: 20,
      wrap: true,
      className: cls('row')
    }, newColumns.map(function (item, index) {
      var _newColumns$find2;

      var dataIndex = item.dataIndex,
          title = item.title,
          columnFiltersDisabled = item.columnFiltersDisabled;
      return /*#__PURE__*/_react.default.createElement(Col, {
        span: 8,
        key: index,
        className: cls('col')
      }, /*#__PURE__*/_react.default.createElement(_components.Checkbox, {
        checked: (_newColumns$find2 = newColumns.find(function (_ref11) {
          var key = _ref11.dataIndex;
          return key === dataIndex;
        })) === null || _newColumns$find2 === void 0 ? void 0 : _newColumns$find2.columnFilters,
        onChange: function onChange(check) {
          var columnsList = (0, _utils2.cloneDeep)(newColumns).map(function (item) {
            if (item.dataIndex === dataIndex) {
              item.columnFilters = check;
            }

            return item;
          });
          setNewColumns(columnsList);
        },
        disabled: columnFiltersDisabled
      }, /*#__PURE__*/_react.default.createElement(_field.Ellipsis, {
        tooltip: title
      }, title)));
    }))));
  };

  if (filterColumnType === 'dialog') {
    return renderDialog();
  }

  if (filterColumnType === 'dropdown') {
    return renderDropdown();
  }

  if (newColumns.length >= 20) {
    return renderDialog();
  }

  return renderDropdown();
};

var _default = FilterColumnIcon;
exports.default = _default;