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

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

const props = defineProps({
    disabled:Boolean,
    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) {
						console.log(val,'kkkkkkkkkkkkkkk')
						await relationRef.value.getInfoByIds(val);
						relationRef.value.confirm();
					}
				}, 0);
			}
		},
    {
      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>