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

import { h as helper } from '../../_chunks/dep-c89aafbb.js';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
import _toConsumableArray from '@babel/runtime/helpers/toConsumableArray';
import { toRefs, ref, computed, watch, h } from '@vue/composition-api';
import { SettingIcon } from '@ldesign/icons-vue';
import intersection from 'lodash/intersection';
import { Checkbox, CheckboxGroup } from '../../checkbox/index.js';
import { DialogPlugin } from '../../dialog/plugin.js';
import { useConfig } from '../../config-provider/useConfig.js';
import useDefaultValue from '../../hooks/useDefaultValue.js';
import { useGlobalIcon } from '../../hooks/useGlobalIcon.js';
import { getCurrentRowByKey } from '../utils.js';
import { Button } from '../../button/index.js';
import { renderTitle } from './useTableHeader.js';
import '../../utils/map-props.js';
import '@babel/runtime/helpers/objectWithoutProperties';
import 'vue';
import '../../utils/withInstall.js';
import 'lodash/capitalize';
import '../../checkbox/group.js';
import '@babel/runtime/helpers/typeof';
import '../../utils/event.js';
import '../../utils/helper.js';
import 'lodash/camelCase';
import '../../config-provider/config-receiver.js';
import 'lodash/mergeWith';
import '../../config-provider/context.js';
import 'lodash/merge';
import '../../_common/js/global-config/default-config.js';
import '../../_common/js/global-config/locale/zh_CN.js';
import '../../_chunks/dep-be599ec8.js';
import 'dayjs';
import '../../_chunks/dep-67ff4010.js';
import '../../config-provider/type.js';
import '../../utils/mixins.js';
import '../../checkbox/checkbox.js';
import '../../utils/render-tnode.js';
import 'lodash/kebabCase';
import '../../checkbox/props.js';
import '../../checkbox/checkbox-group-props.js';
import '../../checkbox/style/css.js';
import '../../checkbox/type.js';
import '../../utils/dom.js';
import 'raf';
import 'lodash/isString';
import '../../utils/easing.js';
import '../../config-provider/config-provider.js';
import 'lodash/cloneDeep';
import '../../dialog/dialog.js';
import 'lodash/isNumber';
import 'lodash/throttle';
import '../../utils/transfer-dom.js';
import '../../hooks/useDestroyOnClose.js';
import '../../_common/js/utils/getScrollbarWidth.js';
import '../../_common/js/utils/helper.js';
import 'lodash/isNull';
import 'lodash/isUndefined';
import 'lodash/isArray';
import '../../dialog/stack.js';
import '../../dialog/props.js';
import '../../dialog/actions.js';
import 'lodash/isObject';
import '../../button/button.js';
import '../../loading/index.js';
import '../../loading/directive.js';
import 'lodash/mapKeys';
import 'lodash/isEqual';
import '../../loading/plugin.js';
import '../../config.js';
import '../../loading/loading.js';
import '../../loading/props.js';
import '../../loading/icon/gradient.js';
import '../../_common/js/loading/circle-adapter.js';
import '../../_common/js/utils/set-style.js';
import '../../loading/style/css.js';
import '../../loading/type.js';
import '../../utils/ripple.js';
import '../../button/props.js';
import '../../button/style/css.js';
import '../../button/type.js';
import '../../hooks/useConfig.js';
import 'lodash/isFunction';
import 'lodash/get';
import '../ellipsis.js';
import 'lodash/debounce';
import '../../tooltip/index.js';
import '../../tooltip/tooltip.js';
import '../../popup/props.js';
import '../../popup/popup.js';
import '@popperjs/core';
import '../../popup/container.js';
import '../../popup/utils.js';
import '../../popup/trigger.js';
import '../../tooltip/props.js';
import '../../tooltip/style/css.js';
import '../../tooltip/type.js';
import '../../_common/js/log/index.js';
import '../../_common/js/log/log.js';
import './useClassName.js';
import './useMultiHeader.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 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 = useConfig("table"),
    classPrefix = _useConfig.classPrefix,
    global = _useConfig.global;
  var _useGlobalIcon = useGlobalIcon({
      SettingIcon: SettingIcon
    }),
    SettingIcon$1 = _useGlobalIcon.SettingIcon;
  var _toRefs = toRefs(props),
    columns = _toRefs.columns,
    columnController = _toRefs.columnController,
    displayColumns = _toRefs.displayColumns,
    columnControllerVisible = _toRefs.columnControllerVisible;
  var dialogInstance = ref(null);
  var enabledColKeys = computed(function () {
    var _columnController$val;
    var arr = (((_columnController$val = columnController.value) === null || _columnController$val === void 0 ? void 0 : _columnController$val.fields) || _toConsumableArray(getColumnKeys(columns.value))).filter(function (v) {
      return v;
    });
    return new Set(arr);
  });
  var keys = _toConsumableArray(getColumnKeys(columns.value));
  var _useDefaultValue = useDefaultValue(displayColumns, props.defaultDisplayColumns || keys, props.onDisplayColumnsChange, "displayColumns", "display-columns-change"),
    _useDefaultValue2 = _slicedToArray(_useDefaultValue, 2),
    tDisplayColumns = _useDefaultValue2[0],
    setTDisplayColumns = _useDefaultValue2[1];
  var columnCheckboxKeys = ref(displayColumns.value || props.defaultDisplayColumns || keys);
  var checkboxOptions = computed(function () {
    return getCheckboxOptions(columns.value);
  });
  var intersectionChecked = computed(function () {
    return intersection(columnCheckboxKeys.value, _toConsumableArray(enabledColKeys.value));
  });
  watch([displayColumns], function (_ref) {
    var _ref2 = _slicedToArray(_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 renderTitle(h, 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: 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);
    context.emit("column-change", 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;
      var params = {
        type: "check",
        columns: newData,
        e: ctx.e
      };
      (_props$onColumnChange2 = props.onColumnChange) === null || _props$onColumnChange2 === void 0 ? void 0 : _props$onColumnChange2.call(props, params);
      context.emit("column-change", params);
    } else {
      var _props$onColumnChange3;
      var disabledColKeys = checkboxOptions.value.filter(function (t) {
        return t.disabled;
      }).map(function (t) {
        return t.value;
      });
      columnCheckboxKeys.value = disabledColKeys;
      var _params = {
        type: "uncheck",
        columns: disabledColKeys,
        e: ctx.e
      };
      (_props$onColumnChange3 = props.onColumnChange) === null || _props$onColumnChange3 === void 0 ? void 0 : _props$onColumnChange3.call(props, _params);
      context.emit("column-change", _params);
    }
  };
  var handleToggleColumnController = function handleToggleColumnController() {
    var _columnController$val4;
    dialogInstance.value = DialogPlugin.confirm(_objectSpread({
      header: global.value.columnConfigTitleText,
      body: function body(h2) {
        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 prefix = classPrefix.value;
        var classes = ["".concat(prefix, "-table__column-controller"), "".concat(prefix, "-table__column-controller--").concat(widthMode)];
        var defaultNode = h("div", {
          "class": classes
        }, [h("div", {
          "class": "".concat(prefix, "-table__column-controller-body")
        }, [h("p", {
          "class": "".concat(prefix, "-table__column-controller-desc")
        }, [global.value.columnConfigDescriptionText]), h("div", {
          "class": "".concat(prefix, "-table__column-controller-block")
        }, [h(Checkbox, {
          "attrs": {
            "indeterminate": isIndeterminate,
            "checked": isCheckedAll
          },
          "on": {
            "change": handleClickAllShowColumns
          }
        }, [global.value.selectAllText])]), h("div", {
          "class": "".concat(prefix, "-table__column-controller-block")
        }, [h(CheckboxGroup, helper([{
          "attrs": {
            "options": checkboxOptions.value
          }
        }, {
          "props": (_columnController$val3 = columnController.value) === null || _columnController$val3 === void 0 ? void 0 : _columnController$val3.checkboxProps
        }, {
          "attrs": {
            "value": columnCheckboxKeys.value
          },
          "on": {
            "change": handleCheckChange
          }
        }]))])])]);
        return defaultNode;
      },
      confirmBtn: global.value.confirmText,
      cancelBtn: global.value.cancelText,
      width: 612,
      onConfirm: function onConfirm() {
        setTDisplayColumns(_toConsumableArray(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: "confirm"
          });
          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: "cancel"
          });
          context.emit("update:columnControllerVisible", false);
        }
      }
    }, ((_columnController$val4 = columnController.value) === null || _columnController$val4 === void 0 ? void 0 : _columnController$val4.dialogProps) || {}));
  };
  watch([columnControllerVisible], function (_ref3) {
    var _ref4 = _slicedToArray(_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(h2) {
    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({}, "".concat(classPrefix.value, "-align-").concat(placement), !!placement)];
    return h("div", {
      "class": classes
    }, [h(Button, helper([{
      "attrs": {
        "theme": "default",
        "variant": "outline",
        "content": global.value.columnConfigButtonText
      },
      "on": {
        "click": handleToggleColumnController
      },
      "scopedSlots": {
        icon: function icon() {
          return h(SettingIcon$1);
        }
      }
    }, {
      "props": (_props$columnControll = props.columnController) === null || _props$columnControll === void 0 ? void 0 : _props$columnControll.buttonProps
    }]))]);
  };
  return {
    tDisplayColumns: tDisplayColumns,
    columnCheckboxKeys: columnCheckboxKeys,
    checkboxOptions: checkboxOptions,
    renderColumnController: renderColumnController
  };
}

export { useColumnController as default, getColumnKeys };
//# sourceMappingURL=useColumnController.js.map
