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

<script setup name="SelectProduct">
import { onMounted, ref, useAttrs, watch, computed } from 'vue';
import { productListApi } from '@/api/service-unit';

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

const attrs = useAttrs();

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

const search = async () => {
  optionList.value = [];
  let data = { enable: true };
  // if (props.productType) {
  //   data.productType = props.productType;
  // }
  const res = await productListApi(data).catch(() => {});
  if (!res) return;

  optionList.value = res;
};

const onChange = () => {
  const selectedData = isMultiple.value
    ? optionList.value.filter(
        (item) => selected.value && selected.value.includes(item.id)
      )
    : optionList.value.filter((item) => selected.value === item.id);
  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.productType,
//   (val) => {
//     selected.value = '';
//     search();
//   }
// );
</script>
