<template>
  <div>
    <template v-if="editing">
      <el-input ref="inputRef" v-model="inputValue" @blur="finishEditing" v-bind="$attrs"></el-input>
    </template>
    <template v-else> {{ displayValue }} <slot name="suffix"></slot> </template>
  </div>
</template>

<script lang="ts" setup>
import { ref, defineProps, defineEmits, nextTick, defineExpose, onBeforeUnmount } from "vue";
const editing = ref(false);
const inputValue = ref("");
const inputRef = ref();
const timerId = ref();
const props = defineProps({
  disabled: {
    type: Boolean,
    default: false
  },
  displayValue: {
    type: String
  }
});
const emit = defineEmits(["done"]);
function startEditing() {
  if (props.disabled) return;
  editing.value = true;
  inputValue.value = props.displayValue || "";
  nextTick(() => {
    inputRef.value?.focus();
  });
}

function finishEditing(event: Event) {
  // 加一个定时器目的是，页面卸载时不要保存
  timerId.value = setTimeout(() => {
    emit("done", {
      event,
      inputValue: inputValue.value.trim(),
      displayValue: props.displayValue,
      callback: () => {
        editing.value = false;
      }
    });
    timerId.value = null;
  }, 600);
}
onBeforeUnmount(() => {
  timerId.value && clearTimeout(timerId.value);
});
defineExpose({
  startEditing
});
</script>

<style lang="scss" scoped></style>
