<template>
  <div class="comp-content">
    <el-select-v2
      class="select"
      v-model="choseList"
      :options="listData"
      :placeholder="disabled ? '' : '请选择项目'"
      filterable
      clearable
      :disabled="disabled"
      :multiple="multiple"
      :collapse-tags="multiple"
      :fit-input-width="fitInputWidth"
      @change="changeFun"
      @clear="clearFun"
    />
  </div>
</template>

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

interface Props {
  modelValue: string;
  multiple?: boolean;
  disabled?: boolean;
  fitInputWidth?: boolean;
  resStr?: string; // 下拉选择绑定的字段 默认是用uuid
  showCodeList?: boolean; // 下拉选择展示的是否是项目编号， 默认展示项目名称
}

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

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

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[props.resStr]),
          label: props.showCodeList ? item.nodeCode : item.nodeName,
        };
      });
      listData.value = build;
    }
  });
};
const multiplyChangeFun = debounce(() => {
  const ids = choseList.value.join(',');
  emit('update:modelValue', ids);
  const changeData: any[] = [];
  listData.value.forEach((item: any) => {
    if (choseList.value.includes(String(item[props.resStr]))) {
      changeData.push(item);
    }
  });
  emit('change', changeData);
}, 500);

const changeFun = () => {
  if (props.multiple) {
    multiplyChangeFun();
  } else {
    emit('update:modelValue', choseList.value);
    let changeData: any = {};
    listData.value.some((item: any) => {
      if (choseList.value === String(item[props.resStr])) {
        changeData = item;
        return true;
      }
    });
    emit('change', changeData);
  }
};

const clearFun = () => {
  emit('clear');
};
</script>

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