<script setup name="DataEDBDetail">
import {ref} from 'vue'
import apiDataEDB from '@/api/dataEDB'
import {apiGetLanguageConfig} from '@/api/common'
import EDBChartDetailVue from './components/EDBChartDetail.vue'
import EDBDataDetailVue from './components/EDBDataDetail.vue'
import EditBaseEDB from './components/EditBaseEDB.vue'
import SetEBDInfoEn from './components/SetEDBInfoEn.vue'
import SetEDBNewData from './components/SetEDBNewData.vue'
import EDBHistory from './components/EDBHistory.vue'
import { useRoute, useRouter } from 'vue-router'
import {showLoadingToast,showToast} from 'vant'
import {useCopyEdbData} from '@/hooks/edb/useCopyEdbData'
import {useEDBDelete} from './hooks/useEDBDelete'
import {useCachedViewsStore} from '@/store/modules/cachedViews'
import { useWindowSize } from '@vueuse/core'
import {edbDataBtn,useAuthBtn} from '@/hooks/useAuthBtn'
import {useToHistoryPage} from '@/hooks/edb/useToHistoryPage'
const {checkAuthBtn} = useAuthBtn()
const {toHistoryPage} = useToHistoryPage()
const { width } = useWindowSize()
const cachedViewsStore=useCachedViewsStore()
const {edbClassifyDelete} =useEDBDelete()
const {copyData} =useCopyEdbData()

const route=useRoute()
const router=useRouter()

const activeType=ref(route.query.showType||'chart')

const chartDetailIns=ref(null)//图表组件实例
const dataDetailIns=ref(null)//数据详情组件实例

const langType=ref('zh')
// 获取当前要显示的语言版本
async function getLangType(){
    const res=await apiGetLanguageConfig({SourceKey:'edb_language'})
    if(res.Ret===200){
        langType.value=res.Data==='CN'?'zh':'en'
    }
}
getLangType()

// 指标详情
const edbInfo=ref(null)
const edbDataAll=ref([])//指标的所有数据
//获取指标的按钮操作权限和详情
//由于指标详情接口中没有按钮权限 只能获取一下指标数据接口了
async function getEDBOptAuth(){
    const res=await apiDataEDB.edbDataList({
        EdbInfoId:route.query.edbInfoId,
        PageSize: 100000,
        CurrentIndex: 1,
    })
    if(res.Ret===200){
        edbInfo.value=res.Data.Item
        edbDataAll.value=res.Data.Item.DataList || []
    }
}
getEDBOptAuth()


// 调整上下限
function handleShowLimit(){
    chartDetailIns.value.handleShowLimitPop()
}

//点击复制
// 提前获取指标的所有数据用于复制（在getEDBOptAuth方法中一起获取）
// ios端无法在异步方法后设置剪切板内容
function handleCopyData(){
    copyData(edbDataAll.value)
}

//点击刷新
async function handleRefreshEDBInfo(){
    const LOADING = showLoadingToast ({
        message: "刷新中...",
        duration: 0,
        forbidClick: true,
    });
    const res=await apiDataEDB.edbRefresh({EdbInfoId:Number(route.query.edbInfoId)})
    LOADING.close()
    if(res.Ret===200){
        showToast({message:'刷新成功',type:'success'})
        if(activeType.value==='chart'){
            chartDetailIns?.value.getEDBDataList()
        }else{
            dataDetailIns?.value.refreshList()
        }
    }
}

//点击编辑
const showEditBaseEDB=ref(false)
function handleEdit(){
    const data=edbInfo.value
    // 基础指标
    if(data.EdbType===1 || [58,59,67,68].includes(data.Source)){
        showEditBaseEDB.value=true
    }
    // 计算指标
    if(data.EdbType === 2 && ![27,40,58,59].includes(data.Source)){
        if([81,82].includes(data.Source)){
            showToast('请在pc端操作')
            return
        }
        router.push({
            path:'/dataEDB/calculate/detail',
            query:{
                source:data.Source,
                name:data.SourceName,
                edbInfoId:data.EdbInfoId,
                type:'edit'
            }
        })
    }
    //代码运算
    if(data.Source===27){
        showToast('代码运算指标请在pc端操作')
    }
    //数据调整
    if(data.Source===40){
        showToast('数据调整指标请在pc端操作')
    }
}
//编辑基础指标成功回调
function handleEditBaseEdbSuccess(e){
    edbInfo.value.EdbName=e.EdbName
}

// 更多操作
const showMoreOpt=ref(false)

// 设置英文
const showSetEn=ref(false)

// 设置指标最新值
const showSetNewData=ref(false)

//指标溯源
const showEDBHistory=ref(false)

//删除指标
function handleEDBDelete(){
    edbClassifyDelete(edbInfo.value).then(async(res)=>{
        if(res===true){
            await cachedViewsStore.removeCaches('DataEDBIndex')
            router.back()
        }
    })
}

//基础指标全部刷新
async function handleRefreshBaseEDBData(){
    const LOADING = showLoadingToast ({
        message: "刷新中...",
        duration: 0,
        forbidClick: true,
    });
    const res=await apiDataEDB.refreshBaseEDBData({EdbInfoId:edbInfo.value.EdbInfoId})
    LOADING.close()
    if(res.Ret===200){
        if(activeType.value==='chart'){
            chartDetailIns?.value.getEDBDataList()
        }else{
            dataDetailIns?.value.refreshList()
        }
    }
}

//计算指标重新计算
async function handleCalculateReset(){
    const res=await apiDataEDB.calculateEDBReset({EdbInfoId:edbInfo.value.EdbInfoId})
    if(res.Ret===200){
        showToast(res.Msg)
        if(activeType.value==='chart'){
            chartDetailIns?.value.getEDBDataList()
        }else{
            dataDetailIns?.value.refreshList()
        }
    }
}

//保存图表上下限
function handleSave(){
    chartDetailIns?.value.handleSaveChartLimit()
}
function isMoreOptShow(){
    return checkAuthBtn(edbDataBtn.edbData_enNameSetting)
        || (edbInfo.value.Button.InsertNewDataButton&&checkAuthBtn(edbDataBtn.edbData_newestValue))
        || (edbInfo.value.EdbType===1&&checkAuthBtn(edbDataBtn.edbData_refreshAll))
        || (edbInfo.value.EdbType===2&&checkAuthBtn(edbDataBtn.edbData_edbSource))
        || (edbInfo.value.EdbType===2&&checkAuthBtn(edbDataBtn.edbData_calculateAgain))
        || (activeType.value==='chart'&&checkAuthBtn(edbDataBtn.edbData_saveEdb))
        || checkAuthBtn(edbDataBtn.edbData_deleteEdb)
}

</script>

<template>
    <div class="edb-detail-page" v-if="edbInfo">
        <div class="top-box">
            <div class="van-multi-ellipsis--l2 edb-name-box">{{langType==='zh'?edbInfo.EdbName:edbInfo.EdbNameEn||edbInfo.EdbName}}</div>
        </div>
        <van-tabs v-model:active="activeType" :offset-top="width>650?60:0" sticky line-width="16" title-active-color="#0052D9" title-inactive-color="#333">
            <van-tab title="图表详情" name="chart">
                <EDBChartDetailVue
                    ref="chartDetailIns" 
                    :edbInfo="edbInfo"
                    :langType="langType"
                />
            </van-tab>
            <van-tab title="数据详情" name="data">
                <EDBDataDetailVue
                    ref="dataDetailIns"
                    :edbInfo="edbInfo"
                    :langType="langType"
                />
            </van-tab>
        </van-tabs>
        <div class="fix-bottom-box">
            <div class="item" @click="handleRefreshEDBInfo" v-permission="edbDataBtn.edbData_update">
                <img class="icon" src="@/assets/imgs/report/icon_refresh.png" alt="">
                <span>刷新</span>
            </div>
            <div class="item" v-if="edbInfo.Button.OpButton&&checkAuthBtn(edbDataBtn.edbData_edit)" @click="handleEdit">
                <img class="icon" src="@/assets/imgs/dataEDB/icon_edit.png" alt="">
                <span>编辑</span>
            </div>
            <div class="item" v-if="activeType==='chart'&&checkAuthBtn(edbDataBtn.edbData_editLimit)" @click="handleShowLimit">
                <img class="icon" src="@/assets/imgs/myETA/icon_limit.png" alt="">
                <div>上下限</div>
            </div>
            <div class="item" v-if="activeType==='data'&&checkAuthBtn(edbDataBtn.edbData_copyData)" @click="handleCopyData">
                <img class="icon" src="@/assets/imgs/myETA/icon_copy.png" alt="">
                <div>复制</div>
            </div>
            <div class="item" @click="showMoreOpt=true" v-if="isMoreOptShow()">
                <img class="icon" src="@/assets/imgs/myETA/icon_menu.png" alt="">
                <div>更多</div>
            </div>
        </div>
    </div>

    <!-- 编辑基础指标 -->
    <EditBaseEDB 
        v-model="showEditBaseEDB" 
        :edbInfoId="edbInfo?.EdbInfoId"
        @success="handleEditBaseEdbSuccess"
    />

    <!-- 更多操作 -->
    <van-action-sheet
        teleport="body"
        v-model:show="showMoreOpt"
        cancel-text="取消"
        close-on-click-action
    >
        <template #default>
            <ul class="edb-opt-list">
                <li class="van-ellipsis item name">{{edbInfo.EdbName}}</li>

                <li class="item" 
                    v-if="checkAuthBtn(edbDataBtn.edbData_enNameSetting)"
                    @click="showSetEn=true">设置英文名称</li>
                <li class="item" 
                    v-if="edbInfo.Button.InsertNewDataButton&&checkAuthBtn(edbDataBtn.edbData_newestValue)"
                    @click="showSetNewData=true"
                >{{edbInfo.DataInsertConfig.Date?'编辑最新值':'添加最新值'}}</li>
                <li class="item" v-if="edbInfo.EdbType===1&&checkAuthBtn(edbDataBtn.edbData_refreshAll)" @click="handleRefreshBaseEDBData">全部刷新</li>
                <li class="item" v-if="edbInfo.EdbType===2&&checkAuthBtn(edbDataBtn.edbData_edbSource)" @click="toHistoryPage(edbInfo?.EdbInfoId)">指标溯源</li>
                <li class="item" v-if="edbInfo.EdbType===2&&checkAuthBtn(edbDataBtn.edbData_calculateAgain)" @click="handleCalculateReset">重新计算</li>  
                <li class="item" v-if="activeType==='chart'&&checkAuthBtn(edbDataBtn.edbData_saveEdb)" @click="handleSave">保存</li>
                <li class="item color-red" 
                    v-if="checkAuthBtn(edbDataBtn.edbData_deleteEdb)"
                    @click="handleEDBDelete">删除</li>
            </ul>
        </template>
    </van-action-sheet>

    <!-- 设置英文 -->
    <SetEBDInfoEn v-model:show="showSetEn" :edbInfo="edbInfo"/>

    <!-- 设置最新值 -->
    <SetEDBNewData v-model:show="showSetNewData" :edbInfo="edbInfo"/>

    <!-- 指标溯源 -->
    <EDBHistory v-model:show="showEDBHistory" :edbInfoId="edbInfo?.EdbInfoId" />
</template>

<style lang="scss" scoped>
:deep(.van-tabs__wrap){
    border-bottom: 1px solid $border-color;
}
.top-box{
    padding: $page-padding $page-padding 10px;
    .edb-name-box{
        font-size: 36px;
        line-height: 52px;
    }
}
.edb-detail-page{
    padding-bottom: 120px;
    // overflow-x: hidden;
}
.fix-bottom-box{
    position: fixed;
    height: 112px;
    border-top: 1px solid $border-color;
    z-index: 99;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    background-color: #fff;
    .item{
        cursor: pointer;
        flex: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        .icon{
            width: 40px;
            height: 40px;
        }
    }

}
.edb-opt-list{
    .item{
        font-size: 14PX;
        text-align: center;
        line-height: 44PX;
        border-bottom: 1px solid $border-color;
    }
    .name{
        font-weight: bold;
        font-size: 15PX;
    }
    .color-blue{
        color: $theme-color;
    }
    .color-red{
        color: $theme-red;
    }
}

@media screen and (min-width:$media-width){
    .top-box{
        padding: 20px $page-padding 10px;
        .edb-name-box{
            font-size: 18px;
            line-height: 27px;
        }
    }
    .edb-detail-page{
        padding-bottom: 70px;
    }
    .fix-bottom-box{
        height: 56px;
        .item{
            .icon{
                width: 24px;
                height: 24px;
            }
        }
    }
}
</style>