/**
 * ldesign v0.3.13
 * (c) 2023 ldesign
 * @license MIT
 */

'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var _toConsumableArray = require('@babel/runtime/helpers/toConsumableArray');
var _typeof = require('@babel/runtime/helpers/typeof');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var vue = require('vue');
var intersection = require('lodash/intersection');
var get = require('lodash/get');
var isFunction = require('lodash/isFunction');
var hooks_useDefaultValue = require('../../hooks/useDefaultValue.js');
var _common_js_table_utils = require('../../_common/js/table/utils.js');
var checkbox_index = require('../../checkbox/index.js');
var radio_index = require('../../radio/index.js');
var _common_js_log_log = require('../../_common/js/log/log.js');
require('lodash/kebabCase');
require('lodash/isNumber');
require('../../utils/withInstall.js');
require('../../checkbox/checkbox.js');
require('../../hooks/useVModel.js');
require('../../form/hooks.js');
require('../../hooks/useRipple.js');
require('../../utils/set-style.js');
require('../../hooks/useKeepAnimation.js');
require('../../config-provider/context.js');
require('lodash/mergeWith');
require('lodash/merge');
require('lodash/isArray');
require('../../_common/js/global-config/default-config.js');
require('../../_common/js/global-config/locale/zh_CN.js');
require('../../_chunks/dep-f4db2590.js');
require('dayjs');
require('../../config-provider/useConfig.js');
require('lodash/cloneDeep');
require('lodash/isString');
require('../../hooks/useConfig.js');
require('../../hooks/tnode.js');
require('lodash/camelCase');
require('../../utils/render-tnode.js');
require('lodash/isEmpty');
require('lodash/isObject');
require('../../checkbox/props.js');
require('../../checkbox/constants.js');
require('../../checkbox/group.js');
require('lodash/isUndefined');
require('../../hooks/slot.js');
require('../../checkbox/checkbox-group-props.js');
require('../../radio/radio.js');
require('../../utils/helper.js');
require('@babel/runtime/helpers/objectWithoutProperties');
require('lodash/isNull');
require('../../radio/constants.js');
require('../../radio/props.js');
require('../../radio/group.js');
require('@babel/runtime/helpers/asyncToGenerator');
require('@babel/runtime/regenerator');
require('lodash/isNil');
require('../../radio/radio-group-props.js');
require('../../radio/useKeyboard.js');
require('../../utils/dom.js');
require('../../utils/easing.js');
require('../../radio/radio-button.js');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var _toConsumableArray__default = /*#__PURE__*/_interopDefaultLegacy(_toConsumableArray);
var _typeof__default = /*#__PURE__*/_interopDefaultLegacy(_typeof);
var _defineProperty__default = /*#__PURE__*/_interopDefaultLegacy(_defineProperty);
var _slicedToArray__default = /*#__PURE__*/_interopDefaultLegacy(_slicedToArray);
var intersection__default = /*#__PURE__*/_interopDefaultLegacy(intersection);
var get__default = /*#__PURE__*/_interopDefaultLegacy(get);
var isFunction__default = /*#__PURE__*/_interopDefaultLegacy(isFunction);

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__default["default"](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 useRowSelect(props, tableSelectedClasses) {
  var _toRefs = vue.toRefs(props),
    selectedRowKeys = _toRefs.selectedRowKeys,
    columns = _toRefs.columns,
    rowKey = _toRefs.rowKey,
    data = _toRefs.data,
    pagination = _toRefs.pagination,
    reserveSelectedRowOnPaginate = _toRefs.reserveSelectedRowOnPaginate;
  var currentPaginateData = vue.ref(data.value);
  var selectedRowClassNames = vue.ref();
  var _useDefaultValue = hooks_useDefaultValue["default"](selectedRowKeys, props.defaultSelectedRowKeys || [], props.onSelectChange, "selectedRowKeys"),
    _useDefaultValue2 = _slicedToArray__default["default"](_useDefaultValue, 2),
    tSelectedRowKeys = _useDefaultValue2[0],
    setTSelectedRowKeys = _useDefaultValue2[1];
  var selectedRowDataMap = vue.ref( /* @__PURE__ */new Map());
  var selectColumn = vue.computed(function () {
    return props.columns.find(function (_ref) {
      var type = _ref.type;
      return ["multiple", "single"].includes(type);
    });
  });
  var canSelectedRows = vue.computed(function () {
    var currentData = reserveSelectedRowOnPaginate.value ? data.value : currentPaginateData.value;
    return currentData.filter(function (row, rowIndex) {
      return !isDisabled(row, rowIndex);
    });
  });
  var intersectionKeys = vue.computed(function () {
    return intersection__default["default"](tSelectedRowKeys.value, canSelectedRows.value.map(function (t) {
      return get__default["default"](t, props.rowKey || "id");
    }));
  });
  vue.watch([data, pagination, reserveSelectedRowOnPaginate], function () {
    if (reserveSelectedRowOnPaginate.value) return;
    var _pagination$value = pagination.value,
      pageSize = _pagination$value.pageSize,
      current = _pagination$value.current,
      defaultPageSize = _pagination$value.defaultPageSize,
      defaultCurrent = _pagination$value.defaultCurrent;
    var tPageSize = pageSize || defaultPageSize;
    var tCurrent = current || defaultCurrent;
    currentPaginateData.value = data.value.slice(tPageSize * (tCurrent - 1), tPageSize * tCurrent);
  }, {
    immediate: true
  });
  vue.watch([data, columns, tSelectedRowKeys, selectColumn, rowKey], function () {
    var _selectColumn$value;
    var disabledRowFunc = function disabledRowFunc(p) {
      return selectColumn.value.disabled(p) ? tableSelectedClasses.disabled : "";
    };
    var disabledRowClass = (_selectColumn$value = selectColumn.value) !== null && _selectColumn$value !== void 0 && _selectColumn$value.disabled ? disabledRowFunc : void 0;
    var selected = new Set(tSelectedRowKeys.value);
    var selectedRowClassFunc = function selectedRowClassFunc(_ref2) {
      var row = _ref2.row;
      var rowId = get__default["default"](row, props.rowKey || "id");
      return selected.has(rowId) ? tableSelectedClasses.selected : "";
    };
    var selectedRowClass = selected.size ? selectedRowClassFunc : void 0;
    selectedRowClassNames.value = [disabledRowClass, selectedRowClass];
  }, {
    immediate: true
  });
  function isDisabled(row, rowIndex) {
    return _common_js_table_utils.isRowSelectedDisabled(selectColumn.value, row, rowIndex);
  }
  function getSelectedHeader() {
    return function () {
      var isIndeterminate = intersectionKeys.value.length > 0 && intersectionKeys.value.length < canSelectedRows.value.length;
      var isChecked = intersectionKeys.value.length !== 0 && canSelectedRows.value.length !== 0 && intersectionKeys.value.length === canSelectedRows.value.length;
      return vue.createVNode(checkbox_index.Checkbox, {
        "checked": isChecked,
        "indeterminate": isIndeterminate,
        "disabled": !canSelectedRows.value.length,
        "onChange": handleSelectAll
      }, null);
    };
  }
  function getRowSelectDisabledData(p) {
    var col = p.col,
      row = p.row,
      rowIndex = p.rowIndex;
    var disabled = typeof col.disabled === "function" ? col.disabled({
      row: row,
      rowIndex: rowIndex
    }) : col.disabled;
    var checkProps = isFunction__default["default"](col.checkProps) ? col.checkProps({
      row: row,
      rowIndex: rowIndex
    }) : col.checkProps;
    return {
      disabled: disabled || (checkProps === null || checkProps === void 0 ? void 0 : checkProps.disabled),
      checkProps: checkProps
    };
  }
  function renderSelectCell(p) {
    var column = p.col,
      _p$row = p.row,
      row = _p$row === void 0 ? {} : _p$row;
    var checked = tSelectedRowKeys.value.includes(get__default["default"](row, props.rowKey || "id"));
    var _getRowSelectDisabled = getRowSelectDisabledData(p),
      disabled = _getRowSelectDisabled.disabled,
      checkProps = _getRowSelectDisabled.checkProps;
    var selectBoxProps = _objectSpread(_objectSpread({
      checked: checked,
      disabled: disabled
    }, checkProps), {}, {
      onClick: function onClick(e) {
        var _e$e;
        if (_typeof__default["default"](e) === "object" && "e" in e) (_e$e = e.e) === null || _e$e === void 0 ? void 0 : _e$e.stopPropagation();else e === null || e === void 0 ? void 0 : e.stopPropagation();
      },
      onChange: function onChange() {
        return handleSelectChange(row);
      }
    });
    if (column.type === "single") return vue.createVNode(radio_index.Radio, selectBoxProps, null);
    if (column.type === "multiple") {
      var _props$indeterminateS;
      var isIndeterminate = (_props$indeterminateS = props.indeterminateSelectedRowKeys) !== null && _props$indeterminateS !== void 0 && _props$indeterminateS.length ? props.indeterminateSelectedRowKeys.includes(get__default["default"](row, props.rowKey)) : false;
      return vue.createVNode(checkbox_index.Checkbox, vue.mergeProps({
        "indeterminate": isIndeterminate
      }, selectBoxProps), null);
    }
    return null;
  }
  function handleSelectChange() {
    var row = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    var selectedRowKeys2 = _toConsumableArray__default["default"](tSelectedRowKeys.value);
    var reRowKey = props.rowKey || "id";
    var id = get__default["default"](row, reRowKey);
    var selectedRowIndex = selectedRowKeys2.indexOf(id);
    var isExisted = selectedRowIndex !== -1;
    if (selectColumn.value.type === "multiple") {
      isExisted ? selectedRowKeys2.splice(selectedRowIndex, 1) : selectedRowKeys2.push(id);
    } else if (selectColumn.value.type === "single") {
      selectedRowKeys2 = !isExisted ? [id] : [];
    } else {
      _common_js_log_log["default"].warn("Table", "`column.type` must be one of `multiple` and `single`");
      return;
    }
    setTSelectedRowKeys(selectedRowKeys2, {
      selectedRowData: selectedRowKeys2.map(function (t) {
        return selectedRowDataMap.value.get(t);
      }),
      currentRowKey: id,
      currentRowData: row,
      type: isExisted ? "uncheck" : "check"
    });
  }
  function handleSelectAll(checked) {
    var _selectedRowKeys$valu;
    var reRowKey = props.rowKey || "id";
    var canSelectedRowKeys = canSelectedRows.value.map(function (record) {
      return get__default["default"](record, reRowKey);
    });
    var disabledSelectedRowKeys = ((_selectedRowKeys$valu = selectedRowKeys.value) === null || _selectedRowKeys$valu === void 0 ? void 0 : _selectedRowKeys$valu.filter(function (id) {
      return !canSelectedRowKeys.includes(id);
    })) || [];
    var allIds = checked ? [].concat(_toConsumableArray__default["default"](disabledSelectedRowKeys), _toConsumableArray__default["default"](canSelectedRowKeys)) : _toConsumableArray__default["default"](disabledSelectedRowKeys);
    setTSelectedRowKeys(allIds, {
      selectedRowData: checked ? allIds.map(function (t) {
        return selectedRowDataMap.value.get(t);
      }) : [],
      type: checked ? "check" : "uncheck",
      currentRowKey: "CHECK_ALL_BOX"
    });
  }
  function formatToRowSelectColumn(col) {
    var isSelection = ["multiple", "single"].includes(col.type);
    if (!isSelection) return col;
    return _objectSpread(_objectSpread({}, col), {}, {
      width: col.width || 64,
      className: [tableSelectedClasses.checkCell, col.className],
      cell: function cell(_, p) {
        return renderSelectCell(p);
      },
      title: col.type === "multiple" ? getSelectedHeader() : col.title
    });
  }
  var onInnerSelectRowClick = function onInnerSelectRowClick(_ref3) {
    var row = _ref3.row,
      index = _ref3.index;
    var selectedColIndex = props.columns.findIndex(function (item) {
      return item.colKey === "row-select";
    });
    if (selectedColIndex === -1) return;
    var _getRowSelectDisabled2 = getRowSelectDisabledData({
        row: row,
        rowIndex: index,
        col: props.columns[selectedColIndex],
        colIndex: selectedColIndex
      }),
      disabled = _getRowSelectDisabled2.disabled;
    if (disabled) return;
    handleSelectChange(row);
  };
  vue.watch(function () {
    return [_toConsumableArray__default["default"](data.value), rowKey];
  }, function () {
    for (var i = 0, len = data.value.length; i < len; i++) selectedRowDataMap.value.set(get__default["default"](data.value[i], rowKey.value || "id"), data.value[i]);
  }, {
    immediate: true
  });
  return {
    selectedRowClassNames: selectedRowClassNames,
    currentPaginateData: currentPaginateData,
    setTSelectedRowKeys: setTSelectedRowKeys,
    formatToRowSelectColumn: formatToRowSelectColumn,
    onInnerSelectRowClick: onInnerSelectRowClick
  };
}

exports["default"] = useRowSelect;
//# sourceMappingURL=useRowSelect.js.map
