<script setup lang="ts">
import { ref, onMounted, computed, watchEffect, nextTick, watch } 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 isDisabled = ref(false)

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

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 (Number(userStore.level) === 2 &&  (['57','53', '52', '56']).includes(String(itemid))) {
//       deraptNameRef.value = depart_name;
//       // formData.value.depart_id = itemid;
//       // formData.value.exec_type = '2'
//   }
//   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);
  }
});

watch(() => userStore.level, (level) => {
  nextTick(async () => {
    if(Number(level) == 2){
      const { depart_name, itemid } = userStore.info || {};
      await RemoteSelectRef.value?.initalData({ name: depart_name })
      value.value = itemid;
      isDisabled.value = (['57','53', '52', '56']).includes(String(itemid))
      emit('change', itemid)
    } else {
      value.value = ''
      isDisabled.value = false
    }
  })
}, {
  immediate: true
})
</script>

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