import _slicedToArray from "@babel/runtime-corejs3/helpers/slicedToArray";
import _extends from "@babel/runtime-corejs3/helpers/extends";
import _Set from "@babel/runtime-corejs3/core-js-stable/set";
import _sliceInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/slice";
import React from 'react';
import { internals } from '../../internals';
import { always, arrayUtils } from '../../utils/others';
import { collectNodes, mergeCellProps } from '../../utils';
export function multiSelect() {
  var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  return function multiSelectStep(pipeline) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;

    var stateKey = 'multiSelect';
    var Checkbox = pipeline.ctx.components.Checkbox;

    if (Checkbox == null) {
      throw new Error('使用 multiSelect 之前需要设置 pipeline.ctx.components.Checkbox');
    }

    var primaryKey = pipeline.ensurePrimaryKey('multiSelect');
    var isDisabled = (_a = opts.isDisabled) !== null && _a !== void 0 ? _a : always(false);
    var clickArea = (_b = opts.clickArea) !== null && _b !== void 0 ? _b : 'checkbox';
    var value = (_f = (_e = (_c = opts.value) !== null && _c !== void 0 ? _c : (_d = pipeline.getStateAtKey(stateKey)) === null || _d === void 0 ? void 0 : _d.value) !== null && _e !== void 0 ? _e : opts.defaultValue) !== null && _f !== void 0 ? _f : [];
    var lastKey = (_k = (_j = (_g = opts.lastKey) !== null && _g !== void 0 ? _g : (_h = pipeline.getStateAtKey(stateKey)) === null || _h === void 0 ? void 0 : _h.lastKey) !== null && _j !== void 0 ? _j : opts.defaultLastKey) !== null && _k !== void 0 ? _k : '';

    var _onChange = function onChange(nextValue, key, keys, action) {
      var _a;

      (_a = opts.onChange) === null || _a === void 0 ? void 0 : _a.call(opts, nextValue, key, keys, action);
      pipeline.setStateAtKey(stateKey, {
        value: nextValue,
        lastKey: key
      }, {
        keys: keys,
        action: action
      });
    };

    var dataSource = pipeline.getDataSource();
    /** dataSource 中包含的所有 keys */

    var fullKeySet = new _Set();
    /** 所有有效的 keys（disable 状态为 false） */

    var allKeys = [];
    var flatDataSource = collectNodes(dataSource);
    flatDataSource.forEach(function (row, rowIndex) {
      var rowKey = internals.safeGetRowKey(primaryKey, row, rowIndex);
      fullKeySet.add(rowKey); // 在 allKeys 中排除被禁用的 key

      if (!isDisabled(row, rowIndex)) {
        allKeys.push(rowKey);
      }
    });
    var set = new _Set(value); // todo: 暂使用hidden隐藏选择列 后续增加配置

    var hiddenSelectColumn = opts.checkboxColumn && opts.checkboxColumn.hidden === true;

    if (!hiddenSelectColumn) {
      var _context;

      var isAllChecked = allKeys.length > 0 && allKeys.every(function (key) {
        return set.has(key);
      });
      var isAnyChecked = allKeys.some(function (key) {
        return set.has(key);
      });
      var defaultCheckboxColumnTitle = /*#__PURE__*/React.createElement(Checkbox, {
        checked: isAllChecked,
        indeterminate: !isAllChecked && isAnyChecked,
        onChange: function onChange(_) {
          if (isAllChecked) {
            _onChange(arrayUtils.diff(value, allKeys), '', allKeys, 'uncheck-all');
          } else {
            _onChange(arrayUtils.merge(value, allKeys), '', allKeys, 'check-all');
          }
        }
      });

      var checkboxColumn = _extends(_extends({
        name: '是否选中',
        title: defaultCheckboxColumnTitle,
        width: 50,
        align: 'center'
      }, opts.checkboxColumn), {
        getCellProps: function getCellProps(value, row, rowIndex) {
          var _a, _b;

          var rowKey = internals.safeGetRowKey(primaryKey, row, rowIndex);
          var checkboxCellProps = {};
          var preCellProps = (_b = (_a = opts.checkboxColumn) === null || _a === void 0 ? void 0 : _a.getCellProps) === null || _b === void 0 ? void 0 : _b.call(_a, value, row, rowIndex);

          if (fullKeySet.has(rowKey) && clickArea === 'cell') {
            var prevChecked = set.has(rowKey);
            var disabled = isDisabled(row, rowIndex);
            checkboxCellProps = {
              style: {
                cursor: disabled ? 'not-allowed' : 'pointer'
              },
              onClick: disabled ? undefined : function (e) {
                if (opts.stopClickEventPropagation) {
                  e.stopPropagation();
                }

                onCheckboxChange(prevChecked, rowKey, e.shiftKey);
              }
            };
          }

          return mergeCellProps(preCellProps, checkboxCellProps);
        },
        render: function render(_, row, rowIndex) {
          if (row[pipeline.getFeatureOptions('footerRowMetaKey')]) {
            return null;
          }

          var key = internals.safeGetRowKey(primaryKey, row, rowIndex);
          var checked = set.has(key);
          return /*#__PURE__*/React.createElement(Checkbox, {
            checked: checked,
            disabled: isDisabled(row, rowIndex),
            onChange: clickArea === 'checkbox' ? function (arg1, arg2) {
              var _a; // 这里要同时兼容 antd 和 fusion 的用法
              // fusion: arg2?.nativeEvent
              // antd: arg1.nativeEvent


              var nativeEvent = (_a = arg2 === null || arg2 === void 0 ? void 0 : arg2.nativeEvent) !== null && _a !== void 0 ? _a : arg1.nativeEvent;

              if (nativeEvent) {
                if (opts.stopClickEventPropagation) {
                  nativeEvent.stopPropagation();
                }

                onCheckboxChange(checked, key, nativeEvent.shiftKey);
              }
            } : undefined
          });
        }
      });

      var nextColumns = _sliceInstanceProperty(_context = pipeline.getColumns()).call(_context);

      var checkboxPlacement = (_l = opts.checkboxPlacement) !== null && _l !== void 0 ? _l : 'start';

      if (checkboxPlacement === 'start') {
        nextColumns.unshift(checkboxColumn);
      } else {
        nextColumns.push(checkboxColumn);
      }

      pipeline.columns(nextColumns);
    }

    pipeline.appendRowPropsGetter(function (row, rowIndex) {
      var rowKey = internals.safeGetRowKey(primaryKey, row, rowIndex);

      if (!fullKeySet.has(rowKey)) {
        // rowKey 不在 fullKeySet 中说明这一行是在 multiSelect 之后才生成的，multiSelect 不对之后生成的行进行处理
        return;
      }

      var style = {};
      var className;
      var onClick;
      var checked = set.has(rowKey);

      if (opts.highlightRowWhenSelected && checked) {
        className = 'highlight';
      }

      if (clickArea === 'row') {
        var disabled = isDisabled(row, rowIndex);

        if (!disabled) {
          style.cursor = 'pointer';

          onClick = function onClick(e) {
            if (opts.stopClickEventPropagation) {
              e.stopPropagation();
            }

            onCheckboxChange(checked, rowKey, e.shiftKey);
          };
        }
      }

      return {
        className: className,
        style: style,
        onClick: onClick
      };
    });
    return pipeline;

    function onCheckboxChange(prevChecked, key, batch) {
      var batchKeys = [key];

      if (batch && lastKey) {
        var lastIdx = allKeys.indexOf(lastKey);
        var cntIdx = allKeys.indexOf(key);

        var _ref = lastIdx < cntIdx ? [lastIdx, cntIdx] : [cntIdx, lastIdx],
            _ref2 = _slicedToArray(_ref, 2),
            start = _ref2[0],
            end = _ref2[1];

        batchKeys = _sliceInstanceProperty(allKeys).call(allKeys, start, end + 1);
      }

      if (prevChecked) {
        _onChange(arrayUtils.diff(value, batchKeys), key, batchKeys, 'uncheck');
      } else {
        _onChange(arrayUtils.merge(value, batchKeys), key, batchKeys, 'check');
      }
    }
  };
}