"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _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");

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 _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); if (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 = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { 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 Tooltip = _components.Balloon.Tooltip;

_icon.default.setConfig(_icon.default.HYBRIDCLOUD);

var cls = (0, _utils.baseClass)('teamix-pro-table-toolbar-filter-column');

var processColumns = function processColumns(columns) {
  return columns.map(function (item) {
    if (item.columnFilters === false) {
      return item;
    }

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

var FilterColumnIcon = function FilterColumnIcon(props) {
  var _actionRef$current2, _actionRef$current2$o;

  var _props$columns = props.columns,
      columns = _props$columns === void 0 ? [] : _props$columns,
      actionRef = props.actionRef;

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

  var _useState7 = (0, _react.useState)(false),
      _useState8 = _slicedToArray(_useState7, 2),
      fullscreen = _useState8[0],
      setFullscreen = _useState8[1];

  (0, _react.useEffect)(function () {
    setNewColumns(processColumns(columns));
  }, [columns]); // 销毁监听函数

  (0, _react.useEffect)(function () {
    return function () {
      var _actionRef$current, _actionRef$current$of;

      (_actionRef$current = actionRef.current) === null || _actionRef$current === void 0 ? void 0 : (_actionRef$current$of = _actionRef$current.off) === null || _actionRef$current$of === void 0 ? void 0 : _actionRef$current$of.call(_actionRef$current, 'filterColumnIcon');
    };
  }, []); // 监听全屏变化

  (_actionRef$current2 = actionRef.current) === null || _actionRef$current2 === void 0 ? void 0 : (_actionRef$current2$o = _actionRef$current2.on) === null || _actionRef$current2$o === void 0 ? void 0 : _actionRef$current2$o.call(_actionRef$current2, function (state) {
    setFullscreen(state);
  }, 'fullScreenState', 'filterColumnIcon'); // 全选

  var onChangeAllColumns = function onChangeAllColumns(check) {
    setAllVisible(check);
    var keyNewColumns = (0, _utils2.cloneDeep)(newColumns);
    keyNewColumns.map(function (item) {
      item.columnFilters = 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);
  }; // 向上


  var moveUp = function moveUp(e, dataIndex) {
    e.stopPropagation();
    var keyNewColumns = (0, _utils2.cloneDeep)(newColumns);
    var index = keyNewColumns.findIndex(function (_ref) {
      var index = _ref.dataIndex;
      return index === dataIndex;
    });

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

    notifyTableRender(keyNewColumns);
  }; // 向下


  var moveDown = function moveDown(e, dataIndex) {
    e.stopPropagation();
    var keyNewColumns = (0, _utils2.cloneDeep)(newColumns);
    var index = keyNewColumns.findIndex(function (_ref2) {
      var index = _ref2.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(keyNewColumns);
  }; // 通知表格渲染


  var notifyTableRender = function notifyTableRender(columns) {
    var _actionRef$current3, _actionRef$current3$s;

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


  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"
      })),
      triggerType: ['click'],
      align: "tr br"
    }, /*#__PURE__*/_react.default.createElement("div", {
      className: cls()
    }, /*#__PURE__*/_react.default.createElement(_components.Menu, null, /*#__PURE__*/_react.default.createElement(CheckboxItem, {
      indeterminate: indeterminate,
      checked: allVisible,
      onChange: onChangeAllColumns
    }, (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"
    }), newColumns.map(function (_ref3, index) {
      var _newColumns$find;

      var dataIndex = _ref3.dataIndex,
          title = _ref3.title;
      return /*#__PURE__*/_react.default.createElement(CheckboxItem, {
        key: index,
        checked: (_newColumns$find = newColumns.find(function (_ref4) {
          var key = _ref4.dataIndex;
          return key === dataIndex;
        })) === null || _newColumns$find === void 0 ? void 0 : _newColumns$find.columnFilters,
        onChange: function onChange(check) {
          return onChangeColumns(check, dataIndex);
        }
      }, title, /*#__PURE__*/_react.default.createElement("div", {
        className: cls({
          sort: true
        })
      }, /*#__PURE__*/_react.default.createElement(_icon.default, {
        size: "small",
        type: "swap-down-line",
        onClick: function onClick(e) {
          return moveDown(e, dataIndex);
        }
      }), /*#__PURE__*/_react.default.createElement(_icon.default, {
        size: "small",
        type: "swap-up-line",
        onClick: function onClick(e) {
          return moveUp(e, dataIndex);
        }
      })));
    })))));
  }; // [5, 18]


  return /*#__PURE__*/_react.default.createElement(Tooltip, {
    trigger: renderDropdown(),
    align: fullscreen ? 'b' : 't',
    popupProps: {
      offset: fullscreen ? [5, 20] : [5, -18],
      animation: {
        in: 'fadeIn',
        out: 'fadeOut'
      }
    }
  }, (0, _utils.getMessage)('customColumnSetting'));
};

var _default = FilterColumnIcon;
exports.default = _default;