<template>
    <div class="documentParsing" 
        v-show="isShowFile"
        @mouseover="handleMouseOver"
        @mouseleave="handleMouseLeave"
        @click="openFile"
        :style="{ maxWidth: isWindowMode ? '60%' : '80%' }">
        <!-- 内容区域 -->
        <div class="documentParsingContent">
            <div class="fileIcon">
                <img :src="imageUrl" alt="">
            </div>
            <div class="fileName"  ref="fileNameTextDiv" :style="{ maxWidth: isShowParsingStatus? fileNameTextMaxWidth : '90%' }" >
                <span class="fileNameText" :filePath="filePath" :imgBase64="imgBase64" v-text="fileNameText"></span>
            </div>
            <el-tooltip popper-class="uos-tooltip" effect="light" :show-arrow="false" :enterable="false"
                :show-after="1000" :offset="2" :content="parsingStatusText"  v-show="isShowParsingStatus">
                <div class="parsingStatus" v-show="isShowParsingStatus"  :style="{maxWidth : '40%'}">
                    <img :src="isParsingStatusEnd?'icons/warning.svg':'icons/loading.svg'"  alt=""  class="parsingStatusIcon"/>
                    <span class="parsingStatusText" v-text="parsingStatusText"></span>
                </div>
            </el-tooltip>
            
        </div>
        <!-- 删除按钮 -->
        <div  class="documentParsingDelete-btn" @click="handleDelete" v-show="isShowDelete">
            <img :src="isDarkMode? 'icons/file-delete-dark.svg':'icons/file-delete-light.svg'"  class="deleteIcon"/>
        </div>
    </div>
</template>

<script setup>
import { ref, watchEffect } from "vue";
import { useGlobalStore } from "@/store/global";
import { Qrequest } from "@/utils";
import _ from "lodash";
import { useRouter } from "vue-router";

const { chatQWeb, updateActivityColor, updateTheme, updateFont } = useGlobalStore()

const isEnabledMouthOver=ref(false)  //是否启用鼠标悬停事件
const isShowFile = ref(false)
const isShowDelete=ref(false);
const imageUrl = ref(''); // 用于存储图片的URL

const fileNameText = computed(() => {
    if(filePath.value != ""){
        return handleFileNameLength(filePath.value.substring(filePath.value.lastIndexOf('/') + 1))
    }
    return
})
const filePath = computed(() => {
    
    return props.filePath
})
const imgBase64 = computed(() => {
    setFileIcon(props.imgBase64)
})

const isShowParsingStatus = ref(false)  //解析状态是否显示
const isParsingStatusEnd = ref(false) //解析完成与否
const parsingStatusText = ref('')   //解析成功与否文案

const isDarkMode = ref(false)  //是否为深色主题
const sysFontPixelSize = ref(14)  //系统字体大小
const fileNameTextMaxWidth = ref('90%')  //根据窗口模式动态设置文件名最大宽度比例
const isWindowMode = ref(false)  //是否为窗口模式
const sigWindowModeChanged = (res) => {
    isWindowMode.value = res;

    //通过正则表达式在完整路径中获取文件名
    if(filePath.value != ""){
        fileNameText.value = handleFileNameLength(filePath.value.substring(filePath.value.lastIndexOf('/') + 1))
    }
    
}
const sigFontChanged = (family, pixelSize) => {
    //字号切换时
    sysFontPixelSize.value = pixelSize
    //通过正则表达式在完整路径中获取文件名
    if(filePath.value != ""){
        fileNameText.value = handleFileNameLength(filePath.value.substring(filePath.value.lastIndexOf('/') + 1))
    }
}

const responseAIFunObj = {
    sigWindowModeChanged,
    sigFontChanged
}


//等待渲染完成
onMounted(async () => {
    for (const key in responseAIFunObj) {
        if (Object.hasOwnProperty.call(responseAIFunObj, key)) {
            chatQWeb[key].connect(responseAIFunObj[key]);
        }
    }
    isWindowMode.value = await Qrequest(chatQWeb.isWindowMode);
})

onBeforeUnmount(() => {
    for (const key in responseAIFunObj) {
        if (Object.hasOwnProperty.call(responseAIFunObj, key)) {
            chatQWeb[key].disconnect(responseAIFunObj[key]);
        }
    }
});



const setFileIcon = (imgBase64_) =>{
    const blob = base64ToBlob(imgBase64_);
    imageUrl.value = createObjectURL(blob);
}

// 将Base64字符串转换为Blob
function base64ToBlob(base64) {
    const byteCharacters = atob(base64);
    const byteNumbers = new Array(byteCharacters.length);
    for (let i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i);
    }
    const byteArray = new Uint8Array(byteNumbers);
    return new Blob([byteArray], { type: 'image/png' });
}

// 创建Object URL
function createObjectURL(blob) {
  return URL.createObjectURL(blob);
}

const handleMouseOver = (event) => {
  if(isEnabledMouthOver.value){
    isShowDelete.value = true
  }
}
const handleMouseLeave = (event) => {
  isShowDelete.value = false
  // 在这里可以执行你想要在鼠标离开时进行的操作
}

const handleDelete = async(event) => {
    event.stopPropagation();  //阻止事件冒泡
    isShowFile.value = false
    emit('sigDeleteFile')
    // await Qrequest(chatQWeb.onDocSummaryRemove, filePath.value)
}

const openFile = async () => {
    await Qrequest(chatQWeb.openFile, filePath.value)
}

//文件名长度控制，超出时中间显示...
const maxFileNameLength = ref(10); // 设置最大显示长度
const fileNameTextDiv = ref(null); // 文件名div
const fileNameTextDivWidth = ref(100)


//获取当前主div的宽度
function getDocClassWidth(){
    const divWidth = document.querySelector('.fileNameText').clientWidth
    fileNameTextDivWidth.value = fileNameTextDiv.value.offsetWidth.value
    console.log(`divWidth = ${divWidth}, fileNameTextDivWidth = ${fileNameTextDivWidth}`)
}

const handleFileNameLength = (fileName) => {
    maxFileNameLength.value = 20
    if(isShowParsingStatus.value){
        if(sysFontPixelSize.value >= 15){
            maxFileNameLength.value = 9
            if (isWindowMode.value) {  //窗口模式
                fileNameTextMaxWidth.value = '70%' 
            }else{  //侧边栏模式
                fileNameTextMaxWidth.value = '60%' 
            }
        }else{
            maxFileNameLength.value = 14
            if (isWindowMode.value) {  //窗口模式
                fileNameTextMaxWidth.value = '70%' 
            }else{  //侧边栏模式
                fileNameTextMaxWidth.value = '45%' 
            }
        }
    }

    const suffix = fileName.match(/\.[^.]*/); // 获取文件后缀
    const fileNameWithoutSuffix = suffix ? fileName.slice(0, -suffix[0].length) : fileName;
    const fileNameLastChar = fileNameWithoutSuffix.slice(-1)
    const maxNameLength = maxFileNameLength.value - suffix[0].length - 2; // 留出空间给省略号和后缀

    if (fileNameWithoutSuffix.length > maxNameLength) {
        return fileNameWithoutSuffix.slice(0, maxNameLength) + '…' + fileNameLastChar + suffix;
    } else {
        return fileName;
    }
}
const props = defineProps(['fileNameText','filePath', 'imgBase64']) 
defineExpose({ isShowFile, isEnabledMouthOver, isShowParsingStatus, isParsingStatusEnd, parsingStatusText, isDarkMode, sysFontPixelSize, isWindowMode, handleFileNameLength})
const emit = defineEmits(['setFileParam', 'sigDeleteFile'])

</script>

<style lang="scss" scoped>
    .documentParsing{
        position: relative; /* 为按钮定位创建一个相对定位的上下文 */
        left: 10px;
        top: 8px;
        // max-width: 220px;
        max-width: 40%;
        width: fit-content;
        height: 30px;
        background-color: rgba(0, 0, 0, 0.1);
        // display: flex;
        align-items: center; /* 水平方向居中 */  
        // justify-content: center; /* 垂直方向居中 */
        border-radius: 8px;  /* 圆角 */
        // margin-bottom: 15px;
        cursor: pointer;
        // overflow: hidden;/* 超出部分不显示 */

        .documentParsingContent{
            // position: absolute;
            display: flex;
            align-items: center; /* 水平方向居中 */  
            // justify-content: center; /* 垂直方向居中 */
            height: 30px;
            // max-width: 220px;
            max-width: 100%;
            // width: fit-content;
            min-width: none;
            // margin-right: 10px;

            // text-overflow: ellipsis;/* 超出部分显示省略号 */
            text-overflow: ellipsis;/* 超出部分显示省略号 */
            overflow: hidden;/* 超出部分不显示 */
            
            .fileIcon{
                display: grid;
                width: 16px;
                height: 16px;
                align-items: center; /* 水平方向居中 */  
                justify-content: center; /* 垂直方向居中 */
                // background-color: black;
                margin-left: 7px;
                margin-right: 7px;
            }

            .fileIcon img {
                max-width: 100%;
                max-height: 100%;
                object-fit: cover; /* 根据需要选择 none | contain | cover | fill */
            }

            .fileName{
                display: flex;
                // max-width: 100px;
                max-width: 60%;
                height: 20px;
                align-items: center; /* 水平方向居中 */  
                // justify-content: flex-start; /* 垂直方向居中 */
                font-size: 1rem;
                font-family: var(--font-family);
                font-weight: 400;
                white-space: nowrap; /* 不换行 */
                text-overflow: ellipsis;/* 超出部分显示省略号 */
                overflow: hidden;/* 超出部分不显示 */
                margin-right: 11px;
                // color: rgb(0, 0, 0);

                .fileNameText{
                    white-space: nowrap; /* 不换行 */
                    text-overflow: ellipsis;/* 超出部分显示省略号 */
                    overflow: hidden;/* 超出部分不显示 */
                }
            }

            .parsingStatus{
                display: grid;
                max-width: none;
                min-width: 30%;
                // width: 65px;
                height: 20px;
                display: flex;
                align-items: center; /* 水平方向居中 */  
                // justify-content: center; /* 垂直方向居中 */
                margin-right: 10px;
                margin-left: auto;

                font-size: 1rem;
                font-family: var(--font-family);
                font-weight: 400;
                white-space: nowrap; /* 不换行 */
                overflow: hidden;/* 超出部分不显示 */
                text-overflow: ellipsis;/* 超出部分显示省略号 */

                .parsingStatusIcon{
                    min-width: 16px;
                    min-height: 16px;
                }

                .parsingStatusText{
                    margin-left: 7px;
                    font-size: 1rem;
                    font-family: var(--font-family);
                    font-weight: 400;
                    white-space: nowrap; /* 不换行 */
                    overflow: hidden;/* 超出部分不显示 */
                    text-overflow: ellipsis;/* 超出部分显示省略号 */
                }
            }
        }

        .documentParsingDelete-btn{
            display: flex;
            position: absolute; /* 绝对定位按钮 */
            top: 0; /* 将按钮顶部对齐到容器的顶部 */
            right: 0; /* 将按钮右侧对齐到容器的右侧 */
            // border: none; /* 移除按钮边框 */
            // background-color: rgba(0, 0, 0, 0.5); /* 按钮背景颜色 */
            // color: white; /* 按钮文字颜色 */
            // border-radius: 50%; /* 按钮圆角 */
            cursor: pointer; /* 鼠标悬停时显示指针 */
            // width: 10px;
            // height: 10px;
            // font-size: 0.4rem;
            // align-items: center; /* 水平方向居中 */  
            // justify-content: center; /* 垂直方向居中 */
            transform: translate(50%, -50%); /* 使用transform将子div的中心点移动到右上角 */
            // outline: none;

        }
    }

    .dark{
        .documentParsing{
            background-color: rgba(255, 255, 255, 0.5);
        }
        .fileName{
            color: rgb(255, 255, 255);
        }
        .parsingStatusText{
            color: rgba(255, 255, 255, 0.9);   
        }
    }
</style>