<template>
  <div>
    <div class="input-box">
      <input class="lx-input"
        :class="{'is-bg': bg, 'is-center': center}"
        ref="input"
        v-bind="$attrs"
        :value="currentValue"
        @input="handleInput"
        @focus="handleFocus"
        @blur="handleBlur"
        @change="handleChange"
        />
        <p v-show="!!tip" class="lx-input_tip" :class="{'is-center': center}">{{tip}}</p>
        <img v-if="bg" class="lx-input__bg" :src="bg">
        <div class="lx-input__clear" v-if="clearable">
          <img @click="clearInput" v-if='currentValue' src="./close.png" alt="关闭">
        </div>
    </div>
  </div>
</template>

<script>
// 1. 组件外必须有div包裹
// 2. 组件必须有name属性
export default {
  name: 'lxInput',
  props: {
    value:{
      type: String,
      default: ''
    },
    bg:{
      type: String,
      default: ''
    },
    tip: {
      type: String,
      default: ''
    },
    clearable: {
      type: Boolean,
      default: false
    },
    center: Boolean,
  },
  data() {
    return {
      focused: false,
      currentValue: this.value ? this.value : '',
    }
  },
  computed: {

  },
  mounted() {

  },
  watch: {
    // value(val, oldValue) {
    //   this.setCurrentValue(val);
    // }
  },
  methods: {
    focus() {
      this.$refs.input.focus();
    },
    blur() {
      this.$refs.input.blur();
    },
    handleInput(event) {
      const value = event.target.value;
      this.setCurrentValue(value);
      this.$emit('input', value)
    },
    handleFocus(event) {
      this.focused = true
      this.$emit('focus', event)
    },
    handleBlur(event) {
      this.focused = false
      this.$emit('blur', event)
    },
    handleChange(event) {
      this.$emit('change', event.target.value)
    },
    setCurrentValue(value) {
      this.currentValue = value
    },
    clearInput() {
      this.$emit('input', '');
      this.$emit('change', '');
      this.$emit('clear');
      this.setCurrentValue('');
      this.focus();
    }
  }
}
</script>

