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

'use strict';

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

var _toConsumableArray = require('@babel/runtime/helpers/toConsumableArray');
var helper = require('../../_chunks/dep-c3e1ffac.js');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var VueCompositionAPI = require('@vue/composition-api');
var intersection = require('lodash/intersection');
var get = require('lodash/get');
var isFunction = require('lodash/isFunction');
var hooks_useDefaultValue = require('../../hooks/useDefaultValue.js');
var table_utils = require('../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('@babel/runtime/helpers/typeof');
require('lodash/isObject');
require('../../utils/map-props.js');
require('@babel/runtime/helpers/objectWithoutProperties');
require('vue');
require('../../utils/withInstall.js');
require('lodash/capitalize');
require('../../checkbox/group.js');
require('../../utils/event.js');
require('../../utils/helper.js');
require('lodash/camelCase');
require('../../config-provider/config-receiver.js');
require('lodash/mergeWith');
require('../../config-provider/context.js');
require('lodash/merge');
require('../../_common/js/global-config/default-config.js');
require('../../_common/js/global-config/locale/zh_CN.js');
require('../../_chunks/dep-7c884501.js');
require('dayjs');
require('../../utils/mixins.js');
require('../../checkbox/checkbox.js');
require('../../utils/render-tnode.js');
require('lodash/kebabCase');
require('../../checkbox/props.js');
require('../../checkbox/checkbox-group-props.js');
require('../../radio/radio.js');
require('../../radio/props.js');
require('../../radio/group.js');
require('lodash/isString');
require('lodash/isNumber');
require('../../utils/dom.js');
require('raf');
require('../../utils/easing.js');
require('../../radio/radio-group-props.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 _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 = VueCompositionAPI.toRefs(props),
    selectedRowKeys = _toRefs.selectedRowKeys,
    columns = _toRefs.columns,
    data = _toRefs.data,
    rowKey = _toRefs.rowKey,
    pagination = _toRefs.pagination,
    reserveSelectedRowOnPaginate = _toRefs.reserveSelectedRowOnPaginate;
  var currentPaginateData = VueCompositionAPI.ref(data.value);
  var selectedRowClassNames = VueCompositionAPI.ref();
  var _useDefaultValue = hooks_useDefaultValue["default"](selectedRowKeys, props.defaultSelectedRowKeys || [], props.onSelectChange, "selectedRowKeys", "select-change"),
    _useDefaultValue2 = _slicedToArray__default["default"](_useDefaultValue, 2),
    tSelectedRowKeys = _useDefaultValue2[0],
    setTSelectedRowKeys = _useDefaultValue2[1];
  var selectedRowDataMap = VueCompositionAPI.ref( /* @__PURE__ */new Map());
  var selectColumn = VueCompositionAPI.computed(function () {
    return props.columns.find(function (_ref) {
      var type = _ref.type;
      return ["multiple", "single"].includes(type);
    });
  });
  var canSelectedRows = VueCompositionAPI.computed(function () {
    var currentData = reserveSelectedRowOnPaginate.value ? data.value : currentPaginateData.value;
    return currentData.filter(function (row, rowIndex) {
      return !isDisabled(row, rowIndex);
    });
  });
  var intersectionKeys = VueCompositionAPI.computed(function () {
    return intersection__default["default"](tSelectedRowKeys.value, canSelectedRows.value.map(function (t) {
      return get__default["default"](t, props.rowKey || "id");
    }));
  });
  var allowUncheck = VueCompositionAPI.computed(function () {
    var singleSelectCol = columns.value.find(function (col) {
      return col.type === "single";
    });
    if (!singleSelectCol || !singleSelectCol.checkProps || !("allowUncheck" in singleSelectCol.checkProps)) return false;
    return singleSelectCol.checkProps.allowUncheck;
  });
  VueCompositionAPI.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
  });
  VueCompositionAPI.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].filter(function (v) {
      return v;
    });
  }, {
    immediate: true
  });
  function isDisabled(row, rowIndex) {
    return table_utils.isRowSelectedDisabled(selectColumn.value, row, rowIndex);
  }
  function getSelectedHeader(h2) {
    return function () {
      return VueCompositionAPI.h(checkbox_index.Checkbox, {
        "attrs": {
          "checked": intersectionKeys.value.length !== 0 && canSelectedRows.value.length !== 0 && intersectionKeys.value.length === canSelectedRows.value.length,
          "indeterminate": intersectionKeys.value.length > 0 && intersectionKeys.value.length < canSelectedRows.value.length,
          "disabled": !canSelectedRows.value.length
        },
        "on": _objectSpread({}, {
          change: handleSelectAll
        })
      });
    };
  }
  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(h2, 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 = {
      props: _objectSpread({
        checked: checked,
        disabled: disabled
      }, checkProps),
      on: {
        click: function click(_ref3) {
          var e = _ref3.e;
          e === null || e === void 0 ? void 0 : e.stopPropagation();
        },
        change: function change() {
          return handleSelectChange(row);
        }
      }
    };
    if (column.type === "single") return VueCompositionAPI.h(radio_index.Radio, helper.helper([{}, selectBoxProps]));
    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 VueCompositionAPI.h(checkbox_index.Checkbox, helper.helper([{
        "attrs": {
          "indeterminate": isIndeterminate
        }
      }, selectBoxProps]));
    }
    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 && allowUncheck.value ? [] : [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(h2, p) {
        return renderSelectCell(h2, p);
      },
      title: col.type === "multiple" ? getSelectedHeader() : col.title
    });
  }
  var onInnerSelectRowClick = function onInnerSelectRowClick(_ref4) {
    var row = _ref4.row,
      index = _ref4.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);
  };
  VueCompositionAPI.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
