<template>
  <div class="sel-wrap-container" ref="box">
    <div class="container" ref="container">
      <slot></slot>
    </div>
    <template v-if="shouldShowMore">
      <div class="more" v-if="more" @click="showMore">更多</div>
      <div class="more" v-else @click="closeMore">收起</div>
    </template>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, getCurrentInstance, useSlots } from 'vue'

const more = ref(true)
const props = defineProps({
  mode: {
    type: String,
    default: 'tag',
  },
  gap: {
    type: String,
    default: 50,
  },
  fontSize: {
    type: Number,
    default: 14
  }
})

function showMore () {
  more.value = false
}

function closeMore () {
  more.value = true
}

const instance: any = getCurrentInstance()

const height = computed(() => {
  return more.value ? '32px' : 'unset'
})
const slots = useSlots()
const box = ref()
const container = ref()
const shouldShowMore = ref(false)
onMounted(() => {
  initWidth()
})

function initWidth () {
  const width = box.value.clientWidth
  const text = container.value.innerText.replaceAll('\n', '')
  const textLength = text.length
  if (props.mode === 'tag') {
    const childNumber = slots.default()[0].children?.length
    shouldShowMore.value = width < ((childNumber - 1) * props.gap + textLength * props.fontSize)
  } else {
    const childNumber = slots.default()[0].props.options?.length
    shouldShowMore.value = width < ((childNumber - 1) * props.gap + textLength * props.fontSize)
  }
}
</script>

<style lang="scss">
.sel-wrap-container {
  height: v-bind(height);
  overflow: hidden;
  display: flex;
  justify-content: space-between;
  line-height: 32px;
  width: 100%;

  .container {
    flex: 1;
    display: flex;
    flex-wrap: wrap;
  }

  .more {
    font-size: 14px;
    cursor: pointer;
  }
}
</style>
