<script setup lang="ts">
import { Person } from '/@src/utils/types'

const props = defineProps({
  label: {
    type: String,
    default: '직원검색',
  },
  placeholder: {
    type: String,
  },
  disabled: {
    type: Boolean,
  },
})

const emits = defineEmits(['appendUser'])

const vSelect = ref()
const model = ref<Person>()
const tagsOptions = ref([])

const onKeyup = (e: any) => {
  const regex_jaeum = /[ㄱ-ㅎ]/g
  if (e.key === 'Process') {
    if (e.target.value.match(regex_jaeum) === null) {
      api.findUser(e.target.value).then((res: Person[]) => {
        if (res.length > 0) {
          // res.map(u => {
          //   if (model.value?.length > 0) {
          //     const ignore = model.value?.reduce((a: Person, b: Person) => {
          //       return a.sabun + '|'  + b.sabun
          //     })
          //
          //     if (typeof ignore !== 'object') {
          //       if (ignore.includes(u.value.sabun)) {
          //         u['disabled'] = true
          //       }
          //     } else {
          //       if (ignore.sabun.includes(u.value.sabun)) {
          //         u['disabled'] = true
          //       }
          //     }
          //   }
          // })
          tagsOptions.value = res
        }
      })
    }
  }
  if (e.target.value === '') {
    tagsOptions.value = []
  }
}

watch(model, (user) => {
  console.log(user)
  if (user === null || Object.keys(user).length === 0) return
  emits('appendUser', user)
  model.value = {}
  vSelect.value.clear()
})

</script>

<template>
  <VField v-slot="{ id }" class="pr-2 is-autocomplete-select">
    <VLabel class="has-fullwidth">
      {{props.label}}
    </VLabel>
    <VControl icon="lucide:search">
      <Multiselect
        v-model="model"
        ref="vSelect"
        :attrs="{ id }"
        :searchable="true"
        :disabled="props.disabled"
        :options="tagsOptions"
        noResultsText="조회된 결과가 없습니다."
        noOptionsText="검색된 결과가 없습니다."
        :placeholder="props.placeholder"
        @keyup="onKeyup"
      >
        <template #multiplelabel="{ values }">
          <div class="multiselect-multiple-label pl-6">
            {{props.placeholder}}
          </div>
        </template>
      </Multiselect>
    </VControl>
  </VField>
</template>

<style scoped lang="scss">
.field {
  padding-bottom: 10px !important;
  .label {
    font-size: 1.3em;
    color: var(--modal-text) !important;
  }
}
</style>