import { defineComponent, computed, watch, provide, openBlock, createElementBlock, normalizeClass, renderSlot } from 'vue';
import { isNil } from 'lodash-es';
import { useTheme } from '../_theme/useTheme';
import { useNormalModel } from '../_util/use/useModel';
import { UPDATE_MODEL_EVENT } from '../_util/constants';
import { collapseProps } from './collapseExpose';
import { useNamespace } from './useNamespace';
import { COMPONENT_NAME, collapseContextKey, arrowPositionKey } from './common';

var script = defineComponent({
  name: COMPONENT_NAME,
  props: collapseProps,
  emits: [UPDATE_MODEL_EVENT],
  setup(props, _ref) {
    let {
      emit
    } = _ref;
    useTheme();
    const [modelValue, setModelValue] = useNormalModel(props, emit);
    const activeNames = computed({
      get: () => {
        if (isNil(modelValue.value)) {
          return [];
        }
        if (props.accordion) {
          if (Array.isArray(modelValue.value)) {
            console.warn(`${COMPONENT_NAME}: 手风琴模式下 modelValue 不支持数组`);
            return [];
          }
          return [modelValue.value];
        } else {
          if (!Array.isArray(modelValue.value)) {
            console.warn(`${COMPONENT_NAME}: 非手风琴模式下 modelValue 仅支持数组`);
            return [];
          }
          return modelValue.value;
        }
      },
      set: names => {
        if (props.accordion) {
          setModelValue(names[0]);
        } else {
          setModelValue(names);
        }
      }
    });

    // 手风琴模式变化时，重置 modelValue
    watch(() => props.accordion, () => {
      activeNames.value = [];
    });
    const handleItemClick = name => {
      let _activeNames = [...activeNames.value];
      const index = _activeNames.indexOf(name);
      if (props.accordion) {
        _activeNames = index > -1 ? [] : [name];
      } else {
        if (index > -1) {
          _activeNames.splice(index, 1);
        } else {
          _activeNames.push(name);
        }
      }
      activeNames.value = _activeNames;
    };
    provide(collapseContextKey, {
      activeNames,
      handleItemClick
    });
    const ns = useNamespace('collapse');
    const rootKls = computed(() => ns.b());
    provide(arrowPositionKey, {
      arrow: computed(() => props === null || props === void 0 ? void 0 : props.arrow),
      embedded: computed(() => props === null || props === void 0 ? void 0 : props.embedded)
    });
    return {
      rootKls,
      activeNames
    };
  }
});

function render(_ctx, _cache, $props, $setup, $data, $options) {
  return openBlock(), createElementBlock("div", {
    class: normalizeClass(_ctx.rootKls),
    role: "tablist",
    "aria-multiselectable": "true"
  }, [renderSlot(_ctx.$slots, "default")], 2 /* CLASS */);
}

script.render = render;
script.__file = "components/collapse/collapse.vue";

export { script as default };
