<template>
    <el-popover placement="top" trigger="hover" popper-style="min-width:unset;padding:0;width:auto;">
        <template #reference>
            <div ref="operaTextRef">
                <slot></slot>
            </div>
        </template>
        <div class="row items-center" style="padding:4px">
            <div class="text-opera-item" @click="handleCopyText">
                <el-tooltip content="复制" placement="top">
                    <IconCopy :size="18"></IconCopy>
                </el-tooltip>
            </div>
            <div class="text-opera-item" @click="handleInsert">
                <el-tooltip content="添加到文本" placement="top">
                    <IconDocAdd :size="18"></IconDocAdd>
                </el-tooltip>
            </div>
            <div class="text-opera-item" @click="handleReplace">
                <el-tooltip content="替换文本" placement="top">
                    <IconFileConversion :size="18"></IconFileConversion>
                </el-tooltip>
            </div>
        </div>
    </el-popover>
</template>

<script lang="ts" setup>
import { useMainStore, useSlidesStore } from "@/store";
import { copyText, replaceText } from "@/utils/clipboard";
import { ElMessage } from "element-plus";
import { storeToRefs } from "pinia";
import { ref } from "vue";
import useHistorySnapshot from '@/hooks/useHistorySnapshot'

const mainStore = useMainStore();
const { handleElement } = storeToRefs(mainStore);
const slidesStore = useSlidesStore()
const { addHistorySnapshot } = useHistorySnapshot()

const operaTextRef = ref<any>()
const handleCopyText= () => {
    const text = operaTextRef.value.innerText
    copyText(text).then(()=>{
        ElMessage({ message: '复制成功', type: 'success' })
    })
}
const handleReplace=()=>{
    if(handleElement.value && 'content' in handleElement.value){
        const text = operaTextRef.value.innerText
        const newContent = replaceText(handleElement.value!.content,text,'R')
        updateElement(newContent)
    }
    ElMessage({ message: '操作成功', type: 'success' })
}
const handleInsert=()=>{
    if(handleElement.value && 'content' in handleElement.value){
        const text = operaTextRef.value.innerText
        const newContent = replaceText(handleElement.value!.content,text,'I')
        updateElement(newContent)
    }
    ElMessage({ message: '操作成功', type: 'success' })
}
const updateElement = (content:string)=>{
    const update:any = {
        id:handleElement.value?.id,
        props:{content}
    }
    slidesStore.updateElement(update)
    addHistorySnapshot()
}
</script>

<style>
    .text-opera-item{
        padding:5px;
        border-radius: 5px;
        cursor: pointer;
        color: #000;
        line-height: 1;
        
    }
    .text-opera-item:hover{
        background: #000;
        color: #FFF;
    }
</style>