<script setup lang="ts">
import { IActionParam, IContext, IParam } from '@core';
import { Ref, onBeforeMount } from 'vue';

interface QuickGroupProps {
  quickGroupModel: IParam;
  context: IContext;
  viewParams: IParam;
}
interface FormGroupEmit {
  (name: 'onQuickGroupEvent', value: IActionParam): void;
}
const props = withDefaults(defineProps<QuickGroupProps>(), {});
const emit = defineEmits<FormGroupEmit>();
const selectItem: Ref<IParam> = ref({});
const items: Ref<any> = ref([]);
const handleClick = ($event: any) => {
  if ((selectItem.value && selectItem.value.id && selectItem.value.id === $event.id) || $event.children) {
    return;
  }
  selectItem.value = $event;
  emit('onQuickGroupEvent', {
    tag: 'quickGroup',
    action: 'valueChange',
    data: $event,
  });
};

//  代码表服务
const codeListService = App.getCodeListService();

onBeforeMount(() => {
  if (codeListService) {
    codeListService
      .getCodeListItems({
        tag: props.quickGroupModel.codeListTag,
        context: props.context,
        viewParams: props.viewParams,
      })
      .then((codeListItems: any[]) => {
        items.value = codeListItems;
        //  默认选中第一项
        if (codeListItems.length) {
          emit('onQuickGroupEvent', {
            tag: 'quickGroup',
            action: 'initSuccess',
            data: items.value[0],
          });
        }
      })
      .catch((error: any) => {
        emit('onQuickGroupEvent', {
          tag: 'quickGroup',
          action: 'initError',
          data: null,
        });
      });
  }
});
</script>

<template>
  <a-space class="app-quick-group" :size="0">
    <a-button
      class="quick-group-item"
      v-for="(item, index) in items"
      :key="index"
      type="text"
      @click="handleClick(item)"
    >
      <span :style="{ color: item.color }">
        <AppIconText v-if="!item.children" :text="item.text" :iconClass="item.iconClass" :imgPath="item.imgPath" />
        <a-dropdown v-else>
          <AppIconText :text="item.text" :iconClass="item.iconClass" :imgPath="item.imgPath" />
          <template #overlay>
            <a-menu>
              <a-menu-item v-for="(childItem, index) in item.children" :key="index">
                <AppIconText :text="childItem.text" :iconClass="childItem.iconClass" :imgPath="childItem.imgPath" />
              </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
      </span>
    </a-button>
  </a-space>
</template>
