<template>
  <a-select
    placeholder="请选择项目"
    allowClear
    :disabled="disabled"
    style="width: 140px"
    :mode="isMultiple ? 'multiple' : undefined"
    :value="value"
    @change="handleChange"
  >
    <a-select-option
      v-for="(item, index) in optionList"
      :key="index"
      :value="item.id"
    >
      {{ item.name }}
    </a-select-option>
  </a-select>
</template>

<script setup lang="ts">
import { getProjectList } from "@/api/projectManagementPage";
import { onMounted, onUpdated } from "vue";

// eslint-disable-next-line vue/no-setup-props-destructure
const {
  value = null,
  rootOrgId = -1,
  disabled = false,
} = defineProps<{
  value?: number | number[];
  rootOrgId: number;
  disabled?: boolean;
}>();
const emit = defineEmits(["update:value"]);

let optionList = $ref<{ id: number; name: string }[]>([]);

async function fetchData() {
  if (!rootOrgId) return;
  const res = await getProjectList({
    // id: props.projectId,
    rootOrgId: rootOrgId,
    pageNo: 1,
    pageSize: 100,
  });
  optionList = res.data.content;
}
onMounted(fetchData);
onUpdated(fetchData);

const isMultiple = $computed(() => Array.isArray(value));

// const valueStr = computed(() => {
//   let res: undefined | number | string = props.value ?? undefined;
//   // if (typeof res === "number") res = props.value + "";
//   return res as undefined | string;
// });

function handleChange(v: string) {
  // console.log(v, v.length, value);
  // 最多只有2项
  emit("update:value", isMultiple ? v.slice(0, 2) : v);
}
</script>
