<template>
  <a-select
    v-model="selected"
    :placeholder="placeholder"
    :allow-clear="clearable"
    :disabled="disabled"
    :options="optionList"
    allow-search
    popup-container="body"
    v-bind="attrs"
    @change="onChange"
  >
    <template v-if="prefix || prefixStr" #prefix>{{
      prefixStr || '教学点'
    }}</template>
  </a-select>
</template>

<script setup lang="ts">
  import { ref, useAttrs, watch } from 'vue';
  import { teachingQuery } from '@/api/order';

  defineOptions({
    name: 'SelectTeaching',
  });

  type ValueType = number | Array<number> | null;

  const props = defineProps<{
    modelValue: ValueType;
    clearable?: boolean;
    disabled?: boolean;
    placeholder?: string;
    multiple?: boolean;
    prefix?: boolean;
    prefixStr?: string;
    flag?: boolean;
  }>();
  const emit = defineEmits(['update:modelValue', 'change', 'getOptions']);
  const attrs = useAttrs();

  interface OptionListItem {
    value: number;
    label: string;
  }

  const selected = ref<number | Array<number> | undefined>();
  const optionList = ref<OptionListItem[]>([]);
  const search = async () => {
    optionList.value = [];
    const datas = { flag: props.flag ? props.flag : undefined };

    const resData = await teachingQuery(datas);
    emit('getOptions', resData);

    optionList.value = (resData || []).map((item) => {
      return { ...item, value: item.id, label: item.name };
    });
  };
  search();

  const onChange = () => {
    const selectedData = props.multiple
      ? optionList.value.filter(
          (item) =>
            selected.value && (selected.value as number[]).includes(item.value)
        )
      : optionList.value.filter((item) => selected.value === item.value);
    emit('update:modelValue', selected.value || null);
    emit('change', props.multiple ? selectedData : selectedData[0]);
  };

  watch(
    () => props.modelValue,
    (val) => {
      selected.value = val || undefined;
    },
    {
      immediate: true,
    }
  );
</script>
