<template>
  <t-select v-model="selected" filterable v-bind="attrs" @change="onChange">
    <t-option
      v-for="item in optionList.value"
      :key="item.id"
      :value="item.id"
      :label="item.level"
    />
  </t-select>
</template>

<script setup name="SelectServiceLevel">
import { onMounted, reactive, ref, useAttrs, watch } from 'vue';
import { serviceLevelListApi } from '@/api/system';

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

const attrs = useAttrs();

const emit = defineEmits(['update:modelValue', 'change']);
const props = defineProps({
  modelValue: { type: [Number, String], default: '' },
  type: { type: String, default: '' },
  typeRequired: { type: Boolean, default: false },
});

const search = async () => {
  if (props.typeRequired && !props.type) return;

  optionList.value = [];
  let data = { enable: true };
  if (props.type) data.type = props.type;
  const res = await serviceLevelListApi(data).catch(() => {});
  if (!res) return;

  optionList.value = res;
};

const onChange = () => {
  emit('update:modelValue', selected.value);
  emit('change', selected.value);
};

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

watch(
  () => props.modelValue,
  (val) => {
    selected.value = val;
  }
);
watch(
  () => props.type,
  (val, oldval) => {
    if (val !== oldval) search();
  }
);
</script>
