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

/**
 * 筛选列
 */
import { Button, Dropdown, Menu, Balloon } from '@alicloudfe/components';
import TeamixIcon from '@teamix/icon';
import { baseClass, getMessage } from '@teamix/utils';
import React, { useState, useEffect } from 'react';
import { deepClone } from '../../utils';
import './index.scss';
var CheckboxItem = Menu.CheckboxItem;
var Tooltip = Balloon.Tooltip;
TeamixIcon.setConfig(TeamixIcon.HYBRIDCLOUD);
var cls = 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 _props$columns = props.columns,
      columns = _props$columns === void 0 ? [] : _props$columns,
      actionRef = props.actionRef;

  var _useState = useState(false),
      _useState2 = _slicedToArray(_useState, 2),
      visible = _useState2[0],
      setVisible = _useState2[1];

  var _useState3 = useState(true),
      _useState4 = _slicedToArray(_useState3, 2),
      allVisible = _useState4[0],
      setAllVisible = _useState4[1];

  var _useState5 = useState(false),
      _useState6 = _slicedToArray(_useState5, 2),
      indeterminate = _useState6[0],
      setIndeterminate = _useState6[1];

  var _useState7 = useState(processColumns(columns)),
      _useState8 = _slicedToArray(_useState7, 2),
      newColumns = _useState8[0],
      setNewColumns = _useState8[1];

  var onVisibleChange = function onVisibleChange(state) {
    setVisible(state);
  };

  useEffect(function () {
    setNewColumns(processColumns(columns));
  }, [columns]); // 全选

  var onChangeAllColumns = function onChangeAllColumns(check) {
    setAllVisible(check);
    var keyNewColumns = deepClone(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 = deepClone(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 = deepClone(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 = deepClone(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$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);
  }; // 计算全选状态


  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.createElement("span", null, /*#__PURE__*/React.createElement(Dropdown, {
      onVisibleChange: onVisibleChange,
      trigger: /*#__PURE__*/React.createElement(Button, {
        iconSize: "small",
        className: "teamix-pro-table-toolbar-icon"
      }, /*#__PURE__*/React.createElement(TeamixIcon, {
        size: "small",
        type: "set-line"
      })),
      triggerType: ['click'],
      align: "tr br"
    }, /*#__PURE__*/React.createElement("div", {
      className: cls()
    }, /*#__PURE__*/React.createElement(Menu, null, /*#__PURE__*/React.createElement(CheckboxItem, {
      indeterminate: indeterminate,
      checked: allVisible,
      onChange: onChangeAllColumns
    }, getMessage('selectAll'), /*#__PURE__*/React.createElement(Button, {
      onClick: restColumns,
      className: cls({
        reset: true
      }),
      text: true,
      type: "primary"
    }, getMessage('reset'))), /*#__PURE__*/React.createElement(Menu.Divider, {
      key: "divider"
    }), newColumns.map(function (_ref3, index) {
      var _newColumns$find;

      var dataIndex = _ref3.dataIndex,
          title = _ref3.title;
      return /*#__PURE__*/React.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.createElement("div", {
        className: cls({
          sort: true
        })
      }, /*#__PURE__*/React.createElement(TeamixIcon, {
        size: "small",
        type: "swap-down-line",
        onClick: function onClick(e) {
          return moveDown(e, dataIndex);
        }
      }), /*#__PURE__*/React.createElement(TeamixIcon, {
        size: "small",
        type: "swap-up-line",
        onClick: function onClick(e) {
          return moveUp(e, dataIndex);
        }
      })));
    })))));
  };

  return /*#__PURE__*/React.createElement(Tooltip, {
    trigger: renderDropdown(),
    align: "t",
    popupProps: {
      offset: [5, -18],
      animation: {
        in: 'fadeIn',
        out: 'fadeOut'
      }
    }
  }, getMessage('customColumnSetting'));
};

export default FilterColumnIcon;