<template>
  <view>
		<uni-easyinput :placeholder="placeholder" :disabled="disabled" :prefixIcon="prefixIcon" :suffixIcon="suffixIcon" v-model="users"
    @focus="open" @clear="handleClear"/>
		<uni-user-popup ref="relationRef" :multiple="multiple" :selectedIds="selectedIds" @change="handleChange" @close="handleClose"/>
	</view>
</template>

<script setup>
  import {
    ref,
    watch,
    // nextTick
  } from 'vue';

const props = defineProps({
    disabled:Boolean,
		multiple: {
		  type: Boolean,
		  default: true,
		},
    placeholder: String,
    prefixIcon: String,
    suffixIcon: String,
    modelValue: {
      type: String,
      default: ''
    },
  })

  const emits = defineEmits(['update:modelValue','change','click']);
  const selectedIds = ref('')
  const relationRef = ref();
  const users = ref('');
  const isOpen = ref(false)
 
  watch(
    () => props.modelValue,
    (val) => { 
      if (!props.modelValue) users.value = ''; 
      if (!isOpen.value) {
      selectedIds.value = val
      setTimeout(async() => {
        if (relationRef.value) {
            await relationRef.value.getInfoByIds(val);
            relationRef.value.confirm();
          }
      }, 0);
        // nextTick(async () => {
        //   if (relationRef.value) {
        //     await relationRef.value.getInfoByIds(val);
        //     relationRef.value.confirm();
        //   }
        // })
      }
    },
    {
      immediate:true
    }
  )
  

  function open() {
    isOpen.value = true
    relationRef.value.open();
		emits('click');
  }

  function handleClear() {
    emits('update:modelValue', '');
		emits('change', ''); 
  }

  function handleChange(selectedList) {
    const name = selectedList.map(item => item.name)
    users.value = name.toString()
    const userIds = selectedList.map(item => item.id)
    emits('update:modelValue', userIds.toString());
		emits('change', userIds.toString());
		isOpen.value = false
  }
	
	function handleClose(){
		isOpen.value = false
	}
</script>