<template>
  <el-select-v2
    v-model="modelValue"
    :options="options"
    @change="handleChange"
    :placeholder="disabled ? '' : $t('通用.请选择')"
    :disabled="disabled"
    v-bind="$attrs"
  />
</template>

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

interface Props {
  nodeType: any;
  parentId?: string | null;
  modelValue?: string | null;
  disabled?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  nodeType: NODE_TYPE.PROJECT,
  parentId: '',
  modelValue: '',
  disabled: false,
});

const emits = defineEmits(['update:modelValue', 'update:nodeInfo']);

const options = ref<any[]>([]);
const modelValue = ref(props.modelValue);

const fetchOptions = async () => {
  const params: any = { current: 1, size: 999, nodeType: props.nodeType };
  if (props.parentId) {
    params.nodeId = props.parentId;
  }
  if (!params.nodeId) {
    options.value = [];
    return;
  }
  const res: any = await getChildrenNodeListApi(params);
  if (res && res.code === 200) {
    options.value = res.data?.map((item: any) => ({
      label: item.nodeName,
      value: item.uuid,
      info: { ...item },
    }));
  } else {
    options.value = [];
  }
};

const handleChange = (val: any) => {
  emits('update:modelValue', val);
  const info = options.value.find((item) => item.value === val)?.info || {};
  emits('update:nodeInfo', info);
};

watch(
  () => props.modelValue,
  (val) => {
    modelValue.value = val;
  }
);
watch(modelValue, (val) => {
  emits('update:modelValue', val);
});
watch(
  () => [props.nodeType, props.parentId],
  () => {
    fetchOptions();
  },
  { immediate: true }
);

onMounted(() => {
  fetchOptions();
});
</script>
