<template>
  <transition name="fade">
    <div 
      class="control-panl pc" 
      :class="{ full, 'strengthen-right': full }" 
      :ref="(dom: any) => exposeConfig.dom = dom" 
      v-if="!hide"
    >
      <div class="control-layer">
        <div class="scroll-view">
          <div c
            lass="panl" 
            v-for="(groupItem, i) in group" 
            :class="{ apart: groupItem.apart }"
          >
            <p v-if="groupItem.label">{{ groupItem.label }}</p>
            <VCtrl 
              v-for="ctrl in groupItem.items" 
              :activeCtrls="modelValue" 
              :ctrl="ctrl"
              :key="ctrl.key"
              @click="ctrl => clickHandler(ctrl)" 
            />
          </div>
        </div>
      </div>
    </div>
  </transition>
</template>

<script lang="ts" setup>
import { ref, watchEffect, watch, reactive, toRaw } from 'vue'
import VCtrl from './ctrl.vue'
import { useActive } from '@/hook'

import type { Groups, Items, Item, ControlExpose } from './index'

const props =  withDefaults(
  defineProps<{
    group: Groups
    show?: boolean
    modelValue: Items
    full?: boolean
  }>(),
  {
    show: true,
    full: false
  }
)

const active = useActive()
const hide = ref(true)
watch(
  () => [active, props.show], 
  () => {
    if (active.value) {
      hide.value = active.value
    }
    setTimeout(() => hide.value = !props.show)
  }, 
  { immediate: true }
)

const emit = defineEmits<{
  (e: 'update:modelValue', items: Item[], oldItems: Item[]): void
  (e: 'select', item: Item): void
}>()

const clickHandler = (ctrl: Item) => {
  if (ctrl.inClick) {
    return emit('select', ctrl)
  }

  const newRuns = reactive([...props.modelValue])
  const index = newRuns.indexOf(reactive(ctrl))
  if (~index) {
    newRuns.splice(index, 1)
  } else if (ctrl.makeup) {
    newRuns.push(ctrl)
  } else {
    const makeupRuns = newRuns.filter(item => item.makeup)
    newRuns.length = 0
    newRuns.push(...makeupRuns, ctrl)
  }
  emit('update:modelValue', newRuns, props.modelValue)
}

watchEffect(() => {
  if (!props.show) {
    const items: Item[] = []
    for (const { items } of props.group) {
      items.push(...items.filter(item => item.def))
    }
    emit('update:modelValue', items, props.modelValue)
  }
})

 
const exposeConfig = reactive<ControlExpose>({ dom: null })
defineExpose(exposeConfig)
</script>

<style lang="sass" scoped>
@import './style.scss'
</style>
