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

import VueMultiselect from '@vueform/multiselect';
import { comparerByKey, groupBy } from '../common/utils.js';
import { getResourceDisplayText } from '../common/zkan-utils.js';
import type { Resource } from '../composables/resourcestore';


export default {
  name: 'InputResourceMultiSelect',
  components: { VueMultiselect },
  props: {
    modelValue: { type: Array as PropType<Resource[]>, required: true },
    options: { type: Array as PropType<Resource[]>, required: true },
  },
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const internalModelValue = computed({
      get: () => props.modelValue.map(x => x.id),
      set: val => emit('update:modelValue', val.map(
        x => props.options.find(r => r.id === x)
      )),
    });
    const internalOptions = computed(() => groupBy(
      props.options, x => x.disabled ? '' : x.type
    ).sort(comparerByKey(x => x.key)).map(x => ({ label: x.key ? {
      classroom: '教室', teacher: '講師', student: '生徒',
    }[x.key] : '無効化', options: x.items.map(x => ({
      value: x.id, label: getResourceDisplayText(x),
    })) })));

    return {
      getResourceDisplayText, internalModelValue, internalOptions,
    };
  },
}
</script>

<template>
<vue-multiselect
  v-model="internalModelValue" :groups="true" :options="internalOptions" mode="tags"
  :hideSelected="true" :searchable="true"
  :closeOnSelect="false" :closeOnDeselect="false"
/>
</template>

<style src="@vueform/multiselect/themes/default.css"></style>
