<script setup name="sharedDetail">
import {nextTick, onMounted, ref, computed, getCurrentInstance} from 'vue'
import {getStaticImg} from '@/hooks/common.js'
import { useRoute, useRouter } from "vue-router";
import apiSheet from '@/api/sheet'
import { useWindowSize } from '@vueuse/core'
import { showToast, showDialog  } from "vant";
import {usePublicSettingStore} from '@/store/modules/publicSetting'
import {etaTablePermission,useAuthBtn} from '@/hooks/useAuthBtn'
const {checkAuthBtn} = useAuthBtn()
const publicSettingStore = usePublicSettingStore()
// import { useDownLoadFile } from '@/hooks/useDownLoadFile'
const { appContext : { config: { globalProperties } } } = getCurrentInstance();
const { width } = useWindowSize()
const route = useRoute()
const router = useRouter()
const queryData = ref({})
const link = ref(publicSettingStore.publicSetting.ChartViewUrl);
//显示更多操作栏
let showMoreAction = ref(false)

const sheetActions = computed(() => {
    let authList = []
    const Source = route.query.Source
    if(Source === 1) authList = [ etaTablePermission.etaTable_customize_mix_refresh, etaTablePermission.etaTable_customize_mix_download, etaTablePermission.etaTable_customize_mix_del]
    else if (Source === 2) authList = [ etaTablePermission.etaTable_customize_data_refresh, etaTablePermission.etaTable_customize_data_download, etaTablePermission.etaTable_customize_data_del]
    else authList = [ etaTablePermission.etaTable_customize_mix_refresh, etaTablePermission.etaTable_excel_download, etaTablePermission.etaTable_excel_del]
    return [
        // { label: globalProperties.$t('shared_table.refresh'), types:'flushed', src: getStaticImg('table/flushed.png'), isAuth: Source === 2 ? true : checkAuthBtn(authList[0]) }, /* 因为pc端时间序列表格没有刷新这个权限，所以暂时直接给true */
        { label: globalProperties.$t('shared_table.download'), types:'download', src: getStaticImg('table/download.png'), isAuth: checkAuthBtn(authList[1])},
        { label: globalProperties.$t('shared_table.delete'), types:'delete', src: getStaticImg('table/delete.png'), isAuth: checkAuthBtn(authList[2])},
    ]
})

const downExcelFileUrl = computed(() => {
    let url = `${
    import.meta.env.VITE_APP_API_URL
    }/datamanage/excel_info/table/download?${localStorage.getItem("token")}`;
    return url;
})

onMounted(() => {
    getExcelDetail( 'load' )
})
//获取表格列表
async function getExcelDetail( source = 'refresh', ExcelInfoId = '' ){
    const detailReq = {
        ExcelInfoId: route.query.id,
    }
    if(source==='delete') detailReq.ExcelInfoId = ExcelInfoId
    const res = await apiSheet.excelDetail(detailReq)
    if(res.Ret!==200) return 
    if(source==='refresh') showToast({ type: 'success', message: globalProperties.$t('shared_table.refresh_success') })
    queryData.value = res.Data
    document.title = queryData.value.ExcelName
}

//更多操作
function handleActionClick(item){
    switch(item.types){
        case 'flushed':
            getExcelDetail( 'refresh' )
            showMoreAction.value = false
            break;
        case 'download':
            downloadExcel(queryData.value)
            showMoreAction.value = false
            break;
        case 'delete':
            showDialog({
                title: globalProperties.$t('shared_table.note'),
                message: globalProperties.$t('shared_table.once_deleted'),
                showCancelButton: true
            }).then(() => {
                apiSheet.excelDelete({
                    ExcelClassifyId: queryData.value.ExcelClassifyId,
                    ExcelInfoId: queryData.value.ExcelInfoId,
                    Source: queryData.Source,
                }).then(res=>{
                    if(res.Ret!==200) return 
                    showToast({message: globalProperties.$t('shared_table.deletion_success'),type:'success'})
                    showMoreAction.value = false
                    getExcelDetail('delete', res.Data.ExcelInfoId)
                })
            }).catch(()=>{})
            break;
        case 'cancel':
            showMoreAction.value = false
            break;
    }
}

/* 下载数据 */
function downloadExcel(cell) {
    const { Source, FileUrl, ExcelInfoId, ExcelName } = cell;
    console.log(cell);
    
    let value = "";
    if (Source === 1) {
        handleDownloadResource(FileUrl, ExcelName)
    } else if ([2, 3,5].includes(Source)) {
        value = `${downExcelFileUrl.value}&ExcelInfoId=${ExcelInfoId}`;
        console.log(value);
        
        const a = document.createElement("a");
        a.href = value;
        a.target = "_blank";
        a.download = ExcelName;
        a.style.display = "none";
        document.body.append(a);
        a.click();
    }
}
// 下载文件
function handleDownloadResource(url,fileName,successCb,faileCb){
    const b = new Base64() 
    const arr = url.split('/')
    const _fileName = arr[arr.length-1]
    const fileNameTypeArr = fileName.split('.')
    const _fileNameTypeArr = _fileName.split('.')
    const fileNameType = fileNameTypeArr.length > 1 ? fileNameTypeArr[fileNameTypeArr.length-1] : ''
    const _fileNameType = _fileNameTypeArr.length > 1 ? _fileNameTypeArr[_fileNameTypeArr.length-1] : ''
    apiSheet.apiDownloadResource({
        FileName:/* fileName||_fileName */'',
        FileUrl:b.encode(url) 
    }).then(res=>{
        //bus.$parseData(response);
        const content = res
        const blob = new Blob([content])
        console.log(blob);
        
        if ('download' in document.createElement('a')) {
            const elink = document.createElement('a')
            elink.download = fileNameType?fileName:(fileName+'.'+_fileNameType)
            elink.style.display = 'none'
            elink.href = window.URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            window.URL.revokeObjectURL(elink.href)
            document.body.removeChild(elink)
        } else {
            navigator.msSaveBlob(blob, fileNameType?fileName:(fileName+'.'+_fileNameType))
        }
        successCb&&successCb()
    }).catch(()=>{
        showToast({message: '下载失败',type:'warning'})
        faileCb&&faileCb()
    })
}

function Base64() {
    // private property
    var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    // public method for encoding
    this.encode = function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;
        input = this._utf8_encode(input);
        while (i < input.length) {
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);
            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;
            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }
            output = output +
                _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
                _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
        }
        return output;
    }
    // private method for UTF-8 encoding
    this._utf8_encode = function (string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";
        for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);
            if (c < 128) {
                utftext += String.fromCharCode(c);
            } else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            } else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }
        }
        return utftext;
    }
}
</script>

<template>
    <div class="page">
        <div class="table-title">
            <div class="table-name">{{ queryData.ExcelName }}</div>
            <div class="top-box">
                <div class="top-item">{{ $t('shared_table.author') }}：{{ queryData.SysUserRealName }}</div>
                <div class="top-item">{{ $t('shared_table.recent_save_time') }}：{{ queryData.CreateTime?.slice(0,10) }} </div>
                <!-- <van-icon name="more-o" @click.stop="showMoreAction=true"/> -->
                <!-- <div class="top-item"></div> -->
            </div>
        </div>
        <div class="sheet-box" v-if="queryData.UniqueCode">
            <iframe v-if="link" :src="link + '/sheetshow?code=' + queryData.UniqueCode" frameborder="0" width="100%" height="100%"></iframe>
        </div>
        <div class="bottom">
            <div v-for="item in sheetActions" :key="item.types">
                <div class="bottom-item" @click="handleActionClick(item)" v-if="item.isAuth">
                    <img :src="item.src" alt="">
                    <div>{{item.label}}</div>
                </div>
            </div>
        </div>
        <!-- 更多设置弹窗 -->
        <van-popup
            v-model:show="showMoreAction"
            :position="width>650?'center':'bottom'"
            round
            closeable
            :style="width>650?{ width: '400px'}:''"
        >
            <div class="global-pop-wrap_mobile sheet-more-action-wrap">
                <div class="head-box">
                    <div class="title van-ellipsis">{{queryData.ExcelName}}</div>
                </div>
                <div class="action-box">
                    <template v-for="item in sheetActions" :key="item.types">
                        <div class="action-item" @click="handleActionClick(item)">
                            {{item.label}}
                        </div>
                    </template>
                </div>
            </div>
        </van-popup>
    </div>
</template>

<style lang="scss" scoped>
.page{
    width: 100%;
    height: 100vh;
    padding: 24px;
    .table-name {
        max-height: 100px;
        font-family: PingFang SC;
        font-size: 36px;
        font-weight: 400;
        line-height: 52px;
        // text-align: left;
    }
    .top-box {
        width: 100%;
        height: 60px;
        display: flex;
        justify-content: space-between;
        font-family: PingFang SC;
        font-size: 24px;
        font-weight: 400;
        line-height: 32px;
        text-align: center;
        color: rgba(102, 102, 102, 1);
        .top-item {
            line-height: 60px;
        }
    }
    .sheet-box{
        width: 100%;
        height: calc(100% - 200px);
        // background-color: pink;
    }
    .sheet-more-action-wrap{
        .head-box{
            .title{
                width: 100%;
                padding:34px 100px;
                box-sizing: border-box;
                font-size: 36px;
                font-weight: 600;
                text-align: center;
            }
        }
        .action-box{
            .action-item{
                text-align: center;
                padding:32px 84px;
                border-bottom: 1px solid #DCDFE6;
                &:last-child{
                    border-bottom: none;
                }
            }
        }
    }
    .bottom {
        margin-top: 10px;
        display: flex;
        justify-content: space-around;
        .bottom-item {
            color: rgba(51, 51, 51, 1);
            font-size: 20px;
            font-weight: 400;
            line-height: 32px;
            text-align: center;
            img {
                width: 40px;
                height: 40px;
            }
        }
    }
}
@media screen and (min-width: 650px) {
    .page{
        width: 100%;
        height: 100vh;
        padding: 12px;
        .table-title {
            width: 100%;
            display: flex;
            justify-content: space-between;
            .table-name {
                width: 50%;
                height: 50px;
                font-family: PingFang SC;
                font-size: 18px;
                font-weight: 400;
                line-height: 25px;
                text-align: left;
            }
            .top-box {
                width: 50%;
                height: 50px;
                display:block;
                font-family: PingFang SC;
                font-size: 12px;
                font-weight: 400;
                text-align: right;
                color: rgba(102, 102, 102, 1);
                .top-item {
                    line-height: 25px;
                }
            }
        }
        .sheet-box{
            margin-top: 10px;
            width: 100%;
            height: calc(100% - 110px);
        }
        .bottom {
            margin: 10px 0;
            display: flex;
            justify-content: space-between;
            .bottom-item {
                color: rgba(51, 51, 51, 1);
                font-size: 10px;
                font-weight: 400;
                line-height: 16px;
                text-align: center;
                img {
                    width: 20px;
                    height: 20px;
                }
            }
        }
    }
}
</style> 
