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

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

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

<script setup>
import { computed, provide, ref, watch, watchEffect } from 'vue'
import icon from '../icon'
import UISizeAnimation from '../size-animation'
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>
