<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> -->
  <t-select
    v-model="selected"
    filterable
    clearable
    v-bind="attrs"
    @change="onChange"
  >
    <t-option v-if="hasNoneValue" value="-1" label="未绑定服务单元">
      <span class="red">未绑定服务单元</span>
    </t-option>
    <t-option
      v-for="item in optionList"
      :key="item.id"
      :value="item.id"
      :label="item.name"
    >
      {{ item.name }}
    </t-option>
  </t-select>
</template>

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

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

const attrs = useAttrs();

const emit = defineEmits(['update:modelValue', 'change', 'default-selected']);
const props = defineProps({
  modelValue: { type: [Number, String, Array], default: '' },
  defaultSelect: { type: Boolean, default: false },
  filterParams: {
    type: Object,
    default() {
      // type:'',statusList:''
      return { statusList: ['PUBLISH'] };
    },
  },
  hasNoneValue: { type: Boolean, default: false },
});

const isMultiple = computed(() => {
  const multiple = attrs.multiple;
  return multiple === '' || multiple;
});

const search = async () => {
  optionList.value = [];

  let data = { ...props.filterParams };
  const res = await serviceUnitListApi(data).catch(() => {});
  if (!res) return;

  optionList.value = res;

  if (props.defaultSelect && !props.modelValue) selectDefault();
};

const selectDefault = () => {
  const defaultOption = optionList.value[0];
  if (defaultOption) {
    selected.value = isMultiple.value ? [defaultOption.id] : defaultOption.id;
    onChange();
    emit('default-selected', defaultOption);
  }
};

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.filterParams,
  (val, oldval) => {
    if (JSON.stringify(val) !== JSON.stringify(oldval)) {
      search();
      emit('update:modelValue', null);
      emit('change', isMultiple.value ? [] : null);
    }
  },
  {
    deep: true,
  }
);
</script>
