<script setup>
import { VRadioGroup } from "vuetify/components/VRadioGroup";
import { computed, ref, watch } from "vue";
import { concat } from "lodash-es";
import { useAlert } from "../../composables/alert";
import { useGraphQl } from "../../composables/graphql";
const props = defineProps({
  returnObject: { type: Boolean, required: false },
  groupKey: { type: String, required: true },
  modelValue: { type: null, required: false },
  fields: { type: Array, required: false },
  lang: { type: String, required: false, default: "TH" }
});
const emit = defineEmits(["update:modelValue"]);
const items = ref([]);
const value = ref();
const alert = useAlert();
const query = () => {
  const variables = { groupKey: {
    name: "groupKey",
    type: "String!",
    value: props.groupKey
  } };
  let fields = ["itemCode", "itemValue", "itemValueAlternative"];
  if (props.fields) fields = concat(fields, props.fields);
  useGraphQl().queryPromise("masterItemByGroupKey", fields, variables).then((result) => {
    items.value = result;
  }).catch((error) => {
    alert?.addAlert({
      message: `${error.message}`,
      alertType: "error"
    });
  });
};
watch(
  () => [props.groupKey, props.fields],
  () => {
    query();
  },
  { deep: true, immediate: true }
);
watch(() => props.modelValue, () => {
  value.value = props.modelValue;
}, { deep: true, immediate: true });
const itemTitleField = computed(() => {
  if (props.lang == "TH") return "itemValue";
  else return "itemValueAlternative";
});
</script>

<template>
  <v-radio-group
    v-model="value"
    v-bind="$attrs"
    @update:model-value="emit('update:modelValue', value.value)"
  >
    <template
      v-for="(_, name, index) in $slots"
      :key="index"
      #[name]="slotData"
    >
      <slot
        :name="name"
        v-bind="slotData || {}"
      />
    </template>
    <v-radio
      v-for="i in items"
      :key="i.itemCode"
      v-bind="$attrs"
      :label="i[itemTitleField]"
      :value="returnObject ? i : i.itemCode"
    />
  </v-radio-group>
</template>
