<template>
  <div
    class="hover-editor-container"
    @mouseenter="mouseenterHandler()"
    @mouseleave="mouseleaveHandler()"
  >
    <div class="hover-editor-content">
      <span v-if="!isModify" class="hover-editor-text">
        {{ editingValue }}
      </span>
      <span v-else v-focus="true">
        <a-textarea
          v-model="editingValue"
          :placeholder="placeholder"
          class="editor-textarea"
          auto-size
          @blur="blur"
          @update="update"
        />
      </span>
    </div>
    <div
      v-show="showEditor"
      :style="{
        marginLeft: ['', null, undefined].includes(visibleName) ? '5px' : '5px'
      }"
      class="editor-btn"
    >
      <icon-edit :size="14" @click="showEditorComponents()" />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { watch, computed, ref } from 'vue'

const props = defineProps<{
  modelValue?: any
  placeholder?: string
}>()

const emits = defineEmits(['update:modelValue', 'modify'])
const editingValue = ref(props.modelValue)
const isModify = ref(false)
const showEditor = ref(false)

const visibleName = computed(() => {
  return props.modelValue
})

const blur = () => {
  isModify.value = false
}

// 返显数据
const update = () => {
  const v = editingValue.value
  if (props.modelValue !== v) {
    emits('update:modelValue', v)
    emits('modify')
  }
  isModify.value = false
}

watch(
  () => props.modelValue,
  () => {
    editingValue.value = props.modelValue
  }
)

const showEditorComponents = () => {
  isModify.value = true
  showEditor.value = false
}

// 鼠标悬浮时显示编辑图标
const mouseenterHandler = () => {
  if (isModify.value) {
    return
  }
  showEditor.value = true
}

// 鼠标离开时隐藏编辑图标
const mouseleaveHandler = () => {
  showEditor.value = false
}
</script>

<style lang="less" scoped>
.hover-editor-container {
  width: 100%;
  display: flex;
  justify-content: start;
  align-items: center;
  //   position: absolute;
  top: 0;
  left: 0;
  height: auto;
  overflow-x: hidden;
  line-clamp: 3;
  text-overflow: ellipsis;
  line-clamp: 1;
  .hover-editor-content {
    overflow: hidden;

    padding: 5px;
    text-overflow: ellipsis;
    .hover-editor-text {
      height: 100%;
      width: 100%;
      padding-left: 10px;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
}
.editor-btn {
  display: flex;
  align-items: center;
  color: rgb(var(--primary-6));
  cursor: pointer;
}
</style>
