<template>
  <a-select
    v-model="selected"
    :placeholder="placeholder"
    :allow-clear="clearable"
    :disabled="disabled"
    :options="optionList"
    filter-option
    v-bind="attrs"
    @change="onChange"
  >
    <template v-if="prefix" #prefix>考点</template>
  </a-select>
</template>

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

  defineOptions({
    name: 'SelectAgent',
  });
  type ValueType = number | Array<number>;

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

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

  const selected = ref<ValueType>();
  const optionList = ref<OptionListItem[]>([]);
  const search = async () => {
    optionList.value = [];
    if (!props.teachingId) return;

    const resData = await agentQuery(props.teachingId);

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

  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);
    emit('change', props.multiple ? selectedData : selectedData[0]);
  };

  watch(
    () => props.modelValue,
    (val) => {
      selected.value = val;
    },
    {
      immediate: true,
    }
  );
  watch(
    () => props.teachingId,
    () => {
      emit('update:modelValue', '');
      emit('change', null);
      search();
    },
    {
      immediate: true,
    }
  );
</script>
