<template>
    <div class="ui-group" :class="{ control }">
        <template v-if="!$slots.header">
            <h3 v-if="props.title" class="group-title" :class="!$slots.default && contentStyle">
                {{ props.title }}
                <span class="group-icon" :class="animationRef && { show: animationRef.show }" @click="control && animationRef.changeShow()" v-if="$slots.icon || control">
                    <slot name="icon" v-if="$slots.icon"></slot>
                    <icon type="pull-down" size="12px" v-else />
                </span>
            </h3>
        </template>
        <div v-else class="group-title" :class="!$slots.default && contentStyle">
            <slot name="header"></slot>

            <span class="group-icon" :class="animationRef && { show: animationRef.show }" @click="control && animationRef.changeShow()" v-if="$slots.icon || control">
                <slot name="icon" v-if="$slots.icon"></slot>
                <icon type="pull-down" size="12px" v-else />
            </span>
        </div>

        <template v-if="$slots.default">
            <UISizeAnimation ref="animationRef" class="group-content" :class="contentStyle" v-if="control">
                <slot></slot>
            </UISizeAnimation>
            <div class="group-content" :class="contentStyle" v-else>
                <slot></slot>
            </div>
        </template>
    </div>
</template>

<script setup>
import icon from '../icon'
import UISizeAnimation from '../size-animation'
import { watchEffect, watch, ref, computed, provide } from 'vue'
import { Relation } from './constant'

const animationRef = ref(null)
const props = defineProps({
    title: String,
    border: Boolean,
    borderTop: Boolean,
    borderBottom: Boolean,
    control: Boolean,
    show: Boolean,
})

const contentStyle = computed(() => ({
    'border-bottom': props.borderBottom || props.border,
    'border-top': props.borderTop || props.border,
}))

const contentInstances = ref([])
provide(Relation, contentInstances)

watchEffect(() => {
    if (animationRef.value) {
        animationRef.value.changeShow(props.show)
    }
})

watch(contentInstances, () => {
    animationRef.value && animationRef.value.refer()
})
</script>

<script>
export default { name: 'UiGroup' }
</script>
