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

import { useAccessStore } from '@vben/stores';

import {
  SYS_ORIGIN_OPTIONS,
  getDisplayableSysOrigins,
} from '#/views/system/shared';

defineOptions({
  inheritAttrs: false,
  name: 'SysOriginSelect',
});

type SelectValue = null | number | string | Array<number | string> | undefined;
type SelectOptionValue = number | string;
type AppOriginOption = Record<string, any> & {
  icon?: string;
  label?: string;
  name?: string;
  value?: SelectOptionValue;
};

const props = defineProps<{
  options?: AppOriginOption[];
  value?: SelectValue;
}>();

const emit = defineEmits<{
  (event: 'change', value: SelectValue, option: any): void;
  (event: 'update:value', value: SelectValue): void;
}>();

const accessStore = useAccessStore();

const fallbackOptions = computed(() => {
  const options = getDisplayableSysOrigins(accessStore.accessCodes || []);
  return (options.length > 0 ? options : SYS_ORIGIN_OPTIONS) as AppOriginOption[];
});

const rawOptions = computed(() =>
  props.options?.length ? props.options : fallbackOptions.value,
);

const hiddenDefaultValue = computed(() =>
  String(rawOptions.value[0]?.value ?? SYS_ORIGIN_OPTIONS[0]?.value ?? 'LIKEI'),
);

watch(
  () => [props.value, hiddenDefaultValue.value] as const,
  ([value, defaultValue]) => {
    if (Array.isArray(value) || value !== undefined && value !== null && value !== '') {
      return;
    }
    if (!defaultValue) {
      return;
    }
    emit('update:value', defaultValue);
    emit('change', defaultValue, rawOptions.value[0] || null);
  },
  { immediate: true },
);
</script>

<template>
  <span class="sys-origin-select--hidden" aria-hidden="true" />
</template>

<style scoped>
.sys-origin-select--hidden {
  display: none !important;
}
</style>
