<template>
  <el-tooltip
    v-model="showTip"
    :manual="manual"
    :content="value"
    :disabled="!overflow"
  >
    <div
      v-if="disabled"
      ref="target"
      class="o-editor u-ellipsis"
    >
      {{ value }}
    </div>
    <input
      v-else
      ref="target"
      :value="value"
      class="o-editor input u-ellipsis"
      maxlength="50"
      @focus="onFocus"
      @blur="onBlur"
      @input="onInput"
      @keydown.enter="$event.target.blur()"
    >
  </el-tooltip>
</template>

<script>
export default {
  name: 'EditInput',
  props: {
    value: {
      type: String,
      default: ''
    },
    disabled: {
      type: [Boolean, String],
      default: false
    }
  },
  data () {
    return {
      overflow: false,
      showTip: false,
      manual: false
    }
  },
  watch: {
    value () {
      if (!this.manual) {
        this.$nextTick(this.checkSize)
      }
    }
  },
  mounted () {
    this.checkSize()

    window.addEventListener('resize', this.checkSize)
  },
  beforeDestroy () {
    window.removeEventListener('resize', this.checkSize)
  },
  methods: {
    onFocus () {
      this.manual = true
      this.showTip = false
    },
    onBlur () {
      this.manual = false
      this.$emit('edit')
      this.$nextTick(this.checkSize)
    },
    onInput (event) {
      this.$emit('input', event.target.value)
    },
    checkSize () {
      if (this.manual) {
        return
      }
      const target = this.$refs.target
      if (target) {
        this.overflow = target.scrollWidth > target.offsetWidth
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.o-editor {
  display: inline-block;
  width: 100%;
  height: 40px;
  padding: 0 10px;
  color: inherit;
  font-size: inherit;
  line-height: 38px;
  border: 1px solid transparent;

  &.input {
    line-height: 40px;
    outline: 0;
    -webkit-appearance: none;
    border-radius: $radius--mini;
    background-color: transparent;

    &:hover {
      border-color: $gray--dark;
    }

    &:focus {
      color: $black;
      border-color: #409eff;
      background-color: $blue--light;
    }
  }
}
</style>
