import { type Dictionaries, type DictionaryKeys } from '@/request/api/dictionary.api';
import { tryOnBeforeUnmount }                     from '@vueuse/core';

import type { ComputedRef, MaybeRefOrGetter } from 'vue';


export function dictionary(
  dictionaries: MaybeRefOrGetter<Dictionaries> | ComputedRef<Dictionaries>,
  key: DictionaryKeys,
  value?: string,
  filter?: (value: string) => boolean,
) {
  const options = unref(toRef(dictionaries))?.[ key ] ?? [];
  value ??= '';
  const _filter = (item?: string) => !!item && (
    filter?.(item) ?? true
  );
  return value
    .toString()
    .split(',')
    .map(value => value.trim().split(':'))
    .map(([ key, label ]) => label ?? options.find(item => item.value === key.trim())?.label)
    .filter(_filter);
}

export function useDictionary(
  dictionaries: MaybeRefOrGetter<Dictionaries> | ComputedRef<Dictionaries>,
  key: DictionaryKeys,
  value?: MaybeRefOrGetter<any> | ComputedRef<any>,
  filter?: (value: string) => boolean,
) {
  const values = shallowRef<string[]>([]);
  const stop = watchEffect(() => {
    values.value = dictionary(dictionaries, key, value.value, filter ?? (
      (v: string) => v !== '无'
    ));
  });
  tryOnBeforeUnmount(() => stop());
  return values;
}



