<style>
.z-table-cell-editable {
  display: flex;
  align-items: center;
}
.z-table-cell-editable .z-table-cell-editable__icon {
  cursor: pointer;
  vertical-align: middle;
  padding-left: 5px;
  fill: #2f54eb;
}
</style>

<template>
  <div>
    <!-- 可编辑状态 -->
    <div v-if="editable" class="z-table-cell-editable">
      <component :value="$_get(row, item.fullKey)" :is="item.type" v-bind="item.props" :style="item.style" size="mini" @input="onInput"></component>
      <span v-if="btnVisible !== false" @click="onConfirm">
        <svg class="z-table-cell-editable__icon" viewBox="0 0 1024 1024" width="24" height="24">
          <path d="M235.946667 472.938667l-45.226667 45.312 210.090667 209.514666 432.362666-427.690666-45.013333-45.482667-387.157333 382.976z"></path>
        </svg>
      </span>
    </div>
    <!-- 渲染状态 -->
    <template v-else>
      <!-- 渲染插槽 -->
      <template v-if="$scopedSlots['default']">
        <slot></slot>
      </template>
      <!-- 默认渲染 -->
      <template v-else>
        {{ $_get(row, item.agentKey || item.fullKey) }}
      </template>
    </template>
  </div>
</template>

<script>
import { get } from '../utils';

export default {
  name: 'cellEditable',
  props: {
    row: Object,
    item: Object,
    editable: Boolean,
    btnVisible: Boolean,
  },
  data() {
    return {
      oldValue: undefined,
      value: undefined,
      confirm: false,
    };
  },
  watch: {
    editable(val) {
      if (val) {
        this.confirm = false;
        this.oldValue = get(this.row, this.item.agentKey || this.item.fullKey);
        this.value = get(this.row, this.item.agentKey || this.item.fullKey);
      } else {
        if (!this.confirm) {
          this.$emit('cancel', this.emitData);
        }
      }
    },
  },
  computed: {
    emitData() {
      const { oldValue, value, row, item } = this;
      return { oldValue, value, row, key: item.key, fullKey: item.fullKey };
    },
  },
  methods: {
    $_get: get,
    // 组件触发input事件
    onInput(value) {
      this.value = value;
      this.$emit('update', this.emitData);
    },
    // 当点击确认
    onConfirm() {
      this.confirm = true;
      this.$emit('done', this.emitData);
    },
  },
};
</script>
