<script setup name="DataEDBIndex">
import {computed, reactive,ref, watch} from 'vue'
import apiDataEDB from '@/api/dataEDB'
import {apiCommonSetSysConfig,apiGetLanguageConfig} from '@/api/common'
import EDBClassify from './components/EDBClassify.vue'
import { showDialog, showSuccessToast, showToast } from 'vant'
import {useRouter} from 'vue-router'
import {useCachedViewsStore} from '@/store/modules/cachedViews'
import langIconZH from '@/assets/imgs/chartETA/lang-icon.png'
import langIconEN from '@/assets/imgs/chartETA/langEn-icon.png'
import { useNoAuth } from '@/hooks/useNoAuth'
import {edbDataBtn,useAuthBtn} from '@/hooks/useAuthBtn'
const {checkAuthBtn} = useAuthBtn()

const cachedViewsStore=useCachedViewsStore()
const router=useRouter()

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'
        // 修改分类的语言显示
        classifyPopIns.value.langTypeChange(langType.value)
    }
}
getLangType()
//设置语言
async function langTypeChange(){
    const res=await apiCommonSetSysConfig({
        ConfigCode: 'edb_language',
		ConfigValue: langType.value === 'en' ? 'CN' : 'EN'
    })
    if(res.Ret===200){
        showSuccessToast('设置成功')
        langType.value=langType.value === 'en' ? 'zh' : 'en'
        classifyPopIns.value.langTypeChange(langType.value)
    }
}

//根据权限决定actions
const actions = computed(()=>{
    let actionArr = []
    if(checkAuthBtn(edbDataBtn.edbData_addEdb)){
        actionArr.push({
            name:'添加指标',
            path:'/dataEDB/addbaseEDB'
        })
    }
    if(checkAuthBtn(edbDataBtn.edbData_calcuEdb)){
        actionArr.push({
            name:'计算指标',
            path:'/dataEDB/calculate/index'
        })
    }
    if(checkAuthBtn(edbDataBtn.edbData_replaceEdb)){
        actionArr.push({
                name:'替换指标',
                path:'/dataEDB/replaceEDB'
            })
    }
    return actionArr
})

const listState = reactive({
    list:[],
    page:1,
    pageSize:20,
    finished:false,
    loading:false,
    total:0,
    activeClassifyName:'',//当前选中的分类名称
    activeClassifyId:0,
})
async function getEDBList(){
    listState.loading=true
    const res=await apiDataEDB.edbChartList({
        PageSize:listState.pageSize,
        CurrentIndex:listState.page,
        ClassifyId:listState.activeClassifyId
    })
    listState.loading=false 
    if(res.Ret===200){ 
        const arr=res.Data.List||[]
        listState.list=[...listState.list,...arr]
        listState.total=res.Data.Paging.Totals
        listState.finished=res.Data.Paging.IsEnd
    }
}
getEDBList()
// 触底加载
function onLoad(){
    listState.page++
    getEDBList()
}
// 刷新列表
function refreshEBDList(){
    listState.page=1
    listState.list=[]
    listState.finished=false
    getEDBList()
}

//基础操作
const showActionPop=ref(false)
async function handleSelectActionOpt(e){
    if(e.path){
        // 替换指标要做校验
        if(e.name==='替换指标'){
            const res=await apiDataEDB.replaceEDBCheck()
            if(res.Ret!==200) return
            if(res.Data!==2){
                showDialog({
                    title:'提示',
                    message: '当前正在替换中，请耐心等待',
                })
                return
            }
        }
        router.push(e.path)
        return
    }
    showToast('敬请期待')
}

// 分类弹窗
const classifyPopIns=ref(null)
const showClassifyPop=ref(false)
function handleSelectClassifyChange(e){
    listState.activeClassifyName=e.selectClassifyNameStr
    listState.activeClassifyId=e.selectClassifyId
}
watch(
    ()=>listState.activeClassifyId,
    ()=>{
        listState.page=1
        listState.list=[]
        listState.finished=false
        listState.total=0
        getEDBList()
    }
)

// 单个指标操作数据
const edbOptState=reactive({
    show:false,
    data:null,
})
watch(
    ()=>edbOptState.show,
    (n)=>{
        if(!n){
            edbOptState.data=null
        }
    }
)
//图表option check
function checkOption(item){
    let optionArr = []
    if(seeComputeEDBInfo(item)&&checkAuthBtn(edbDataBtn.edbData_checkCalcChart)){
        optionArr.push('查看')
    }
    if(item.Button.ShowEdbRelation&&checkAuthBtn(edbDataBtn.edbData_checkRelatedEdb)){
        optionArr.push('关联指标')
    }
    if(item.Button.ShowChartRelation&&checkAuthBtn(edbDataBtn.edbData_checkRelatedChart)){
        optionArr.push('关联图表')
    }
    if(item.Button.MoveButton){
        optionArr.push('移动至')
    }
    return optionArr.length
}
function handleShowEdbOpt(item){
    edbOptState.data=item

    edbOptState.show=true
}
// 控制指标操作中的计算指标查看
function seeComputeEDBInfo(data){
    return data?.EdbType===2&&![58,59,67,68].includes(data?.Source)
}


const activeEditEDBData=ref(null)//当前编辑的指标项数据
const showEditBaseEDB=ref(false)// 显示编辑基础指标
// 指标操作
function handleEDBOpt(type,data){
    // 移动至
    if(type==='move'){
        handleShowEDBMove(data)
    }

    //查看关联的图表
    if(type==='relationChart'){
        router.push({
            path:'/dataEDB/RelationChart',
            query:{
                edbInfoId:data.EdbInfoId
            }
        })
    }

    //查看关联指标
    if(type==='relationEDB'){
        router.push({
            path:'/dataEDB/relationEDB',
            query:{
                edbInfoId:data.EdbInfoId
            }
        })
    }

    //查看计算指标
    if(type==='see'){
        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:'preview'
            }
        })
    }

    edbOptState.show=false
}

// 移动指标
const edbMoveState=reactive({
    show:false,
    selectValue:'',
    options:[],
    edbInfoId:0,//要移动的分类id
    // tabIndex:2,
})
async function handleShowEDBMove(data){
    edbMoveState.options=classifyPopIns.value.classifyList
    edbMoveState.selectValue=data.ClassifyId
    edbMoveState.edbInfoId=data.EdbInfoId
    // edbMoveState.tabIndex=2
    edbMoveState.show=true
}
function handleEdbMoveSelectValueChange({value,selectedOptions,tabIndex}){
    // console.log(value,selectedOptions,tabIndex);
    // edbMoveState.tabIndex=tabIndex
}
async function handleConfirmEDBMove(){
    apiDataEDB.edbCatalogMove({
        ClassifyId:0,
        ParentClassifyId:edbMoveState.selectValue,
        EdbInfoId:edbMoveState.edbInfoId,
        PrevClassifyId:0,
        NextClassifyId:0,
        PrevEdbInfoId:0,
        NextEdbInfoId:0,
    }).then(res=>{
        if(res.Ret===200){
            showToast('移动成功!')
            refreshEBDList()
            edbMoveState.show=false
        }
    })
}

// 跳转详情
function handleEDBDetail(item){
    if(!item.HaveOperaAuth) return showToast(useNoAuth().edb)

    router.push({
        path:'/dataEDB/detail',
        query:{
            edbInfoId:item.EdbInfoId
        }
    })
}

async function goSearch(){
    // 删除指标搜索页的缓存
    await cachedViewsStore.removeCaches('DataEDBSearch')
    router.push('/dataEDB/search')
}

</script>

<template>
    <div class="dataEDB-index-page">
        <div class="top-sticky-box">
            <div class="search-box">
                <van-search 
                    shape="round" 
                    readonly 
                    placeholder="请输入指标ID/指标名称"
                    style="flex:1;padding-left:0"
                    @click-input="goSearch"
                />
                <div class="lang-icon icon" v-permission="edbDataBtn.edbData_switchEn">
                    <img :src="langType==='zh'?langIconZH:langIconEN" alt="" @click="langTypeChange">
                </div>
            </div>
            <div class="count-box">
                <div class="con">
                    <div class="van-ellipsis label">{{listState.activeClassifyName||'全部'}}</div>
                    <span class="num">共{{listState.total}}个指标</span>
                </div>
                <img class="menu-icon" src="@/assets/imgs/dataEDB/icon_menu.png" alt="" @click="showClassifyPop=true">
            </div>
        </div>
        <div class="edb-list-wrap">
            <van-list
                v-model:loading="listState.loading"
                :finished="listState.finished"
                :finished-text="listState.list.length>0?'没有更多了':'暂无数据'"
                :immediate-check="false"
                @load="onLoad"
            >
                <img v-if="listState.list.length==0&&listState.finished" class="list-empty-img" src="https://hzstatic.hzinsights.com/static/ETA_mobile/empty_img.png" alt="">
                <ul class="edb-list">
                    <li class="edb-item" v-for="item in listState.list" :key="item.EdbInfoId" @click="handleEDBDetail(item)">
                        <div class="van-multi-ellipsis--l2 name">{{langType==='zh'?item.EdbName:item.EdbNameEn||item.EdbName}}</div>
                        <van-image
                            class="img"
                            :src="!item.HaveOperaAuth?useNoAuth().noAuthImg:item.ChartImage"
                        />
                        <div>
                            <span class="time">{{item.CreateTime.substring(0,10)}}</span>
                            <svg 
                                class="opt-icon" 
                                xmlns="http://www.w3.org/2000/svg" 
                                width="28" 
                                height="28" 
                                viewBox="0 0 28 28" 
                                fill="none"
                                v-if="checkOption(item)&&item.HaveOperaAuth"
                                @click.stop="handleShowEdbOpt(item)"
                            >
                                <rect width="28" height="28" rx="4" :fill="item.EdbInfoId===edbOptState.data?.EdbInfoId?'#0052D9':'none'"/>
                                <path d="M14 19.25C14.9625 19.25 15.75 20.0375 15.75 21C15.75 21.9625 14.9625 22.75 14 22.75C13.0375 22.75 12.25 21.9625 12.25 21C12.25 20.0375 13.0375 19.25 14 19.25ZM12.25 14C12.25 14.9625 13.0375 15.75 14 15.75C14.9625 15.75 15.75 14.9625 15.75 14C15.75 13.0375 14.9625 12.25 14 12.25C13.0375 12.25 12.25 13.0375 12.25 14ZM12.25 7C12.25 7.9625 13.0375 8.75 14 8.75C14.9625 8.75 15.75 7.9625 15.75 7C15.75 6.0375 14.9625 5.25 14 5.25C13.0375 5.25 12.25 6.0375 12.25 7Z" :fill="item.EdbInfoId===edbOptState.data?.EdbInfoId?'#fff':'#333333'"/>
                            </svg>
                        </div>
                    </li>
                </ul>
            </van-list>
        </div>
        
    </div>

    <!-- 悬浮操作按钮 -->
    <div class="fixed-opt-btn" @click="showActionPop=true" v-if="actions.length">
        <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48" fill="none">
            <path fill-rule="evenodd" clip-rule="evenodd" d="M43.4855 12.7505L25.4062 2.31235C24.536 1.80995 23.4639 1.80995 22.5937 2.31235L4.5144 12.7505V33.6267C4.5144 34.6315 5.05046 35.5599 5.92065 36.0623L24 46.5005L42.0793 36.0623C42.9495 35.5599 43.4855 34.6315 43.4855 33.6267V12.7505ZM23.997 22.2665L9.01233 13.6153L24 4.96245L38.9859 13.6158L23.997 22.2665ZM25.5 24.8665L40.485 16.2149V33.5165L25.5 42.1666V24.8665ZM22.5 24.8665V42.1667L7.51198 33.5165V16.2132L22.5 24.8665Z" fill="white"/>
        </svg>
    </div>

    <!-- 基础操作弹窗 -->
    <van-action-sheet
        teleport="body"
        v-model:show="showActionPop"
        cancel-text="取消"
        close-on-click-action
        :actions="actions"
        @select="handleSelectActionOpt"
    >
    </van-action-sheet>

    <!-- 分类弹窗 -->
    <EDBClassify ref="classifyPopIns" v-model="showClassifyPop" @change="handleSelectClassifyChange"/>

    <!-- 指标的操作 -->
    <van-action-sheet
        teleport="body"
        v-model:show="edbOptState.show"
        cancel-text="取消"
        close-on-click-action
    >
        <template #default>
            <ul class="edb-opt-list">
                <!-- 计算指标查看 -->
                <li class="item" v-if="seeComputeEDBInfo(edbOptState.data)&&checkAuthBtn(edbDataBtn.edbData_checkCalcChart)" @click="handleEDBOpt('see',edbOptState.data)">查看</li>
                <li class="item" v-if="edbOptState.data?.Button.ShowEdbRelation&&checkAuthBtn(edbDataBtn.edbData_checkRelatedEdb)" @click="handleEDBOpt('relationEDB',edbOptState.data)">关联指标</li>
                <li class="item" v-if="edbOptState.data?.Button.ShowChartRelation&&checkAuthBtn(edbDataBtn.edbData_checkRelatedChart)" @click="handleEDBOpt('relationChart',edbOptState.data)">关联图表</li>
                <li class="item" v-if="edbOptState.data?.Button.MoveButton" @click="handleEDBOpt('move',edbOptState.data)">移动至</li>
            </ul>
        </template>
    </van-action-sheet>

    <!-- 指标移动 -->
    <van-popup 
        v-model:show="edbMoveState.show" 
        round 
        position="bottom"
    >
        <van-cascader
            v-model="edbMoveState.selectValue"
            title="移动至"
            :options="edbMoveState.options"
            :field-names="{text:'ClassifyName',value:'ClassifyId',children:'Children'}"
            @close="edbMoveState.show = false"
            @change="handleEdbMoveSelectValueChange"
        />
        <div style="width:300px;margin:0 auto;padding:20px 0">
            <van-button type="primary" round block @click="handleConfirmEDBMove">确定</van-button>
        </div>
    </van-popup>
</template>

<style lang="scss" scoped>
.dataEDB-index-page{
    min-height: 100vh;
    background-color: $page-bg-grey;
}
.fixed-opt-btn{
    cursor: pointer;
    width: var(--van-back-top-size);
    height: var(--van-back-top-size);
    position: fixed;
    right: var(--van-back-top-right);
    bottom: calc(var(--van-back-top-bottom) + var(--van-back-top-size) + 10px);
    background-color: $theme-color;
    border-radius: 50%;
    box-shadow: 0px 6px 28px 4px rgba(0, 0, 0, 0.05), 0px 16px 20px 2px rgba(0, 0, 0, 0.06), 0px 10px 10px -6px rgba(0, 0, 0, 0.1);
    svg{
        width: 40px;
        height: 40px;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%,-50%);
    }
}
.top-sticky-box{
    top: 0;
    left: 0;
    right: 0;
    z-index: 99;
    position: sticky;
    background-color: #fff;
    .search-box{
        display: flex;
        align-items: center;
        padding: 20px $page-padding;
        border-bottom: 1px solid $border-color;
        :deep(.van-search){
            padding: 0;
        }
        .lang-icon{
            cursor: pointer;
            margin-left: 10px;
            width: 70px;
            height:70px;
            background-color: #F2F3FF;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            img{
                width:45px;
                height:45px;
            }
        }
    }
    .count-box{
        display: flex;
        align-items: center;
        padding: 20px $page-padding;
        .con{
            flex: 1;
            display: flex;
            overflow: hidden;
            .lable{
                flex: 1;
            }
            .num{
                color: $font-grey_999;
                margin-left: 12px;
                flex-shrink: 0;
            }
        }
        .menu-icon{
            cursor: pointer;
            width: 48px;
            height: 48px;
            flex-shrink: 0;
            margin-left: 10px;
        }
    }
}
.edb-list-wrap{
    padding: 32px $page-padding;
    .edb-list{
        display: flex;
        justify-content: space-between;
        flex-wrap: wrap;
        gap: 30px 0;
        .edb-item{
            cursor: pointer;
            width: 326px;
            border-radius: 8px;
            background: #FFF;
            box-shadow: 0px 0px 6px 1px rgba(0, 0, 0, 0.08);
            padding: 10px;
            .name{
                min-height: 70px;
            }
            .img{
                width: 100%;
                height: 220px;
                margin: 14px 0;
            }
            .time{
                font-size: 24px;
            }
            .opt-icon{
                cursor: pointer;
                float: right;
                width: 28px;
                height: 28px;
            }
        }
    }
    
}
.edb-opt-list{
    .item{
        font-size: 14PX;
        text-align: center;
        line-height: 44PX;
        border-bottom: 1px solid $border-color;
    }
    .color-blue{
        color: $theme-color;
    }
    .color-red{
        color: $theme-red;
    }
}

@media screen and (min-width:$media-width){
    .fixed-opt-btn{
        bottom: calc(var(--van-back-top-bottom) + var(--van-back-top-size) + 10px);
        svg{
            width: 20px;
            height: 20px;
        }
    }
    .top-sticky-box{
        top: 60px;
        .search-box{
            padding: 20px $page-padding;
            .lang-icon{
                margin-left: 10px;
                width: 35px;
                height: 35px;
                img{
                    width: 23px;
                    height: 23px;
                }
            }
        }
        .count-box{
            padding: 20px $page-padding;
            .con{
                .num{
                    margin-left: 12px;
                }
            }
            .menu-icon{
                width: 30px;
                height: 30px;
            }
        }
    }
    .edb-list-wrap{
        padding: 32px $page-padding;
        .edb-list{
            gap: 15px;
            justify-content: flex-start;
            .edb-item{
                width: 308px;
                border-radius: 8px;
                padding: 10px;
                .name{
                    min-height: 36px;
                }
                .img{
                    height: 220px;
                    margin: 14px 0;
                }
                .time{
                    font-size: 14px;
                }
                .opt-icon{
                    width: 28px;
                    height: 28px;
                }
            }
        }
    }
}

</style>