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

<script setup name="SelectSupplier">
import { onMounted, ref, useAttrs, watch, computed } from 'vue';
import { getAllRoleList } from '@/api/user';

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

const attrs = useAttrs();

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

const search = async () => {
  optionList.value = [];
  const res = await getAllRoleList().catch(() => {});
  if (!res) return;

  optionList.value = res;
  fixRegionManager();
};

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,
  }
);
const fixRegionManager = () => {
  if (
    optionList.value?.length &&
    props.checkDing &&
    props.dingRole === 'REGION_COORDINATOR'
  ) {
    selected.value = isMultiple.value
      ? optionList.value
          .filter((item) => item.type === 'REGION_MANAGER')
          .map((item) => item.id)
      : optionList.value.find((item) => item.type === 'REGION_MANAGER')?.id;
    onChange();
  }
};
watch([() => props.checkDing, () => props.dingRole], () => {
  fixRegionManager();
});
</script>
