<template>
  <input v-bind="{class: {ellipsis: true, uppercase}, name, value: nValue, disabled, readonly, placeholder, autocomplete: 'off'}"
         v-on="{...$listeners, input: onUserInput}" @focus="onFocus" @blur="onBlur" @keyup.enter="onEnter"
         @compositionstart="onCompositionStart" @compositionend="onCompositionEnd">
</template>
<script>
import {prop} from '@uif/next/lib/utils/tools'
import vModel from '_common/vModel'
import {formatUserInputValue, formatUserValue} from '_common/inputUtils'

export default {
  name: 'n-input-lite',
  mixins: [vModel],
  props: {
    // 表单名称
    name: prop.string(),
    // 表单值
    value: prop.stringNumber(),
    // 输入提示
    placeholder: prop.string(),
    // 禁用
    disabled: prop.boolean(),
    // 只读
    readonly: prop.boolean(),
    // 数值输入
    number: {
      type: [Number, Boolean],
      default: false
    },
    // 负数
    negative: prop.boolean(),
    // 去首位空
    trim: prop.boolean(true),
    // 自动大写
    uppercase: prop.boolean(),
    // 一直获焦
    focusing: prop.boolean()
  },
  data () {
    return {
      nValue: this.value,
      // 输入法输入
      isOnComposition: false,
      listeners: Object.assign({}, this.$listeners, {input: () => 0})
    }
  },
  mounted () {
    this.setFocusing(0)
  },
  methods: {
    setValue (value) {
      if (this.nValue !== value) {
        this.nValue = value
        this.$emit('u-update', this.nValue)
      }
    },
    // 用户输入事件
    onUserInput (event) {
      if (!this.isOnComposition) {
        const {uppercase, number, negative} = this
        const value = formatUserInputValue({value: event.target.value, uppercase, number, negative})
        this.setValue(value)
        if (event.target.value !== value) {
          event.target.value = value
        }
      }
    },
    // 用户输入事件 输入法
    onCompositionStart () {
      this.isOnComposition = true
    },
    // 用户输入事件 输入法
    onCompositionEnd (event) {
      this.isOnComposition = false
      this.onUserInput(event)
    },
    // 获取焦点
    onFocus () {
      this.backup = this.nValue
      this.$emit('u-focus', this)
    },
    // 失去焦点
    onBlur (event) {
      const value = formatUserValue({value: event.target.value, uppercase: this.uppercase, number: this.number, needTrim: this.trim})
      this.setValue(value)
      this.$emit('u-blur', this)
      if (this.nValue !== this.backup) {
        this.$emit('u-change', this.nValue)
      }
      this.setFocusing(200)
    },
    // 回车事件
    onEnter (event) {
      const value = formatUserValue({value: event.target.value, uppercase: this.uppercase, number: this.number, needTrim: this.trim})
      this.setValue(value)
      this.$emit('u-enter', this.nValue)
    },
    // 设置获焦
    setFocusing (delay) {
      if (this.focusing) {
        setTimeout(() => !this._isDestroyed && this.$el && this.$el.focus(), delay)
      }
    }
  }
}
</script>
