<template>
  <div class="table-edit">
    <div
      :class="{
        left:align ==='left',
        center: align ==='center',
        right: align ==='right',
      }"
      class="table-edit__text"
      v-if="!editStatus"
    >
      <span @dblclick="handleClick" >{{editValue?editValue:'-'}}</span>
      <i class="el-icon-edit" @click="handleClick"></i>
    </div>
    <div
      class="table-edit__edit"
      v-else
    >
      <el-input ref="input" :type="type" v-model="editValue" @blur="handleBlur" @keydown.native.enter="handleSave"></el-input>
      <i class="el-icon-check" @click="handleSave"></i>
    </div>
  </div>
</template>

<script>
  export default {
    name: "XdTableEditItem",
    props:{
      type:{
        type:String,
        default:'text'
      },
      value: {
        type:String|Number,
        default:''
      },
      align:{
        type:String,
        default: 'left'
      },
      blur:{
        type:Boolean,
        default: false
      }
    },
    data(){
      return {
        editValue: '',
        prevValue: '',
        editStatus:false,
      }
    },
    created() {
      this.editValue = this.value;
      this.prevValue = this.value;
    },

    methods:{
      handleClick(){
        this.editStatus = !this.editStatus;
        this.$nextTick(()=>{
          this.$refs['input'].focus()
        })

      },
      handleBlur(){
        if(this.blur) {
          this.handleSave()
        }
      },
      handleSave(){
        this.editStatus = !this.editStatus;
        this.$emit('input', this.editValue);
        this.$emit('onSave',(status)=>{
          if(status) this.prevValue = this.editValue;
          else this.editValue = this.prevValue;
          this.$emit('input', this.editValue);
        });
      },
    },

  }
</script>

<style scoped lang="scss">
  .table-edit {
    width: 100%;
    & > div {
      display: flex;
      align-items: flex-start;
      line-height: 17px;
      & > i {
        margin-left: 5px;
        font-size: 16px;
        cursor: pointer;
      }
    }

    &__text {
      font-size: 12px;
      &.center {
        justify-content: center;
      }
      &.left {
        justify-content: flex-start;
      }
      &.right {
        justify-content: flex-end;
      }
    }
    &__edit {
      align-items: center!important;
    }
  }
</style>
