/**
 * tdesign v0.41.7
 * (c) 2022 tdesign
 * @license MIT
 */

'use strict';

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

var helper = require('../../_chunks/dep-99705d51.js');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var _toConsumableArray = require('@babel/runtime/helpers/toConsumableArray');
var VueCompositionAPI = require('@vue/composition-api');
var tdesignIconsVue = require('tdesign-icons-vue');
var intersection = require('lodash/intersection');
var checkbox_index = require('../../checkbox/index.js');
var dialog_plugin = require('../../dialog/plugin.js');
var table_hooks_useTableHeader = require('./useTableHeader.js');
var configProvider_useConfig = require('../../config-provider/useConfig.js');
var hooks_useDefaultValue = require('../../hooks/useDefaultValue.js');
var table_utils = require('../utils.js');
var button_index = require('../../button/index.js');
require('../../checkbox/group.js');
require('@babel/runtime/helpers/typeof');
require('vue');
require('../../config.js');
require('../../checkbox/checkbox.js');
require('../../utils/render-tnode.js');
require('../../utils/classnames.js');
require('../../checkbox/props.js');
require('../../utils/helper.js');
require('@babel/runtime/helpers/objectWithoutProperties');
require('lodash/camelCase');
require('../../utils/event.js');
require('../../checkbox/checkbox-group-props.js');
require('../../utils/map-props.js');
require('../../utils/withInstall.js');
require('lodash/capitalize');
require('../../dialog/dialog.js');
require('lodash/throttle');
require('../../dialog/actions.js');
require('lodash/isString');
require('lodash/isObject');
require('../../dialog/props.js');
require('../../utils/mixins.js');
require('../../config-provider/config-receiver.js');
require('lodash/mergeWith');
require('../../config-provider/context.js');
require('lodash/merge');
require('../../_common/js/global-config/default-config.js');
require('../../_common/js/global-config/locale/zh_CN.js');
require('../../utils/transfer-dom.js');
require('../../utils/dom.js');
require('raf');
require('../../utils/easing.js');
require('../../hooks/useDestroyOnClose.js');
require('../../button/button.js');
require('../../loading/index.js');
require('../../loading/loading.js');
require('../../loading/icon/gradient.js');
require('../../_common/js/loading/circle-adapter.js');
require('../../_common/js/utils/set-style.js');
require('../../_common/js/utils/helper.js');
require('../../loading/props.js');
require('../../loading/plugin.js');
require('../../button/props.js');
require('../../utils/ripple.js');
require('lodash/isFunction');
require('./useMultiHeader.js');
require('./useClassName.js');
require('lodash/cloneDeep');
require('../ellipsis.js');
require('lodash/debounce');
require('../../popup/index.js');
require('../../popup/popup.js');
require('@popperjs/core');
require('../../popup/props.js');
require('../../popup/container.js');
require('lodash/get');

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,
      global = _useConfig.global;

  var _toRefs = VueCompositionAPI.toRefs(props),
      columns = _toRefs.columns,
      columnController = _toRefs.columnController,
      displayColumns = _toRefs.displayColumns,
      columnControllerVisible = _toRefs.columnControllerVisible;

  var dialogInstance = VueCompositionAPI.ref(null);
  var enabledColKeys = VueCompositionAPI.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", "display-columns-change"),
      _useDefaultValue2 = _slicedToArray__default["default"](_useDefaultValue, 2),
      tDisplayColumns = _useDefaultValue2[0],
      setTDisplayColumns = _useDefaultValue2[1];

  var columnCheckboxKeys = VueCompositionAPI.ref(displayColumns.value || props.defaultDisplayColumns || keys);
  var checkboxOptions = VueCompositionAPI.computed(function () {
    return getCheckboxOptions(columns.value);
  });
  var intersectionChecked = VueCompositionAPI.computed(function () {
    return intersection__default["default"](columnCheckboxKeys.value, _toConsumableArray__default["default"](enabledColKeys.value));
  });
  VueCompositionAPI.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, len) {
      var _item$children;

      var item = columns2[i];

      if (item.colKey) {
        arr.push({
          label: function label() {
            return 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);
      }
    };

    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);
    context.emit("column-change", params);
  };

  var handleClickAllShowColumns = function handleClickAllShowColumns(checked, ctx) {
    if (checked) {
      var _columns$value, _props$onColumnChange2;

      var newData = ((_columns$value = columns.value) === null || _columns$value === void 0 ? void 0 : _columns$value.map(function (t) {
        return t.colKey;
      })) || [];
      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 = dialog_plugin.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 = VueCompositionAPI.h("div", {
          "class": classes
        }, [VueCompositionAPI.h("div", {
          "class": "".concat(prefix, "-table__column-controller-body")
        }, [VueCompositionAPI.h("p", {
          "class": "".concat(prefix, "-table__column-controller-desc")
        }, [global.value.columnConfigDescriptionText]), VueCompositionAPI.h("div", {
          "class": "".concat(prefix, "-table__column-controller-block")
        }, [VueCompositionAPI.h(checkbox_index.Checkbox, {
          "attrs": {
            "indeterminate": isIndeterminate,
            "checked": isCheckedAll
          },
          "on": {
            "change": handleClickAllShowColumns
          }
        }, [global.value.selectAllText])]), VueCompositionAPI.h("div", {
          "class": "".concat(prefix, "-table__column-controller-block")
        }, [VueCompositionAPI.h(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: 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) || {}));
  };

  VueCompositionAPI.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(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__default["default"]({}, "".concat(classPrefix.value, "-align-").concat(placement), !!placement)];
    return VueCompositionAPI.h("div", {
      "class": classes
    }, [VueCompositionAPI.h(button_index.Button, helper.helper([{
      "attrs": {
        "theme": "default",
        "variant": "outline",
        "content": global.value.columnConfigButtonText
      },
      "on": {
        "click": handleToggleColumnController
      },
      "scopedSlots": {
        icon: function icon() {
          return VueCompositionAPI.h(tdesignIconsVue.SettingIcon);
        }
      }
    }, {
      "props": (_props$columnControll = props.columnController) === null || _props$columnControll === void 0 ? void 0 : _props$columnControll.buttonProps
    }]))]);
  };

  return {
    tDisplayColumns: tDisplayColumns,
    columnCheckboxKeys: columnCheckboxKeys,
    checkboxOptions: checkboxOptions,
    renderColumnController: renderColumnController
  };
}

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