<template>
    <el-dialog v-model="show" v-loading="loading" :show-close="false" 
    :close-on-press-escape="false" :close-on-click-modal="false" 
    style="width: 600px;">
        <template #header>
            <div class="row overflow-hide">
                <div>
                    <img v-if="details.FileType==1" class="q-px-md" 
                    :src="!details.ConfigId?datas.pdfImg:datas.pdfImgConfig" 
                    style="height: 43px;" />
                    <img v-if="details.FileType==2" class="q-px-md" 
                    :src="datas.adsImg" 
                    style="height: 43px;" />
                </div>
                <div class="q-pl-md col">
                    <div>
                        <el-tooltip
                        placement="top-start">
                            <template #content><div style="max-width: 600px;">{{details.FileName}}</div></template>
                            <div class="HistoricalVersion-Title pointer">{{details.FileName}}</div>
                        </el-tooltip>
                    </div>
                    <div class="text-small text-5B5D62 q-pt-sm">创建者：{{details.CreateName}}</div>
                </div>
            </div>
        </template>
        
        <div class="HistoricalVersion-container" 
        ref="HistoricalVersion"
        style="min-height: 200px;max-height: 400px;">
                <el-scrollbar @scroll="scrollingHandler" height="400">
                <table class="text-small" style="width: 100%;">
                    <tr class="text-left">
                        <th class="text-light" style="min-width: 150px;width: 150px;">时间</th>
                        <th class="text-light" style="min-width: 100px;width: 100px;"><span >更新者</span></th>
                        <th class="text-light" style="min-width: 80px;width: 80px;">大小</th>
                        <th class="text-light">版本名称</th>
                        <th class="text-light text-center" style="min-width: 120px;width: 120px;">操作</th>
                    </tr>
                    <tr class="HistoricalVersion-table pointer" v-for="(item,index) in dataList">
                        <td class="text-light text-5B5D62">
                            <span class="text-bold">{{item.UpdateTime.substr(0,11)}}</span>
                            <span class="q-pl-md q-pt-sm">{{item.UpdateTime.substr(11,19)}}</span>
                        </td>
                        <td class="HistoricalVersion-title text-light textwrap text-5B5D62">
                            <span>{{item.CreateByName}}</span>
                        </td>
                        <td class="text-light text-5B5D62"><span>{{item.FileSize}}KB</span></td>
                        <td class="text-light">
                            <span :class="[item.LogId==0?'active':'text-5B5D62']">
                            {{item.LogId==0?'当前版本':''}}</span>
                        </td>
                        <td class="text-center">
                            <span class="hoverShow row items-center">
                                <el-button type="primary" icon="View" size="small" @click.stop="clickControls(item)">查看</el-button>
                                <el-dropdown class="q-pl-md" trigger="click">
                                    <el-icon size="16" color="#b1b7cf"><MoreFilled /></el-icon>
                                    <template #dropdown>
                                        <el-dropdown-menu class="q-pa-md">
                                        <el-dropdown-item icon="Promotion" @click.stop="clickControls(item,1)">另存</el-dropdown-item>
                                        <el-dropdown-item v-if="item.LogId!=0" icon="Switch" @click.stop="clickControls(item,2)">替换</el-dropdown-item>
                                    </el-dropdown-menu>
                                    </template>
                                </el-dropdown>
                                </span>
                        </td>
                    </tr>
                </table>
                <div v-if="dataList.length == 0 && !loading" class="bg-white rounded col" 
                style="padding: 40px 10px;">
                    <el-empty :image-size="150" description="文档没有历史版本" />
                </div>
                <el-divider class="no-bg q-mt-lg" v-if='dataList.length>0 && queryObj.pageCount == queryObj.pageIndex && !loading && queryObj.pageCount != 1'>
                    <span class="text-small bg-white" style="padding: 0 10px;color:#a3a3a3">已加载完成所有数据</span>
                </el-divider>
                <div v-if="loading" style="height:40px;" class="q-mt-md no-bg" background="transparent" v-loading="loading" element-loading-text="正在加载中"></div>
            </el-scrollbar>
        </div>
        
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="()=>closedhandler()">关闭</el-button>
            </span>
        </template>
    </el-dialog>
    <CopyFile v-if="isCopyTo" 
    :details="details"
    :type="datas.type"
    :his-obj="journeyAdsDetails"
    @close="() => {journeyAdsDetails = '';isCopyTo=false}"
    @success="refreshHandler()"></CopyFile>
</template>
<script setup lang="ts">
import { ApiResult } from '@/configs/axios';
import { ref,reactive } from 'vue';
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus';
import ConfigService from '@/services/ConfigService';
import { createPlayLink, query } from '@/utils/common'
import CopyFile from "./CopyFile.vue";

    const props = defineProps({
        id:{
            type:Number,
            required:true
        },
        details: {
            type:Object,
            required:true
        }
    })
    const emit = defineEmits<{
    (event: 'close'): void
    (event: 'refreshHandler'): void
    }>()
    const datas = reactive({
        type: 1,
        pdfImg: 'https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Test/Upload/Goods/1708337830000_43.png',
        pdfImgConfig:'https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Test/Upload/Goods/20240805163740.png',
        adsImg: 'https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Test/Upload/Goods/1708250377000_777.png',
    })
    const show=ref(true)
    const loading = ref(false)
    const HistoricalVersion = ref<any>()
    const deleteLoading = ref<any>(null);
    const queryObj = reactive({
        pageIndex: 1,
        pageSize: 10,
        pageCount: 0, //总页数
        FileId: props.details.FileId,
    })
    const journeyAdsDetails = ref<any>('');
    const isCopyTo = ref(false);
    const dataList=ref<any[]>([])

    const clickControls = (row:any,type:any=0) => {
        if(type){
            journeyAdsDetails.value = row
            if(type==1){
                isCopyTo.value = true
                datas.type = type
            }else{
                ElMessageBox.confirm(
                    `此操作将替换到当前版本，是否确定?`,
                    "提示",
                    {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning",
                    }
                )
                    .then(async () => {
                        try {
                            SaveOverlay()
                        } catch (error) { }
                    })
                    .catch(() => { });
            }
        }else {
            let param = query()
            const url = createPlayLink(row.FileId,row.LogId,1)//`${location.origin}/?uid=${param.uid}&sellId=${row.FileId}&LogId=${row.LogId}&ViewSlideshow=1`
            window.open(url);
        }
    }
    const SaveOverlay = async () => {
        let queryMsg = {
            LogId: journeyAdsDetails.value.LogId,
            FileId: journeyAdsDetails.value.FileId,
            UpdateType: 2,
            FolderId: '',
        };
        deleteLoading.value = ElLoading.service({
            lock: true,
            text: "正在处理",
        });
        let pageRes = await ConfigService.UpdateOtherByHistory(queryMsg);
        if (pageRes.data.resultCode == ApiResult.SUCCESS) {
            ElMessage({
                showClose: true,
                message: `替换文件${props.details.FileType ? "" : "夹"}成功`,
                type: "success",
            });
            refreshHandler()
        } else {
            ElMessage({
                showClose: true,
                message: `替换文件${props.details.FileType ? "" : "夹"}失败`,
                type: "warning",
            });
        }
        deleteLoading.value.close();
        deleteLoading.value = null;
    }
    const closedhandler=()=>{
        emit('close')
    }
    const querySearchHandler = async () => {
        if(loading.value) return
        loading.value = true
        try {
            if(queryObj.pageIndex == 1) dataList.value =[]
            let pageRes = await ConfigService.GetFileHistory(queryObj);
            if (pageRes.data.resultCode==ApiResult.SUCCESS) {
                pageRes.data.data.pageData.forEach((x:any) => {
                    x.NewTitle = ''
                })
                dataList.value = dataList.value.concat(pageRes.data.data.pageData)
                queryObj.pageCount = pageRes.data.data.pageCount;
            }
        } catch (error) {
            ElMessage.error({
                message:'数据加载异常，请刷新页面'
            })
        }
        loading.value = false
    }
    const scrollingHandler = () =>{
        if(HistoricalVersion.value && !loading.value){
            let maxHeight = HistoricalVersion.value.scrollHeight - HistoricalVersion.value.offsetHeight
            let scrollTop = HistoricalVersion.value.scrollTop
            if((maxHeight - scrollTop==0||maxHeight - scrollTop<1) && queryObj.pageCount > queryObj.pageIndex) {
                queryObj.pageIndex++
                querySearchHandler()
            }
        }
    }

    const refreshHandler = () => {
        queryObj.pageIndex = 1;
        querySearchHandler();
        emit('refreshHandler')
    }
    querySearchHandler()

</script>
<style lang="scss" scoped>
    .HistoricalVersion-Title{
        width: 100%;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        font-size: 15px;
        position: relative;
    }
    .HistoricalVersion-container th{
        padding: 0 10px 5px 10px;
        border-bottom: 1px solid #f6f6f6;
        background: #fff;
        position: sticky;
        top: 0px;
        z-index: 2;
    }
    .HistoricalVersion-container td{
        padding:  8px 10px;
        border-bottom: 1px solid #f6f6f6;
    }
    .hoverShow {
        opacity: 0;
    }
    .HistoricalVersion-table:hover .hoverShow {
        opacity: 1;
    }
    .active {
        color: $themeColor;
    }
</style>