/**
 * ldesign v0.2.22
 * (c) 2022/12/7 16:21 built by swimly
 * @license MIT
 */

'use strict';

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

var helper = require('../../../chunks/helper.js');
var VueCompositionAPI = require('@vue/composition-api');
var iconsVue = require('@ldesign/icons-vue');
var intersection = require('lodash/intersection');
var components_checkbox_index = require('../../checkbox/index.js');
var components_dialog_plugin = require('../../dialog/plugin.js');
var components_configProvider_useConfig = require('../../config-provider/useConfig.js');
var hooks_useDefaultValue = require('../../../hooks/useDefaultValue.js');
var hooks_useGlobalIcon = require('../../../hooks/useGlobalIcon.js');
var components_table_utils = require('../utils.js');
var components_button_index = require('../../button/index.js');
var components_table_hooks_useTableHeader = require('./useTableHeader.js');
require('../../../utils/map-props.js');
require('vue');
require('../../../utils/withInstall.js');
require('lodash/capitalize');
require('../../../config.js');
require('../../checkbox/group.js');
require('../../../chunks/log.js');
require('../../../chunks/_commonjsHelpers-fe796db6.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('../../../chunks/zh_CN.js');
require('../../../utils/mixins.js');
require('../../checkbox/checkbox.js');
require('../../../utils/render-node.js');
require('lodash');
require('../../checkbox/props.js');
require('../../../utils/dom.js');
require('raf');
require('lodash/isString');
require('../../../utils/easing.js');
require('../../dialog/dialog.js');
require('lodash/isNumber');
require('lodash/throttle');
require('../../../utils/transfer-dom.js');
require('../../../hooks/useDestroyOnClose.js');
require('../../dialog/props.js');
require('../../dialog/actions.js');
require('lodash/isObject');
require('../../button/button.js');
require('../../loading/index.js');
require('../../loading/loading.js');
require('../../loading/props.js');
require('../../loading/icon/gradient.js');
require('../../../chunks/defineProperty-19da3d4c.js');
require('../../../chunks/set-style.js');
require('../../../chunks/helper2.js');
require('../../loading/plugin.js');
require('../../../utils/ripple.js');
require('../../button/props.js');
require('../../dialog/stack.js');
require('lodash/isFunction');
require('lodash/get');
require('../core/ellipsis.js');
require('lodash/debounce');
require('../../tooltip/index.js');
require('../../tooltip/tooltip.js');
require('../../popup/props.js');
require('../../popup/popup.js');
require('@popperjs/core');
require('../../popup/container.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 intersection__default = /*#__PURE__*/_interopDefaultLegacy(intersection);

function getColumnKeys(columns) {
  let keys = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : /* @__PURE__ */new Set();
  for (let i = 0, len = columns.length; i < len; i++) {
    const col = columns[i];
    col.colKey && keys.add(col.colKey);
    if (col.children?.length) getColumnKeys(col.children, keys);
  }
  return keys;
}
function useColumnController(props, context) {
  const {
    classPrefix,
    global
  } = components_configProvider_useConfig.useConfig("table");
  const {
    SettingIcon
  } = hooks_useGlobalIcon.useGlobalIcon({
    SettingIcon: iconsVue.SettingIcon
  });
  const {
    columns,
    columnController,
    displayColumns,
    columnControllerVisible
  } = VueCompositionAPI.toRefs(props);
  const dialogInstance = VueCompositionAPI.ref(null);
  const enabledColKeys = VueCompositionAPI.computed(() => {
    const arr = (columnController.value?.fields || [...getColumnKeys(columns.value)]).filter(v => v);
    return new Set(arr);
  });
  const keys = [...getColumnKeys(columns.value)];
  const [tDisplayColumns, setTDisplayColumns] = hooks_useDefaultValue["default"](displayColumns, props.defaultDisplayColumns || keys, props.onDisplayColumnsChange, "displayColumns", "display-columns-change");
  const columnCheckboxKeys = VueCompositionAPI.ref(displayColumns.value || props.defaultDisplayColumns || keys);
  const checkboxOptions = VueCompositionAPI.computed(() => getCheckboxOptions(columns.value));
  const intersectionChecked = VueCompositionAPI.computed(() => intersection__default["default"](columnCheckboxKeys.value, [...enabledColKeys.value]));
  VueCompositionAPI.watch([displayColumns], _ref => {
    let [val] = _ref;
    columnCheckboxKeys.value = val || props.defaultDisplayColumns || keys;
  });
  function getCheckboxOptions(columns2) {
    let arr = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
    for (let i = 0, len = columns2.length; i < len; i++) {
      const item = columns2[i];
      if (item.colKey) {
        arr.push({
          label: () => components_table_hooks_useTableHeader.renderTitle(VueCompositionAPI.h, context.slots, item, i),
          value: item.colKey,
          disabled: !enabledColKeys.value.has(item.colKey)
        });
      }
      if (item.children?.length) getCheckboxOptions(item.children, arr);
    }
    return arr;
  }
  const handleCheckChange = (val, ctx) => {
    columnCheckboxKeys.value = val;
    const params = {
      columns: val,
      type: ctx.type,
      currentColumn: components_table_utils.getCurrentRowByKey(columns.value, String(ctx.current)),
      e: ctx.e
    };
    props.onColumnChange?.(params);
    context.emit("column-change", params);
  };
  const handleClickAllShowColumns = (checked, ctx) => {
    if (checked) {
      const newData = checkboxOptions.value?.map(t => t.value) || [];
      columnCheckboxKeys.value = newData;
      const params = {
        type: "check",
        columns: newData,
        e: ctx.e
      };
      props.onColumnChange?.(params);
      context.emit("column-change", params);
    } else {
      const disabledColKeys = checkboxOptions.value.filter(t => t.disabled).map(t => t.value);
      columnCheckboxKeys.value = disabledColKeys;
      const params = {
        type: "uncheck",
        columns: disabledColKeys,
        e: ctx.e
      };
      props.onColumnChange?.(params);
      context.emit("column-change", params);
    }
  };
  const handleToggleColumnController = () => {
    dialogInstance.value = components_dialog_plugin.DialogPlugin.confirm({
      header: global.value.columnConfigTitleText,
      body: h2 => {
        const widthMode = columnController.value?.displayType === "fixed-width" ? "fixed" : "auto";
        const checkedLength = intersectionChecked.value.length;
        const isCheckedAll = checkedLength === enabledColKeys.value.size;
        const isIndeterminate = checkedLength > 0 && checkedLength < enabledColKeys.value.size;
        const prefix = classPrefix.value;
        const classes = [`${prefix}-table__column-controller`, `${prefix}-table__column-controller--${widthMode}`];
        const defaultNode = VueCompositionAPI.h("div", {
          "class": classes
        }, [VueCompositionAPI.h("div", {
          "class": `${prefix}-table__column-controller-body`
        }, [VueCompositionAPI.h("p", {
          "class": `${prefix}-table__column-controller-desc`
        }, [global.value.columnConfigDescriptionText]), VueCompositionAPI.h("div", {
          "class": `${prefix}-table__column-controller-block`
        }, [VueCompositionAPI.h(components_checkbox_index.Checkbox, {
          "attrs": {
            "indeterminate": isIndeterminate,
            "checked": isCheckedAll
          },
          "on": {
            "change": handleClickAllShowColumns
          }
        }, [global.value.selectAllText])]), VueCompositionAPI.h("div", {
          "class": `${prefix}-table__column-controller-block`
        }, [VueCompositionAPI.h(components_checkbox_index.CheckboxGroup, helper.helper([{
          "attrs": {
            "options": checkboxOptions.value
          }
        }, {
          "props": columnController.value?.checkboxProps
        }, {
          "attrs": {
            "value": columnCheckboxKeys.value
          },
          "on": {
            "change": handleCheckChange
          }
        }]))])])]);
        return defaultNode;
      },
      confirmBtn: global.value.confirmText,
      cancelBtn: global.value.cancelText,
      width: 612,
      onConfirm: () => {
        setTDisplayColumns([...columnCheckboxKeys.value]);
        if (columnControllerVisible.value === void 0) {
          dialogInstance.value.hide();
        } else {
          props.onColumnControllerVisibleChange?.(false, {
            trigger: "confirm"
          });
          context.emit("update:columnControllerVisible", false);
        }
      },
      onClose: () => {
        if (columnControllerVisible.value === void 0) {
          dialogInstance.value.hide();
        } else {
          props.onColumnControllerVisibleChange?.(false, {
            trigger: "cancel"
          });
          context.emit("update:columnControllerVisible", false);
        }
      },
      ...(columnController.value?.dialogProps || {})
    });
  };
  VueCompositionAPI.watch([columnControllerVisible], _ref2 => {
    let [visible] = _ref2;
    if (visible === void 0) return;
    if (dialogInstance.value) visible ? dialogInstance.value.show() : dialogInstance.value.hide();else visible && handleToggleColumnController();
  }, {
    immediate: true
  });
  const renderColumnController = h2 => {
    const isColumnController = !!(columnController.value && Object.keys(columnController.value).length);
    const placement = isColumnController ? columnController.value.placement || "top-right" : "";
    if (isColumnController && columnController.value.hideTriggerButton) return null;
    const classes = [`${classPrefix.value}-table__column-controller-trigger`, {
      [`${classPrefix.value}-align-${placement}`]: !!placement
    }];
    return VueCompositionAPI.h("div", {
      "class": classes
    }, [VueCompositionAPI.h(components_button_index.Button, helper.helper([{
      "attrs": {
        "theme": "default",
        "variant": "outline",
        "content": global.value.columnConfigButtonText
      },
      "on": {
        "click": handleToggleColumnController
      },
      "scopedSlots": {
        icon: () => VueCompositionAPI.h(SettingIcon)
      }
    }, {
      "props": props.columnController?.buttonProps
    }]))]);
  };
  return {
    tDisplayColumns,
    columnCheckboxKeys,
    checkboxOptions,
    renderColumnController
  };
}

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