<template>
  <div :name="name" :class="getBorderClass({border, disabled, isFocus, pointer: true})" @click="toFocus">
    <n-input-lite v-if="isFocus" ref="input" v-model="keyword" :placeholder="textList.join(' ~ ')" :focusing="true"
                  :class="getValueClass({size, disabled, ellipsis: true, rightIcon: iconProps})"
                  @hook:mounted="onInputMounted" @u-enter="onEnter"></n-input-lite>
    <!-- 有值 / 无数据 -->
    <span v-else :class="getValueClass({size, disabled, ellipsis: true, rightIcon: iconProps, placeholder: !hasValue})">
      <template v-for="text in textList">
        <span class="n-date-picker-refer-text" :key="text">{{text}}</span>
      </template>
    </span>
    <!-- icon -->
    <n-icon v-if="iconProps" class="n-form-icon" v-bind="iconProps" @click="onIconClick"></n-icon>
  </div>
</template>

<script>
import NIcon from '@uif/next/lib/components/icon'
import NInputLite from '@uif/next/lib/components/input-lite'
import {isValueArray, prop} from '@uif/next/lib/utils/tools'
import {getBorderClass, getValueClass} from '_common/formUtils'

export default {
  name: 'n-date-picker-refer',
  components: {
    NIcon,
    NInputLite
  },
  model: {
    prop: 'isFocus',
    event: 'setFocus'
  },
  props: {
    // 激活状态
    isFocus: prop.boolean(),
    // 表单名称
    name: prop.string(),
    // 可显示的内容
    labels: prop.array(),
    // input 大小
    size: prop.inArray(['small', 'middle', 'large'], 'middle'),
    // input 边框形状
    border: prop.inArray(['none', 'line', 'rect'], 'rect'),
    // 禁用
    disabled: prop.boolean(),
    // 提示文本
    placeholder: prop.string('请选择'),
    // 可删除
    clearable: prop.boolean()
  },
  data () {
    return {
      getBorderClass,
      getValueClass,
      keyword: ''
    }
  },
  computed: {
    // 有值
    hasValue ({labels}) {
      return isValueArray(labels)
    },
    // 展示的值
    textList ({labels, placeholder}) {
      return isValueArray(labels) ? labels : [placeholder]
    },
    // 右侧icon
    iconProps ({hasValue, clearable, disabled}) {
      if (hasValue && clearable && !disabled) {
        return {type: 'circle-delete', scene: 'light', isRemove: true}
      }
      return {type: 'calendar-empty'}
    }
  },
  methods: {
    // 获焦事件
    toFocus () {
      if (!this.disabled) {
        this.$emit('setFocus', true)
      }
    },
    // 开始输入
    onInputMounted () {
      this.keyword = ''
    },
    // 用户正在输入
    onEnter () {
      this.$emit('user-input', this.keyword)
    },
    // 删除全部
    onIconClick (event) {
      if (this.iconProps.isRemove) {
        event.stopPropagation()
        this.$emit('u-update', [])
      }
    }
  }
}
</script>
