<template>
  <a-select
    placeholder="请选择角色"
    allowClear
    :value="valueStr"
    style="width: 140px"
    @change="handleChange"
  >
    <a-select-option
      v-for="(item, index) in optionList"
      :key="index"
      :value="item.code"
    >
      {{ item.name }}
    </a-select-option>
  </a-select>
</template>

<script setup lang="ts">
import { getRoleList } from "@/api/roleManagementPage";
import { ROLE_MANAGE_SET } from "@/constants/constants";
import { useMainStore } from "@/store";
import { onMounted, computed, watch } from "vue";
import { RoleOption } from "@/types";

const props = withDefaults(
  defineProps<{
    value?: null | string;
    rootOrgId?: null | number;
    isManage?: boolean;
  }>(),
  {
    value: null,
    rootOrgId: null,
    isManage: false,
  }
);
const emit = defineEmits<{
  (e: "update:value", code: string): void;
  (e: "change", role: RoleOption | null): void;
}>();

let optionList = $ref<RoleOption[]>([]);

onMounted(async () => {
  await fetchData();
});

watch(() => [props.rootOrgId], fetchData);

const store = useMainStore();
async function fetchData() {
  if (typeof props.rootOrgId !== "number") return;

  const res = await getRoleList(props.rootOrgId);
  optionList = res.data;

  if (props.isManage) {
    const info = ROLE_MANAGE_SET[store.userInfo.role];
    let userRoleSet = [...info];
    optionList = optionList.filter((item: RoleOption) =>
      userRoleSet.includes(item.code)
    );
  }
}
const valueStr = computed(() => {
  let res: undefined | string = props.value ?? undefined;
  // if (typeof res === "number") res = props.value;
  return res;
});

function handleChange(v: string) {
  // console.log(typeof v);
  emit("update:value", v);
  const role = optionList.find((item) => item.code === v);
  emit("change", role || null);
}
</script>
