<script setup lang="ts">
import { ref, onMounted, computed, watchEffect, nextTick } from "vue";
import { useUserStoreHook } from "/@/store/modules/user";
import RemoteSelect from "/@/components/RemoteSelect";
import { httpDepart } from "/@/api/user";
import { useVModel } from "@vueuse/core";

const userStore = useUserStoreHook();

const isReadonly = computed(() => Number(userStore.level) === 2);

const props = defineProps<{
  modelValue?: string;
  disabled?: boolean;
}>();

const emit = defineEmits(["change"]);

const value = useVModel(props, "modelValue");

const RemoteSelectRef = ref<InstanceType<typeof RemoteSelect> | null>(null);

onMounted(() => {
  value.value && (RemoteSelectRef.value as any).initalData(value.value);
});

watchEffect(() => {
  if (!isReadonly.value) return;
  const { depart_name } = userStore.info || {};
  nextTick(() => RemoteSelectRef.value.initalData({ name: depart_name }));
});

function handleChange() {
  emit("change");
}

function handleInital(val) {
  value.value = val;
}

defineExpose({
  initalData: data => {
    (RemoteSelectRef.value as any).initalData(data);
  }
});
</script>

<template>
  <RemoteSelect
    ref="RemoteSelectRef"
    :disabled="disabled"
    :is-root="true"
    v-model="value"
    style="width: 100%"
    :api="httpDepart"
    request-prop="name"
    response-label-prop="name"
    response-val-prop="id"
    @change="handleChange"
    @inital="handleInital"
  />
</template>
