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

import _toConsumableArray from '@babel/runtime/helpers/toConsumableArray';
import _typeof from '@babel/runtime/helpers/typeof';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
import { toRefs, ref, computed, watch, createVNode, mergeProps } from 'vue';
import intersection from 'lodash/intersection';
import get from 'lodash/get';
import isFunction from 'lodash/isFunction';
import useDefaultValue from '../../hooks/useDefaultValue.js';
import { isRowSelectedDisabled } from '../../_common/js/table/utils.js';
import { Checkbox } from '../../checkbox/index.js';
import { Radio } from '../../radio/index.js';
import '../../_common/js/log/index.js';
import log from '../../_common/js/log/log.js';
import 'lodash/kebabCase';
import 'lodash/isNumber';
import '../../utils/withInstall.js';
import '../../checkbox/checkbox.js';
import '../../hooks/useVModel.js';
import '../../form/hooks.js';
import '../../hooks/useRipple.js';
import '../../utils/set-style.js';
import '../../hooks/useKeepAnimation.js';
import '../../config-provider/context.js';
import 'lodash/mergeWith';
import 'lodash/merge';
import 'lodash/isArray';
import '../../_common/js/global-config/default-config.js';
import '../../_common/js/global-config/locale/zh_CN.js';
import '../../_chunks/dep-512eb181.js';
import 'dayjs';
import '../../_chunks/dep-ac28b67c.js';
import '../../hooks/useConfig.js';
import '../../config-provider/useConfig.js';
import 'lodash/cloneDeep';
import 'lodash/isString';
import '../../config-provider/type.js';
import '../../hooks/tnode.js';
import 'lodash/camelCase';
import '../../utils/render-tnode.js';
import 'lodash/isEmpty';
import 'lodash/isObject';
import '../../checkbox/props.js';
import '../../checkbox/constants.js';
import '../../checkbox/group.js';
import 'lodash/isUndefined';
import '../../hooks/slot.js';
import '../../checkbox/checkbox-group-props.js';
import '../../checkbox/style';
import '../../checkbox/type.js';
import '../../radio/radio.js';
import '../../utils/helper.js';
import '@babel/runtime/helpers/objectWithoutProperties';
import 'lodash/isNull';
import '../../radio/constants.js';
import '../../radio/props.js';
import '../../radio/group.js';
import '@babel/runtime/helpers/asyncToGenerator';
import '@babel/runtime/regenerator';
import 'lodash/isNil';
import '../../radio/radio-group-props.js';
import '../../radio/useKeyboard.js';
import '../../utils/dom.js';
import '../../utils/easing.js';
import '../../radio/radio-button.js';
import '../../radio/style';
import '../../radio/type.js';

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 useRowSelect(props, tableSelectedClasses) {
  var _toRefs = toRefs(props),
    selectedRowKeys = _toRefs.selectedRowKeys,
    columns = _toRefs.columns,
    rowKey = _toRefs.rowKey,
    data = _toRefs.data,
    pagination = _toRefs.pagination,
    reserveSelectedRowOnPaginate = _toRefs.reserveSelectedRowOnPaginate;
  var currentPaginateData = ref(data.value);
  var selectedRowClassNames = ref();
  var _useDefaultValue = useDefaultValue(selectedRowKeys, props.defaultSelectedRowKeys || [], props.onSelectChange, "selectedRowKeys"),
    _useDefaultValue2 = _slicedToArray(_useDefaultValue, 2),
    tSelectedRowKeys = _useDefaultValue2[0],
    setTSelectedRowKeys = _useDefaultValue2[1];
  var selectedRowDataMap = ref( /* @__PURE__ */new Map());
  var selectColumn = computed(function () {
    return props.columns.find(function (_ref) {
      var type = _ref.type;
      return ["multiple", "single"].includes(type);
    });
  });
  var canSelectedRows = computed(function () {
    var currentData = reserveSelectedRowOnPaginate.value ? data.value : currentPaginateData.value;
    return currentData.filter(function (row, rowIndex) {
      return !isDisabled(row, rowIndex);
    });
  });
  var intersectionKeys = computed(function () {
    return intersection(tSelectedRowKeys.value, canSelectedRows.value.map(function (t) {
      return get(t, props.rowKey || "id");
    }));
  });
  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
  });
  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(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 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 createVNode(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(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(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(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 createVNode(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(row, props.rowKey)) : false;
      return createVNode(Checkbox, mergeProps({
        "indeterminate": isIndeterminate
      }, selectBoxProps), null);
    }
    return null;
  }
  function handleSelectChange() {
    var row = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    var selectedRowKeys2 = _toConsumableArray(tSelectedRowKeys.value);
    var reRowKey = props.rowKey || "id";
    var id = get(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 {
      log.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(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(disabledSelectedRowKeys), _toConsumableArray(canSelectedRowKeys)) : _toConsumableArray(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);
  };
  watch(function () {
    return [_toConsumableArray(data.value), rowKey];
  }, function () {
    for (var i = 0, len = data.value.length; i < len; i++) selectedRowDataMap.value.set(get(data.value[i], rowKey.value || "id"), data.value[i]);
  }, {
    immediate: true
  });
  return {
    selectedRowClassNames: selectedRowClassNames,
    currentPaginateData: currentPaginateData,
    setTSelectedRowKeys: setTSelectedRowKeys,
    formatToRowSelectColumn: formatToRowSelectColumn,
    onInnerSelectRowClick: onInnerSelectRowClick
  };
}

export { useRowSelect as default };
//# sourceMappingURL=useRowSelect.js.map
