/**
 * ldesign v0.2.14
 * (c) 2022/11/2 16:16 built by swimly
 * @license MIT
 */

import { h as helper } from '../../../chunks/helper.js';
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/use-default-value.js';
import { useGlobalIcon } from '../../../hooks/use-global-icon.js';
import { getCurrentRowByKey } from '../utils.js';
import { Button } from '../../button/index.js';
import { renderTitle } from './useTableHeader.js';
import '../../../chunks/_commonjsHelpers.js';
import '../../../utils/map-props.js';
import 'vue';
import '../../../utils/with-install.js';
import 'lodash';
import '../../../config.js';
import '../../checkbox/group.js';
import '../../../chunks/index.js';
import '../../../chunks/log.js';
import '../../../chunks/_commonjsHelpers-2e6815bd.js';
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 '../../../chunks/zh_CN.js';
import '../../config-provider/type.js';
import '../../../utils/mixins.js';
import '../../checkbox/checkbox.js';
import '../../../utils/render-node.js';
import '../../checkbox/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 '../../dialog/dialog.js';
import 'lodash/isNumber';
import 'lodash/throttle';
import '../../../utils/transfer-dom.js';
import '../../../hooks/use-destroy-onclose.js';
import '../../dialog/props.js';
import '../../dialog/mixins/action.js';
import 'lodash/isObject';
import '../../button/button.js';
import '../../loading/index.js';
import '../../loading/loading.js';
import '../../loading/props.js';
import '../../loading/icon/gradient.js';
import '../../../chunks/defineProperty-838e4192.js';
import '../../../chunks/set-style.js';
import '../../../chunks/helper2.js';
import '../../loading/style/css.js';
import '../../loading/type.js';
import '../../loading/plugin.js';
import '../../../utils/ripple.js';
import '../../button/props.js';
import '../../button/style/css.js';
import '../../button/type.js';
import '../../dialog/stack.js';
import '../../../hooks/use-config.js';
import 'lodash/isFunction';
import 'lodash/get';
import '../core/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 '../../tooltip/props.js';
import '../../tooltip/style/css.js';
import '../../tooltip/type.js';
import './useClassName.js';
import './useMultiHeader.js';

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++) {
    var _col$children;
    const 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) {
  const {
    classPrefix,
    global
  } = useConfig("table");
  const {
    SettingIcon: SettingIcon$1
  } = useGlobalIcon({
    SettingIcon: SettingIcon
  });
  const {
    columns,
    columnController,
    displayColumns,
    columnControllerVisible
  } = toRefs(props);
  const dialogInstance = ref(null);
  const enabledColKeys = computed(() => {
    var _columnController$val;
    const arr = (((_columnController$val = columnController.value) === null || _columnController$val === void 0 ? void 0 : _columnController$val.fields) || [...getColumnKeys(columns.value)]).filter(v => v);
    return new Set(arr);
  });
  const keys = [...getColumnKeys(columns.value)];
  const [tDisplayColumns, setTDisplayColumns] = useDefaultValue(displayColumns, props.defaultDisplayColumns || keys, props.onDisplayColumnsChange, "displayColumns", "display-columns-change");
  const columnCheckboxKeys = ref(displayColumns.value || props.defaultDisplayColumns || keys);
  const checkboxOptions = computed(() => getCheckboxOptions(columns.value));
  const intersectionChecked = computed(() => intersection(columnCheckboxKeys.value, [...enabledColKeys.value]));
  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++) {
      var _item$children;
      const item = columns2[i];
      if (item.colKey) {
        arr.push({
          label: () => 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);
    }
    return arr;
  }
  const handleCheckChange = (val, ctx) => {
    var _props$onColumnChange;
    columnCheckboxKeys.value = val;
    const 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);
  };
  const handleClickAllShowColumns = (checked, ctx) => {
    if (checked) {
      var _checkboxOptions$valu, _props$onColumnChange2;
      const newData = ((_checkboxOptions$valu = checkboxOptions.value) === null || _checkboxOptions$valu === void 0 ? void 0 : _checkboxOptions$valu.map(t => t.value)) || [];
      columnCheckboxKeys.value = newData;
      const 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;
      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$onColumnChange3 = props.onColumnChange) === null || _props$onColumnChange3 === void 0 ? void 0 : _props$onColumnChange3.call(props, params);
      context.emit("column-change", params);
    }
  };
  const handleToggleColumnController = () => {
    var _columnController$val4;
    dialogInstance.value = DialogPlugin.confirm({
      header: global.value.columnConfigTitleText,
      body: h2 => {
        var _columnController$val2, _columnController$val3;
        const widthMode = ((_columnController$val2 = columnController.value) === null || _columnController$val2 === void 0 ? void 0 : _columnController$val2.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 = h("div", {
          "class": classes
        }, [h("div", {
          "class": `${prefix}-table__column-controller-body`
        }, [h("p", {
          "class": `${prefix}-table__column-controller-desc`
        }, [global.value.columnConfigDescriptionText]), h("div", {
          "class": `${prefix}-table__column-controller-block`
        }, [h(Checkbox, {
          "attrs": {
            "indeterminate": isIndeterminate,
            "checked": isCheckedAll
          },
          "on": {
            "change": handleClickAllShowColumns
          }
        }, [global.value.selectAllText])]), h("div", {
          "class": `${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: () => {
        setTDisplayColumns([...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: () => {
        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], _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 => {
    var _props$columnControll;
    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 h("div", {
      "class": classes
    }, [h(Button, helper([{
      "attrs": {
        "theme": "default",
        "variant": "outline",
        "content": global.value.columnConfigButtonText
      },
      "on": {
        "click": handleToggleColumnController
      },
      "scopedSlots": {
        icon: () => h(SettingIcon$1)
      }
    }, {
      "props": (_props$columnControll = props.columnController) === null || _props$columnControll === void 0 ? void 0 : _props$columnControll.buttonProps
    }]))]);
  };
  return {
    tDisplayColumns,
    columnCheckboxKeys,
    checkboxOptions,
    renderColumnController
  };
}

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