<script setup lang="ts">
import { onMounted, ref, watch } from 'vue';

import { useRequest } from '@/hooks/request';
import { getDeviceGroupList } from '@/api';

import type { DeviceGroup } from '@/types';

const emit = defineEmits<{
  change: [id: number];
}>();

const { handleRequest } = useRequest();
const gradeOne = ref<number | undefined>(undefined);
const gradeTwo = ref<number | undefined>(undefined);
const oneDeviceGroup = ref<DeviceGroup[]>([]);
const twoDeviceGroup = ref<DeviceGroup[]>([]);

watch(gradeOne, (id) => {
  if (id) {
    getDeviceGroups(id);
  }
});

watch(gradeTwo, (id) => {
  if (id) {
    emit('change', id);
  }
});

onMounted(() => {
  getDeviceGroups(-1);
});

const getDeviceGroups = (parentId: number) => {
  handleRequest(async () => {
    const data = await getDeviceGroupList({
      parentId,
    });

    if (data.length) {
      if (parentId === -1) {
        oneDeviceGroup.value = data;
        gradeOne.value = data[0].id;
      } else {
        twoDeviceGroup.value = data;
        gradeTwo.value = data[0].id;
      }
    }
  });
};
</script>

<template>
  <div>
    <ASelect
      class="group-select"
      v-model:value="gradeOne"
      :options="oneDeviceGroup"
      :field-names="{ label: 'groupName', value: 'id' }"
      :placeholder="$t('common.plzSelect')"
    />
    <ASelect
      class="group-select"
      v-model:value="gradeTwo"
      :options="twoDeviceGroup"
      :field-names="{ label: 'groupName', value: 'id' }"
      :placeholder="$t('common.plzSelect')"
    />
  </div>
</template>

<style lang="scss" scoped>
.group-select {
  width: 192px;

  & + & {
    margin-left: 16px;
  }
}
</style>
