<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { getRole } from 'src/services/keycloak';

import { createSelect, SelectProps } from './select';
import SelectInput from '../SelectInput.vue';

import { Branch } from 'src/stores/branch/types';

import useStore from 'src/stores/branch';

type SelectOption = Branch;

const value = defineModel<string | null | undefined>('value', {
  required: true,
});
const valueOption = defineModel<SelectOption>('valueOption', {
  required: false,
});

const selectOptions = ref<SelectOption[]>([]);

const { fetchList: getList, fetchById: getById } = useStore();

defineEmits<{
  (e: 'create'): void;
}>();

type ExclusiveProps = {
  codeOnly?: boolean;
  selectFirstValue?: boolean;
  branchVirtual?: boolean;
  checkRole?: string[];
};

const props = defineProps<SelectProps<typeof getList> & ExclusiveProps>();

const { getOptions, setFirstValue, getSelectedOption, filter } =
  createSelect<SelectOption>(
    {
      value,
      valueOption,
      selectOptions,
      getList: async (query) => {
        const ret = await getList({
          query,
          ...props.params,
          activeOnly: true,
        });
        if (ret) return ret.result;
      },
      getByValue: async (id) => {
        const ret = await getById(id);
        if (ret) return ret;
      },
    },
    { valueField: 'id' },
  );

onMounted(async () => {
  await getOptions();

  if (props.autoSelectOnSingle && selectOptions.value.length === 1) {
    setFirstValue();
  }

  if (props.selectFirstValue) {
    setDefaultValue();
  } else await getSelectedOption();
});

function setDefaultValue() {
  setFirstValue();
}
</script>
<template>
  <SelectInput
    v-model="value"
    incremental
    id="select-hq-id"
    :label
    :placeholder
    :readonly
    :disable="disabled"
    :option="
      selectOptions.map((v) => {
        const ret = {
          label: codeOnly
            ? v.code
            : `${branchVirtual ? $t('branch.card.branchVirtual') : ''}` +
              (
                {
                  ['eng']: [v.nameEN, `(${v.code})`].join(' '),
                  ['tha']: [v.name, `(${v.code})`].join(' '),
                } as const
              )[$i18n.locale],
          value: v.id,
        };
        return ret;
      })
    "
    hide-selected
    fill-input
    :rules="[
      (v: string) => !props.required || !!v || $t('form.error.required'),
    ]"
    @filter="filter"
  >
    <template #append v-if="clearable">
      <q-icon
        v-if="!readonly && value"
        name="mdi-close-circle"
        @click.stop="value = ''"
        class="cursor-pointer clear-btn"
      />
    </template>
  </SelectInput>
</template>
