<template>
  <div>
    <template v-if="editing">
      <el-input
        ref="inputRef"
        style="width: 100%; font-size: 16px"
        v-model="inputValue"
        @blur="finishEditing"
        v-bind="$attrs"
      ></el-input>
    </template>
    <template v-else>
      <div v-if="isDblclick" style="" @dblclick="startEditing">
        <slot> {{ displayValue }}</slot>
      </div>
      <div v-else @click="startEditing">
        <slot> {{ displayValue }}</slot>
      </div>
    </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
  },
  isDblclick: {
    type: Boolean,
    default: true
  },
  displayValue: {
    type: String
  }
});
const emit = defineEmits(["done"]);
function startEditing() {
  if (props.disabled) return;
  editing.value = true;
  inputValue.value = props.displayValue || "";
  nextTick(() => {
    inputRef.value?.select();
  });
}

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

<style lang="scss" scoped>
.el-textarea {
  :deep(.el-textarea__inner) {
    padding: 0;
    background-color: unset;
    box-shadow: none;
  }
}
.el-input {
  :deep(.el-input__wrapper) {
    background-color: unset;
    box-shadow: none;
    &.is-focus {
      .el-input__inner::placeholder {
        color: transparent;
      }
    }
  }
}
</style>
