<template>
  <div :class="{main: true, readonly: !!readonly}" :style="{height: height || '36px'}">
    <span
      v-if="!editing"
      class="plain-text"
      :style="{'justify-content': align || 'left'}"
      @click="edit(true)"
    >{{internalValue}}</span>
    <div v-else :class="{'plain-input': !!plain}">
      <el-input
        ref="_input"
        class="val-input"
        size="small"
        :placeholder="placeholder || '请输入内容'"
        v-model="internalValue"
        @blur="edit(false)"
        @keyup.enter.native="edit(false)"
        @keyup.esc.native="edit(false)"
        clearable
        :type="type"
        oninput="type === 'number' && (value=value.replace(/[^\d-.]/g,''))"
        @input="onTextEdited"
      />
    </div>
  </div>
</template>

<script>
export default {
  name: "LineEdit",
  props: ['value', 'readonly', 'placeholder', 'height', 'type', 'plain', 'align', ],
  data() {
    return {
      editing: false,
      internalValue: this.value,
    };
  },
  watch: {
    value: function(newVal) {
      if(newVal !== this.internalValue)
        this.internalValue = newVal;
    },
  },
  methods: {
    edit(on) {
      if(!!this.readonly)
        return;
      if(on)
      {
        this.editing = true;
        this.$nextTick(() => {
          this.$refs._input.focus();
        })
      }
      else
      {
        this.editing = false;
        if(this.internalValue === null || this.internalValue === undefined)
        {
          this.internalValue = '';
          this.$emit('input', this.internalValue);
        }
      }
    },
    onTextEdited(val) {
      if(val !== this.value)
        this.$emit('input', val);
    },
  }
}
</script>

<style scoped>
.main {
  text-align: center;
  min-height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.main[class="main"] .plain-text:hover {
  cursor: pointer;
}
.main[class="main"] .plain-text:hover:after {
  content: '🖉';
  color: #409EFF;
  font-size: 12px;
  cursor: pointer;
  position: absolute;
  /*margin-left: 10px;*/
  right: 0;
  font-weight: bold;
}
.plain-text {
  width: 100%;
  height: 100%;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}
.plain-input >>> .el-input {
  min-width: unset;
}

.plain-input >>> .el-input__inner {
  border-width: 0 0 1px 0;
  border-radius: 0;
}

.plain-input.is-disabled >>> .el-input__inner {
  background-color: unset;
  min-width: unset;
}
/* chrome kernel */
.val-input >>> input::-webkit-outer-spin-button,
.val-input >>> input::-webkit-inner-spin-button {
   -webkit-appearance: none !important;
 }
/* firefox kernel */
.val-input >>> input[type='number'] {
  -moz-appearance: textfield;
  min-width: unset;
}
</style>
