<script setup name="sharedDetail">
import {nextTick, onMounted, ref, computed, getCurrentInstance} from 'vue'
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 {getStaticImg} from '@/hooks/common.js'
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)
let showPicker = ref(false)
let showVersionPicker = ref(false)
const chartList = ref([])
const sheetActions = computed(() => {
    const list = [
        { label: globalProperties.$t('shared_table.refresh'), types:'flushed', src: getStaticImg('table/flushed.png'), isAuth: etaTablePermission.etaTable_customize_balance_refresh},
        { label: globalProperties.$t('shared_table.download'), types:'download', src: getStaticImg('table/download.png'), isAuth:etaTablePermission.etaTable_customize_balance_download},
        { label: globalProperties.$t('shared_table.delete'), types:'delete', src: getStaticImg('table/delete.png'), isAuth: etaTablePermission.etaTable_customize_balance_del},
    ]
    if (chartList.value && chartList.value.length > 0) list.unshift({ label: globalProperties.$t('shared_table.chart'), types:'chart', src: getStaticImg('table/chart.png'), isAuth: etaTablePermission.etaTable_customize_balance_edit })
    return list
})
const customFieldName = {
    text: 'ExcelName',
    value: 'ExcelInfoId',
};
const customVersionFieldName = {
    text: 'VersionName',
    value: 'UniqueCode',
};
const downExcelFileUrl = computed(() => {
    let url = `${
    import.meta.env.VITE_APP_API_URL
    }/datamanage/excel_info/table/download?${localStorage.getItem("token")}`;
    return url;
})

onMounted(() => {
    getVersionList()
    getChildTable()
})
//获取表格列表
async function getExcelDetail( source = 'refresh', ExcelInfoId = '' ){
    const detailReq = {
        ExcelInfoId: ExcelInfoId,
    }
    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
}

// 获取关联图库列表

async function getChartList(ExcelInfoId){
    const res = await apiSheet.getBalanceChartData({
        ExcelInfoId
    })
    if(res.Ret!==200) return 
    chartList.value = res.Data.List||[]
}

//更多操作
function handleActionClick(item){
    switch(item.types){
        case 'flushed':
            getChildTable()
            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 'chart':
            goChart()
            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;
    }
}

const columns = [
    { text: '杭州', value: 'Hangzhou' },
    { text: '宁波', value: 'Ningbo' },
    { text: '温州', value: 'Wenzhou' },
    { text: '绍兴', value: 'Shaoxing' },
    { text: '湖州', value: 'Huzhou' },
];
const versionOpts = ref([])
const childTableOpts = ref([])
const fieldValue = ref('表格名');
const fieldValueVersion = ref('版本');

// 平衡表获取版本列表
function getVersionList(){
    apiSheet.balanceTableVersion({ExcelInfoId: route.query.id,}).then(res=>{
        if(res.Ret === 200){
            const arr = res.Data.List || []
            versionOpts.value = arr
        }
    })
}

// 平衡表获取子表列表
function getChildTable(){
    apiSheet.getBalanceChildTable({ParentId: route.query.id,}).then(res=>{
        if(res.Ret === 200){
            const arr = res.Data.List || []
            childTableOpts.value = arr
            getExcelDetail( 'load', arr[0] ? arr[0].ExcelInfoId : route.query.id)
            getChartList(arr[0] ? arr[0].ExcelInfoId : route.query.id)
        }
    })
}

// 平衡表选择器
const onConfirm = ({ selectedOptions }) => {
    showPicker.value = false;
    fieldValue.value = selectedOptions[0].ExcelName;
    getExcelDetail( 'load', selectedOptions[0].ExcelInfoId)
};

// 版本选择器
const onConfirmVersion = ({ selectedOptions }) => {
    showVersionPicker.value = false;
    fieldValueVersion.value = selectedOptions[0].VersionName;
    getExcelDetail( 'load', selectedOptions[0].ExcelInfoId)
};

// 关联图表页
function goChart () {
    router.push({ path: '/balance/chart', query: { id: queryData.value.ExcelInfoId, name: queryData.value.ExcelName } });
}
</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>
                <!-- <div class="top-item"></div> -->
            </div>
        </div>
        <div class="filter-box">
            <div class="filter-item">
                <div class="filter-select" @click.stop="showPicker=true">
                    <div class="filter-value">
                        {{ fieldValue }} 
                    </div> 
                    <van-icon name="arrow"/>
                </div>
            </div>
            <div class="filter-item">
                <div class="filter-select"  @click.stop="showVersionPicker=true">
                    <div class="filter-value">
                        {{ fieldValueVersion }} 
                    </div> 
                    <van-icon name="arrow"/>
                </div>
            </div>
            <!-- <div class="top-item"><van-icon name="chart-trending-o" size="22" @click.stop="goChart"v-if="queryData.Source === 5" /> <van-icon name="more-o" size="22" @click.stop="showMoreAction=true"/></div> -->
        </div>
        <div class="sheet-box" v-if="queryData.UniqueCode">
            <iframe :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>

        <!-- 平衡表选择器 -->
        <van-popup v-model:show="showPicker" round position="bottom">
            <van-picker
                :columns="childTableOpts"
                @cancel="showPicker = false"
                @confirm="onConfirm"
                :columns-field-names="customFieldName"
            />
        </van-popup>
        <!-- 版本选择器 -->
        <van-popup v-model:show="showVersionPicker" round position="bottom">
            <van-picker
                :columns="versionOpts"
                @cancel="showVersionPicker = false"
                @confirm="onConfirmVersion"
                :columns-field-names="customVersionFieldName"
            />
        </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;
    }
    .filter-box {
        font-size: 28px;
        width: 100%;
        // height: 84px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        .filter-item {
            margin: 10px 0;
            width: 49%;
            height: 84px;
            display: flex;
            align-items: center;
            border-radius: 12px;
            justify-content: space-between;
            .filter-select {
                width: 100%;
                height: 72px;
                border-radius: 12px;
                font-size: 28px;
                font-weight: 400;
                padding: 0 16px;
                display: flex;
                align-items: center;
                justify-content: space-between;
                color: rgba(0, 82, 217, 1);
                background: rgba(242, 243, 255, 1);
                .filter-value {
                    line-height: 72px;
                    text-align: center;
                }
            }
        }
        .top-item {
            width: 10%;
            height: 60px;
            display: flex;
            justify-content: space-around;
            align-items: center;
        }
    }
    .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% - 300px);
    }
    .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 {
        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) {
        .filter-box {
            width: 50%;
            font-size: 16px;
            height: 30px;
            position: absolute;
            left: 12px;
            bottom: 18px;
            .filter-item {
                width: 49%;
                height: 30px;
                .filter-select {
                    height: 30px;
                    border-radius: 6px;
                    font-size: 14px;
                }
            }
            .top-item {
                height: 30px;
            }
        }
    }
}
@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% - 125px);
        }
        .bottom {
            width: 30%;
            position: absolute;
            right: 12px;
            bottom: 12px;
            display: flex;
            justify-content: space-around;
            .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> 
