/**
 * ldesign v0.2.14
 * (c) 2022/11/2 16:16 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/use-default-value.js');
var hooks_useGlobalIcon = require('../../../hooks/use-global-icon.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/with-install.js');
require('lodash');
require('../../../config.js');
require('../../checkbox/group.js');
require('../../../chunks/log.js');
require('../../../chunks/_commonjsHelpers-2e6815bd.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('../../../chunks/zh_CN.js');
require('../../../utils/mixins.js');
require('../../checkbox/checkbox.js');
require('../../../utils/render-node.js');
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/use-destroy-onclose.js');
require('../../dialog/props.js');
require('../../dialog/mixins/action.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-838e4192.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++) {
    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
  } = 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(() => {
    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] = 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++) {
      var _item$children;
      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 = 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: components_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);
    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 = components_dialog_plugin.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 = 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$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) || {})
    });
  };
  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 => {
    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 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$columnControll = props.columnController) === null || _props$columnControll === void 0 ? void 0 : _props$columnControll.buttonProps
    }]))]);
  };
  return {
    tDisplayColumns,
    columnCheckboxKeys,
    checkboxOptions,
    renderColumnController
  };
}

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