<template>
  <Space v-bind="attrs">
    <template v-for="(item, i) in groups" :key="`fmgrp${i}`">
      <AButton :class="{ 'form-group-actived': value === item }" @click="handleClick(item)">
        {{ item }}
      </AButton>
    </template>
    <!-- 占位符，避免没有组别时没有内容导致父组件的Flex布局受影响 -->
    <span></span>
  </Space>
</template>
<script lang="ts">
  import { defineComponent, PropType, watch } from 'vue';
  import { Space, Button } from 'ant-design-vue';
  import { useAttrs } from '/@/hooks/core/useAttrs';
  import { first } from 'lodash';

  export default defineComponent({
    name: 'FormGroup',
    components: {
      Space,
      AButton: Button,
    },
    props: {
      value: {
        type: String,
      },
      groups: {
        type: Array as PropType<string[]>,
        default: () => [],
      },
    },
    emits: ['update:value', 'change'],
    setup(props, { emit }) {
      const attrs = useAttrs();

      function handleClick(value?: string) {
        if (props.value === value) {
          emit('update:value', undefined);
          emit('change', undefined);
        } else {
          emit('update:value', value);
          emit('change', value);
        }
      }

      watch(
        () => props.groups,
        (nv) => {
          !props.value && handleClick(first(nv));
        },
        {
          immediate: true,
        }
      );

      return { attrs, handleClick };
    },
  });
</script>
<style lang="less" scoped>
  .form-group-actived {
    color: @white;
    background: @gradient-primary-color;
  }
  .form-group-actived:hover {
    color: @white;
  }
</style>
