<template>
  <div class="comp-content">
    <el-select-v2
      class="select"
      v-model="choseList"
      :options="listData"
      :placeholder="disabled ? '' : '请选择'"
      filterable
      clearable
      :disabled="disabled"
      :multiple="multiple"
      @change="changeFun"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch } from 'vue';
import { queryNodeListApi } from '@/api/project/node';

interface Props {
  modelValue: string;
  multiple?: boolean;
  disabled?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: '',
  multiple: false,
  disabled: false,
});
const listData = ref<any>([]);
const choseList = ref<any>([]);

const emit = defineEmits(['update:modelValue', 'change']);

watch(() => props.modelValue, (val: any) => {
  if (props.multiple) {
    choseList.value = val ? val.split(',') : [];
  } else {
    choseList.value = val;
  }
}, { deep: true, immediate: true });

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

const getlistDataFun = () => {
  const params = {
    nodeType: 'project',
    current: 1,
    size: 9999,
  };
  queryNodeListApi(params).then((res: any) => {
    if (res.code === 200) {
      const build = res.data.data.map((item: any) => {
        return {
          ...item,
          value: String(item.uuid),
          label: item.nodeName,
        };
      });
      listData.value = build;
    }
  });
};

const changeFun = () => {
  if (props.multiple) {
    const ids = choseList.value.join(',');
    emit('update:modelValue', ids);
    const changeData: any[] = [];
    listData.value.forEach((item: any) => {
      if (choseList.value.includes(String(item.id))) {
        changeData.push(item);
      }
    });
    emit('change', changeData);
  } else {
    emit('update:modelValue', choseList.value);
    let changeData: any = {};
    listData.value.some((item: any) => {
      if (choseList.value === String(item.id)) {
        changeData = item;
        return true;
      }
    });
    emit('change', changeData);
  }
};
</script>

<style lang="scss" scoped>
.comp-content {
  width: 100%;
  .select {
    width: 100%;
  }
}
</style>
