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

'use strict';

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

var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var _toConsumableArray = require('@babel/runtime/helpers/toConsumableArray');
var vue = require('vue');
var iconsVueNext = require('@ldesign/icons-vue-next');
var intersection = require('lodash/intersection');
var checkbox_index = require('../../checkbox/index.js');
var dialog_plugin = require('../../dialog/plugin.js');
var configProvider_useConfig = require('../../config-provider/useConfig.js');
var hooks_useGlobalIcon = require('../../hooks/useGlobalIcon.js');
var hooks_useDefaultValue = require('../../hooks/useDefaultValue.js');
var table_utils = require('../utils.js');
var button_index = require('../../button/index.js');
var table_hooks_useTableHeader = require('./useTableHeader.js');
require('../../utils/withInstall.js');
require('../../checkbox/checkbox.js');
require('../../hooks/useVModel.js');
require('lodash/kebabCase');
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('@babel/runtime/helpers/typeof');
require('../../_chunks/dep-7f0559c3.js');
require('dayjs');
require('../../hooks/useConfig.js');
require('lodash/cloneDeep');
require('lodash/isFunction');
require('lodash/isString');
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('../../utils/dom.js');
require('../../utils/easing.js');
require('../../dialog/dialog.js');
require('../../hooks/useDestroyOnClose.js');
require('../../_common/js/utils/getScrollbarWidth.js');
require('../../_common/js/utils/helper.js');
require('@babel/runtime/helpers/objectWithoutProperties');
require('lodash/isNull');
require('lodash/isNumber');
require('../../hooks/useTeleport.js');
require('../../dialog/stack.js');
require('../../dialog/hooks.js');
require('lodash/omit');
require('../../dialog/props.js');
require('../../button/button.js');
require('../../loading/index.js');
require('../../loading/directive.js');
require('../../loading/plugin.js');
require('../../loading/loading.js');
require('../../loading/props.js');
require('../../loading/icon/gradient.js');
require('../../_common/js/loading/circle-adapter.js');
require('../../_common/js/utils/set-style.js');
require('../../button/props.js');
require('lodash/get');
require('../ellipsis.js');
require('lodash/debounce');
require('../../tooltip/index.js');
require('../../tooltip/tooltip.js');
require('../../popup/props.js');
require('../../popup/index.js');
require('../../popup/popup.js');
require('@popperjs/core');
require('../../popup/container.js');
require('../../hooks/useResizeObserver.js');
require('../../tooltip/util.js');
require('../../tooltip/props.js');
require('./useClassName.js');
require('./useMultiHeader.js');

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

var _defineProperty__default = /*#__PURE__*/_interopDefaultLegacy(_defineProperty);
var _slicedToArray__default = /*#__PURE__*/_interopDefaultLegacy(_slicedToArray);
var _toConsumableArray__default = /*#__PURE__*/_interopDefaultLegacy(_toConsumableArray);
var intersection__default = /*#__PURE__*/_interopDefaultLegacy(intersection);

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 getColumnKeys(columns) {
  var keys = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : /* @__PURE__ */new Set();
  for (var i = 0, len = columns.length; i < len; i++) {
    var _col$children;
    var col = columns[i];
    col.colKey && keys.add(col.colKey);
    if ((_col$children = col.children) !== null && _col$children !== void 0 && _col$children.length) getColumnKeys(col.children, keys);
  }
  return keys;
}
function useColumnController(props, context) {
  var _useConfig = configProvider_useConfig.useConfig("table"),
    classPrefix = _useConfig.classPrefix,
    globalConfig = _useConfig.globalConfig;
  var _useGlobalIcon = hooks_useGlobalIcon.useGlobalIcon({
      SettingIcon: iconsVueNext.SettingIcon
    }),
    SettingIcon = _useGlobalIcon.SettingIcon;
  var _toRefs = vue.toRefs(props),
    columns = _toRefs.columns,
    columnController = _toRefs.columnController,
    displayColumns = _toRefs.displayColumns,
    columnControllerVisible = _toRefs.columnControllerVisible;
  var dialogInstance = vue.ref(null);
  var enabledColKeys = vue.computed(function () {
    var _columnController$val;
    var arr = (((_columnController$val = columnController.value) === null || _columnController$val === void 0 ? void 0 : _columnController$val.fields) || _toConsumableArray__default["default"](getColumnKeys(columns.value))).filter(function (v) {
      return v;
    });
    return new Set(arr);
  });
  var keys = _toConsumableArray__default["default"](getColumnKeys(columns.value));
  var _useDefaultValue = hooks_useDefaultValue["default"](displayColumns, props.defaultDisplayColumns || keys, props.onDisplayColumnsChange, "displayColumns"),
    _useDefaultValue2 = _slicedToArray__default["default"](_useDefaultValue, 2),
    tDisplayColumns = _useDefaultValue2[0],
    setTDisplayColumns = _useDefaultValue2[1];
  var columnCheckboxKeys = vue.ref(displayColumns.value || props.defaultDisplayColumns || keys);
  var checkboxOptions = vue.computed(function () {
    return getCheckboxOptions(columns.value);
  });
  var intersectionChecked = vue.computed(function () {
    return intersection__default["default"](columnCheckboxKeys.value, _toConsumableArray__default["default"](enabledColKeys.value));
  });
  vue.watch([displayColumns], function (_ref) {
    var _ref2 = _slicedToArray__default["default"](_ref, 1),
      val = _ref2[0];
    columnCheckboxKeys.value = val || props.defaultDisplayColumns || keys;
  });
  function getCheckboxOptions(columns2) {
    var arr = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
    var _loop = function _loop(i) {
      var _item$children;
      var item = columns2[i];
      if (item.colKey) {
        arr.push({
          label: function label() {
            return table_hooks_useTableHeader.renderTitle(context.slots, item, i);
          },
          value: item.colKey,
          disabled: !enabledColKeys.value.has(item.colKey)
        });
      }
      if ((_item$children = item.children) !== null && _item$children !== void 0 && _item$children.length) getCheckboxOptions(item.children, arr);
    };
    for (var i = 0, len = columns2.length; i < len; i++) {
      _loop(i);
    }
    return arr;
  }
  var handleCheckChange = function handleCheckChange(val, ctx) {
    var _props$onColumnChange;
    columnCheckboxKeys.value = val;
    var params = {
      columns: val,
      type: ctx.type,
      currentColumn: table_utils.getCurrentRowByKey(columns.value, String(ctx.current)),
      e: ctx.e
    };
    (_props$onColumnChange = props.onColumnChange) === null || _props$onColumnChange === void 0 ? void 0 : _props$onColumnChange.call(props, params);
  };
  var handleClickAllShowColumns = function handleClickAllShowColumns(checked, ctx) {
    if (checked) {
      var _checkboxOptions$valu, _props$onColumnChange2;
      var newData = ((_checkboxOptions$valu = checkboxOptions.value) === null || _checkboxOptions$valu === void 0 ? void 0 : _checkboxOptions$valu.map(function (t) {
        return t.value;
      })) || [];
      columnCheckboxKeys.value = newData;
      (_props$onColumnChange2 = props.onColumnChange) === null || _props$onColumnChange2 === void 0 ? void 0 : _props$onColumnChange2.call(props, {
        type: "check",
        columns: newData,
        e: ctx.e
      });
    } else {
      var _props$onColumnChange3;
      var disabledColKeys = checkboxOptions.value.filter(function (t) {
        return t.disabled;
      }).map(function (t) {
        return t.value;
      });
      columnCheckboxKeys.value = disabledColKeys;
      (_props$onColumnChange3 = props.onColumnChange) === null || _props$onColumnChange3 === void 0 ? void 0 : _props$onColumnChange3.call(props, {
        type: "uncheck",
        columns: disabledColKeys,
        e: ctx.e
      });
    }
  };
  var handleToggleColumnController = function handleToggleColumnController() {
    var _columnController$val4;
    dialogInstance.value = dialog_plugin.DialogPlugin.confirm(_objectSpread({
      header: globalConfig.value.columnConfigTitleText,
      body: function body() {
        var _columnController$val2, _columnController$val3;
        var widthMode = ((_columnController$val2 = columnController.value) === null || _columnController$val2 === void 0 ? void 0 : _columnController$val2.displayType) === "fixed-width" ? "fixed" : "auto";
        var checkedLength = intersectionChecked.value.length;
        var isCheckedAll = checkedLength === enabledColKeys.value.size;
        var isIndeterminate = checkedLength > 0 && checkedLength < enabledColKeys.value.size;
        var defaultNode = vue.createVNode("div", {
          "class": ["".concat(classPrefix.value, "-table__column-controller"), "".concat(classPrefix.value, "-table__column-controller--").concat(widthMode)]
        }, [vue.createVNode("div", {
          "class": "".concat(classPrefix.value, "-table__column-controller-body")
        }, [vue.createVNode("p", {
          "class": "".concat(classPrefix.value, "-table__column-controller-desc")
        }, [globalConfig.value.columnConfigDescriptionText]), vue.createVNode("div", {
          "class": "".concat(classPrefix.value, "-table__column-controller-block")
        }, [vue.createVNode(checkbox_index.Checkbox, {
          "indeterminate": isIndeterminate,
          "checked": isCheckedAll,
          "onChange": handleClickAllShowColumns
        }, {
          "default": function _default() {
            return [globalConfig.value.selectAllText];
          }
        })]), vue.createVNode("div", {
          "class": "".concat(classPrefix.value, "-table__column-controller-block")
        }, [vue.createVNode(checkbox_index.CheckboxGroup, vue.mergeProps({
          "options": checkboxOptions.value
        }, ((_columnController$val3 = columnController.value) === null || _columnController$val3 === void 0 ? void 0 : _columnController$val3.checkboxProps) || {}, {
          "value": columnCheckboxKeys.value,
          "onChange": handleCheckChange
        }), null)])])]);
        return defaultNode;
      },
      confirmBtn: globalConfig.value.confirmText,
      cancelBtn: globalConfig.value.cancelText,
      width: 612,
      onConfirm: function onConfirm() {
        setTDisplayColumns(_toConsumableArray__default["default"](columnCheckboxKeys.value));
        if (columnControllerVisible.value === void 0) {
          dialogInstance.value.hide();
        } else {
          var _props$onColumnContro;
          (_props$onColumnContro = props.onColumnControllerVisibleChange) === null || _props$onColumnContro === void 0 ? void 0 : _props$onColumnContro.call(props, false, {
            trigger: "cancel"
          });
          context.emit("update:columnControllerVisible", false);
        }
      },
      onClose: function onClose() {
        if (columnControllerVisible.value === void 0) {
          dialogInstance.value.hide();
        } else {
          var _props$onColumnContro2;
          (_props$onColumnContro2 = props.onColumnControllerVisibleChange) === null || _props$onColumnContro2 === void 0 ? void 0 : _props$onColumnContro2.call(props, false, {
            trigger: "confirm"
          });
          context.emit("update:columnControllerVisible", false);
        }
      }
    }, ((_columnController$val4 = columnController.value) === null || _columnController$val4 === void 0 ? void 0 : _columnController$val4.dialogProps) || {}));
  };
  vue.watch([columnControllerVisible], function (_ref3) {
    var _ref4 = _slicedToArray__default["default"](_ref3, 1),
      visible = _ref4[0];
    if (visible === void 0) return;
    if (dialogInstance.value) visible ? dialogInstance.value.show() : dialogInstance.value.hide();else visible && handleToggleColumnController();
  }, {
    immediate: true
  });
  var renderColumnController = function renderColumnController() {
    var _props$columnControll;
    var isColumnController = !!(columnController.value && Object.keys(columnController.value).length);
    var placement = isColumnController ? columnController.value.placement || "top-right" : "";
    if (isColumnController && columnController.value.hideTriggerButton) return null;
    var classes = ["".concat(classPrefix.value, "-table__column-controller-trigger"), _defineProperty__default["default"]({}, "".concat(classPrefix.value, "-align-").concat(placement), !!placement)];
    return vue.createVNode("div", {
      "class": classes
    }, [vue.createVNode(button_index.Button, vue.mergeProps({
      "theme": "default",
      "variant": "outline",
      "onClick": handleToggleColumnController,
      "content": globalConfig.value.columnConfigButtonText
    }, (_props$columnControll = props.columnController) === null || _props$columnControll === void 0 ? void 0 : _props$columnControll.buttonProps), {
      icon: function icon() {
        return vue.createVNode(SettingIcon, null, null);
      }
    })]);
  };
  return {
    tDisplayColumns: tDisplayColumns,
    columnCheckboxKeys: columnCheckboxKeys,
    checkboxOptions: checkboxOptions,
    renderColumnController: renderColumnController
  };
}

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