<script>
import { defineComponent, h, onMounted } from "vue";

export default defineComponent({
  name: "ButtonGroup",
  props: {
    defaultValue: {
      type: Number,
      default: 0,
    },
  },
  components: {},
  emits: ["change"],
  setup(props, ctx) {
    const children = ctx.slots
      .default()
      .filter((item) => item.componentOptions?.tag === "button-group-item");

    function setCheckedState(setIndex) {
      children.forEach((node, index) => {
        if (setIndex !== index) {
          node.componentInstance.uncheck();
        } else {
          node.componentInstance.check();
        }
      });
    }

    children.forEach((node, index) => {
      const listeners = node.componentOptions.listeners || {};
      listeners["click"] = function clickItem() {
        setCheckedState(index);
        ctx.emit("change", index);
      };
      node.componentOptions.listeners = listeners;
    });

    onMounted(() => {
      setCheckedState(props.defaultValue);
    });

    return () =>
      h(
        "div",
        {
          class: "button-group",
        },
        children
      );
  },
});
</script>

<style scoped lang="less">
.button-group {
  display: flex;
}
</style>
