<template>
  <UItext
    :disabled="props.disabled"
    class="select" 
    :class="{ready, focus: showOptions}" 
    ref="vmRef"
    v-model="inputValue"
    :width="props.width"
    :height="props.height"
    readonly
    :placeholder="props.placeholder"
    @blur="blurHandler"
    @click="changShow(!showOptions)">
    <template v-slot:icon>
      <icon type="pull-down" small />
    </template>
  </UItext>

  <UIFloating :mount="mountEl" :refer="vmRef && vmRef.root">
    <ul 
      class="select-replace"
      :class="{ ready }"
      :style="originHeight && {'max-height': maxHeight + 'px'}"
      ref="contentRef">
      <li 
        v-for="option in props.options" 
        :key="option.value"
        :class="{active: props.modelValue === option.value}"
        @click="optionClickHandler(option)">
        {{option.label}}
      </li>
    </ul>
  </UIFloating>
</template>

<script setup>
import UItext from './text.vue'
import UIFloating from '../floating/index.vue'
import { ref, onUnmounted, computed } from 'vue'
import { selectPropsDesc } from './state'
import icon from '../icon'
import { changeWHFactory } from '../../utils'

const props = defineProps(selectPropsDesc)
const emit = defineEmits(['update:modelValue'])
const vmRef = ref(null)
const mountEl = document.body

const inputValue = computed(() => {
  const selectOption = props.options.find(
    ({value}) => value === props.modelValue
  )
  return selectOption ? selectOption.label : ''
})

const [ 
  contentRef, 
  changShow, 
  maxHeight,
  originHeight,
  showOptions,
  ready
] = changeWHFactory()


const optionClickHandler = (option) => {
  emit('update:modelValue', option.value)
  vmRef.value.input.focus()
  changShow(false)
}

let timeout
const blurHandler = () => 
  timeout = setTimeout(() => changShow(false), 500)

const attach = document.documentElement
const htmlClickHandler = ev => {
  if (vmRef.value.root.contains(ev.target)) {
    clearTimeout(blurHandler)    
  } else {
    changShow(false)
  }
}

attach.addEventListener('click', htmlClickHandler)
onUnmounted(() => {
  attach.removeEventListener('click', htmlClickHandler)
})
</script>