<template>
  <t-select
    v-model="selected"
    filterable
    clearable
    v-bind="attrs"
    @change="onChange"
  >
    <t-option
      v-for="item in optionList"
      :key="item.userId"
      :value="item.userId"
      :label="`${item.name}_${item.supplierName || ''}_${item.city || ''}`"
    />
  </t-select>
</template>

<script setup name="SelectFreeEngineer">
import { onMounted, ref, useAttrs, watch, computed } from 'vue';
import {
  personAllocateFreeCoordinatorApi,
  personAllocateFreeEngineerApi,
} from '@/api/resource-guard';

let optionList = ref([]);
let selected = ref('');

const attrs = useAttrs();

const emit = defineEmits(['update:modelValue', 'change']);
const props = defineProps({
  modelValue: { type: [Number, String, Array], default: '' },
  type: { type: String, default: '' },
  unitId: { type: String, default: '' },
  crmNo: { type: String, default: '' },
});
const isMultiple = computed(() => {
  const multiple = attrs.multiple;
  return multiple === '' || multiple;
});

const search = async () => {
  if (!props.type) return;
  optionList.value = [];

  let res = null;
  if (props.type === 'REGION_COORDINATOR') {
    res = await personAllocateFreeCoordinatorApi(
      props.unitId,
      props.crmNo
    ).catch(() => {});
    if (!res) return;
  } else {
    res = await personAllocateFreeEngineerApi(props.type, props.crmNo).catch(
      () => {}
    );
    if (!res) return;
  }

  optionList.value = res;
};

const onChange = () => {
  const selectedData = isMultiple.value
    ? optionList.value.filter(
        (item) => selected.value && selected.value.includes(item.userId)
      )
    : optionList.value.filter((item) => selected.value === item.userId);
  emit('update:modelValue', selected.value);
  emit('change', isMultiple.value ? selectedData : selectedData[0]);
};

onMounted(() => {
  search();
});

watch(
  () => props.modelValue,
  (val) => {
    selected.value = val;
  },
  {
    immediate: true,
  }
);
watch(
  () => props.type,
  (val, oldval) => {
    if (val !== oldval) {
      search();
      emit('update:modelValue', null);
      emit('change', isMultiple.value ? [] : null);
    }
  }
);
</script>
