<!--
  @name: 输入框
  @description: -
  @author 张文
  @date: 2022-01-18
-->
<template>
  <div
    :class="[
      'ty-global-flex-start',
      showBottomBorder ? 'ty-global-bottom-border' : '',
      required?'ty-global-required' : '',
      'ty-input-box',
    ]"
  >
    <label
      v-if="title.length || !!$slots.title"
      :class="[
        'ty-global-flex-start',
        'ty-input-title',
        showColon?'ty-global-show-colon':''
      ]"
      :style="{
        width:titleWidth ? titleWidth + 'px' : 'auto',
        textAlign: titleAlign || 'left',
        display:'inline-block'
      }"
    >
      <slot name="title">{{ title }}</slot>

    </label>

    <div class="ty-global-flex-start ty-input-body">
      <!-- 输入框主体 -->
      <div class="ty-global-flex-start ty-input-boss">

        <!-- 键盘 -->
        <img
          v-if="showKeyboard && !disabled && !readonly"
          class="ty-input-img"
          :src="require('../../assets/img/InputIcon/keyboard.png')"
          alt="键盘"
          @click="keyboardClick"
        >

        <!-- 文本域 -->
        <textarea
          v-if="type === 'textarea'"
          ref="tyInput"
          class="ty-input-input"
          v-model="val"
          :name="name"
          :disabled="disabled"
          :readonly="readonly || readonlyInp"
          :rows="rows"
          :maxlength="maxlength"
          :style="{
            textAlign:inputAlign,
            resize:'none'
          }"
          :placeholder="placeholderData"
          @focus="inputFocus"
          @blur="inputBlur"
          @keydown.enter="confirm"
        />

        <!-- 输入框 -->
        <input
          v-else
          ref="tyInput"
          class="ty-input-input"
          :type="['number','digit'].includes(type) ? 'text' : type"
          :name="name"
          :value="val"
          :maxlength="maxlength"
          :disabled="disabled"
          :readonly="readonly || readonlyInp"
          :style="{
            textAlign:inputAlign
          }"
          :placeholder="placeholderData"
          @focus="inputFocus"
          @blur="inputBlur"
          @keydown.enter="confirm"
          @input="input"
        >

        <!-- 字数统计 -->
        <div
          v-if="showWordLimit"
          class="ty-input-word-limit"
        >
          <span v-if="maxlength">{{ value.length || 0 }} / {{ maxlength }}</span>
          <span v-else>{{ value.length }}</span>
        </div>

        <!-- 清除按钮 -->
        <van-icon
          v-if="showClear && !disabled && !readonly &&!readonlyInp  && val"
          class="ty-input-clear"
          name="clear"
          @click="clearClick"
        />

        <!-- 获取焦点时划线用的 -->
        <div class="ty-input-border"></div>

        <!-- 按钮插槽 -->
        <div v-if="!!$slots.button" class="ty-input-button-box">
          <slot name="button"></slot>
        </div>
      </div>

    </div>

  </div>
</template>

<script>

export default {
  name: "tyInput",
  props:{
    // 输入框的值
    value: [String, Number],

    // 输入框标题
    title: {
      type:[String, Number],
      default: ''
    },

    // 标题的对齐方式
    titleAlign:String,

    // 标题的宽度
    titleWidth: Number,

    // 输入框的名字，form表单使用
    name: String,

    // 输入类型
    type:{
      type: String,
      default: 'text'
    },

    // 占位符，默认为：请扫描或输入+传入的title值
    placeholder: String,

    // 是否禁用，默认false
    disabled:{
      type: Boolean,
      default: false
    },

    // 是否自读，默认false
    readonly:{
      type:Boolean,
      default:false
    },

    // 输入内容格式化函数，默认在change事件时触发
    formatter: Function,

    // 是否显示必填的星号，默认false。仅展示星号不做必填校验
    required:{
      type:Boolean,
      default:false
    },

    // 输入框文本对齐位置，默认左对齐
    inputAlign:{
      type:String,
      default: 'left'
    },

    // 文本域时显示的文本行数
    rows:{
      type: Number,
      default: 2
    },

    // 允许输入的最大字符量
    maxlength:[Number,String],

    // 是否显示字数统计
    showWordLimit:{
      type: Boolean,
      default :false
    },

    // 是否显示键盘图标
    showKeyboard:{
      type: Boolean,
      default: true
    },

    // 是否显示清除图标
    showClear:{
      type: Boolean,
      default: true
    },

    // 是否显示下边框
    showBottomBorder:{
      type: Boolean,
      default: true
    },

    // 是否获取输入框焦点，默认false，失去焦点后会改变值为false
    getFocus:{
      type:Boolean,
      default:false
    },

    // 是否禁止软键盘弹出，默认禁止弹出，可通过双击输入框强制弹出
    notKeyboard:{
      type:Boolean,
      default:true
    },

    // 获得扫码结果后是否立刻将输入框内容置空，默认false
    autoClearVal:{
      type:Boolean,
      default:false
    },

    // 输入完成后是否立刻失去焦点
    inputOverBlur:{
      type: Boolean,
      default: false
    },

    // 是否显示冒号
    showColon:{
      type: Boolean,
      default: false
    },

    // 如果输入类型是小数，则小数点接受几位，0表示不限制
    decimalScale:{
      type: Number,
      default: 0
    },
  },
  computed:{
    // 输入框实际绑定的值
    val:{
      get(){
        return this.value
      },
      set(v){
        this.$emit('input', v)
      }
    },
    // 提示文字
    placeholderData(){
      if(this.disabled || this.readonly){
        return ''
      }

      if (this.placeholder){
        return this.placeholder
      }

      return this.$tyLanguage.get('wms_project.pda.common.scanInput', '请扫描或输入') + this.title
    }
  },
  watch:{
    getFocus:{
      handler(n){
        n ? this.setFocusFn() : this.setBlurFn()
      },
    }
  },
  data() {
    return {
      // 用于禁止弹出键盘的零时标识
      readonlyInp:false,
      // 是否通过点击键盘
      isClickKeyboard:false
    }
  },
  mounted() {
    this.getFocus && this.setFocusFn()
  },
  methods: {

    // 键盘单击
    keyboardClick(){
      this.inputFocus()
      this.isClickKeyboard = true
    },

    // 点击清除按钮
    clearClick(){
      this.val=''
      this.$refs.tyInput.value = ''
      this.input()
      this.$refs.tyInput.focus()
      this.$emit('clear')
    },

    // 获取焦点
    setFocusFn(){
      this.isOpenKeyboard()
      this.$refs.tyInput.focus()
    },

    // 失去焦点
    setBlurFn(){
      this.$refs.tyInput.blur()
    },

    // 获取焦点事件
    inputFocus(){
      // 全局变量存入当前获取焦点的节点，方便后期获取焦点
      window.tyWindowGlobalData.set('input.dom',this.$refs.tyInput)
      this.$emit('update:getFocus', true)
    },

    // 失去焦点事件
    inputBlur(){
      if (this.val) this.val = this.val.trim()
      this.$emit('update:getFocus', false)
    },

    // 是否弹出输入法
    isOpenKeyboard(){
      if (this.isClickKeyboard){
        this.isClickKeyboard = false
        return
      }
      if (this.notKeyboard){
        this.readonlyInp=true
        setTimeout(()=>{
          this.readonlyInp=false
        },200)
      }else {
        this.isKeyboard=false
      }
    },

    // 点击回车
    async confirm(){

      let obj={}, val = this.val

      // 去除空格
      if (val) val = val.trim()


      // 是否需要清空输入框
      if (this.autoClearVal){
        this.clearClick()
      }else {
        this.val = val
      }

      // 输入框是否需要失去焦点
      if (this.inputOverBlur){
        this.inputBlur()
      }

      this.$emit('confirm', val, obj)
    },

    input(){
      let val = this.$refs.tyInput.value

      // 整数
      if (this.type === 'digit'){
        val = val.replace(/\D/g, '')
      }

      // 小数
      if (this.type === 'number'){
        const num = val.replace(/[^\d/.]/, '')
        if (/^\d+/.test(num)){
          const use = num.includes('.')
          if(use){
            const list = num.split('.')
            const decimal = this.decimalScale ? list[1].substring(0, this.decimalScale) : list[1]
            val =  list[0] + '.' + decimal
          }else {
            val =  num
          }
        }else {
          val = ''
        }
      }

      // 是否存在格式化函数
      if (this.formatter && typeof this.formatter === 'function'){
        val = this.formatter(val)
      }

      // 赋值
      this.$refs.tyInput.value = val


      this.$emit('input', val)
    }
  }
}
</script>

<style scoped lang="less">
@import "../../assets/css/var.less";


.ty-input-box{
  font-size: 14px;
  overflow: hidden;
  padding: 5px 0;
}

.ty-input-title{
  color: @titleColor;
  flex-shrink: 0;
  margin-right: 5px;
}

.ty-input-body{
  flex: 1;
  position: relative;
  transition: all .3s;
}

.ty-input-boss{
  flex: 1;
  position: relative;
}

.ty-input-img{
  width: 20px;
}

.ty-input-clear{
  font-size: 18px;
  color: #cdcdcd;
}

.ty-input-input{
  width: 100%;
  border: none;
  padding: 6px;

  &::-webkit-input-placeholder{
    color: #ccc;
  }


  &:focus ~ .ty-input-border:after{
    width: 100%;
  }
}

.ty-input-border{

  &:after{
    content: ' ';
    display: block;
    position: absolute;
    bottom: 0;
    left: 0;
    width: 0;
    height: 1px;
    background-color: @baseColor;
    transform: scaleY(0.5);
    transition: all .3s;
  }
}

.ty-input-word-limit{
  font-size: 12px;
  flex-shrink: 0;
  margin-right: 5px;

  >span{
    color: #ccc;
  }
}

.ty-input-button-box{
  padding-left: 8px;
  flex-shrink: 0;
}

</style>
