<script setup>
import {ref,reactive,watch, computed} from 'vue'
import { useRoute, useRouter } from "vue-router";
import SelectEDBClassify from '../components/SelectEDBClassify.vue'
import SelectEDBUnit from '../components/SelectEDBUnit.vue'
import SelectEDBFrequency from '../components/SelectEDBFrequency.vue'
import SeeEDBDataList from './components/SeeEDBDataList.vue'
import SelectEDB from './components/SelectEDB.vue'
import EDBHistory from '@/views/dataEDB/components/EDBHistory.vue'
import {calculateTypeTipsMap} from '../util/config'
import { showToast,showDialog  } from 'vant';
import apiDataEDB from '@/api/dataEDB'
import {useToHistoryPage} from '@/hooks/edb/useToHistoryPage'
const {toHistoryPage} = useToHistoryPage()
const route=useRoute()
const router=useRouter()

const letterOpts = [];//字母数据
function initLetterOpt(){
    for(let i=0;i<26;i++){
        letterOpts.push(String.fromCharCode(65+i));
    }
}
initLetterOpt()

//公式说明
const showTips=ref(false)
const tipsContent=ref(calculateTypeTipsMap.get(['toMonthSeason','accumulate'].includes(route.query.source)? route.query.source: Number(route.query.source))||'')

//提交计算按钮文字
function getCalculateBtnText(){
    let str='生成计算指标'
    const btnTextMap=new Map([
		[5,'转月值计算'],
		[6,'同比值计算'],
		[7,'同差值计算'],
		[8,'移动平均计算'],
		[12,'环比值计算'],
		[13,'环差值计算'],
		[14,'升频计算'],
		[61,'转季值计算'],
		[62,'累计值计算'],
		[63,'年初至今计算'],
        [72,'指数修匀计算'],
        [75,'日均值计算'],
	])
    str=btnTextMap.get(source.value)

    return str
}

const source=ref(0)//计算类型
const tabsArr=ref([])
// tab切换
function handleTabChange(){
    edbList.value=[
        {
            tag:letterOpts[0],
            edbData:null,
            name:'',
            unit:'',
            classify:'',
            classifyName:'',
            frequency:'',
            numberN:1,
            alphaVal:'',
        },
        {
            tag:letterOpts[1],
            edbData:null,
            name:'',
            unit:'',
            classify:'',
            classifyName:'',
            frequency:'',
            numberN:1,
            alphaVal:'',
        }
    ]
}
// 初始化
function init(){
    // 累计值转月/季值
    if(route.query.source==='toMonthSeason'){
        tabsArr.value=[{ label: '累计值转月值',key: 5 },{ label: '累计值转季值',key: 61 }]
        source.value=5
    }else if(route.query.source==='accumulate'){//累计值
        tabsArr.value=[{ label: '累计值',key: 62 },{ label: '年初至今累计值',key: 63 }]
        source.value=62
    }else{
        tabsArr.value=[]
        source.value=Number(route.query.source)
    }

}
init()

// 指标列表
const activeTag=ref(letterOpts[0])
const edbList=ref([
    {
        tag:letterOpts[0],
        edbData:null,
        name:'',
        unit:'',
        classify:'',
        classifyName:'',
        frequency:'',
        numberN:1,
        alphaVal:'',
    },
    {
        tag:letterOpts[1],
        edbData:null,
        name:'',
        unit:'',
        classify:'',
        classifyName:'',
        frequency:'',
        numberN:1,
        alphaVal:'',
    }
])
function handleAddEdbList(){
    if(edbList.value.length>=26){
        showToast('添加指标个数已达上限')
        return
    }
    let tag = edbList.value[edbList.value.length-1].tag;
	let index = letterOpts.findIndex(item => item === tag);
	const item = {
		tag: letterOpts[index+1],
        edbData:null,
        name:'',
        unit:'',
        classify:'',
        classifyName:'',
        frequency:'',
        numberN:1,
        alphaVal:'',
	};
	edbList.value.push(item);
}
function handleDeleteEDBItem(index){
    if(index===currentEdbInfoIndex.value){
        activeTag.value=edbList.value[0].tag
    }
    edbList.value.splice(index, 1)

}
// 当前操作指标的下标
const currentEdbInfoIndex=computed(()=>{
    return edbList.value.findIndex(item=>item.tag===activeTag.value)
})

// 选择指标
const showSelectEDB=ref(false)
function handleConfirmSelectEDB(e){
    edbList.value[currentEdbInfoIndex.value].edbData=e
    const obj=setBaseInfo(e,edbList.value[currentEdbInfoIndex.value])
    edbList.value[currentEdbInfoIndex.value].name=obj.targetName
    edbList.value[currentEdbInfoIndex.value].unit=obj.unit
    edbList.value[currentEdbInfoIndex.value].frequency=obj.frequency

    if([72,75].includes(source.value)){//指数修匀设置默认指标目录为选择的指标目录
        selectEDBClassifyINS.value?.getSelectClassifyOpt(e.ClassifyId)//获取选择的分类目录
    }
}

// 选择指标后设置基础信息
function setBaseInfo(obj,list){
    switch(source.value){
        case 6:
        case 32:
            return {
                targetName: `${obj.EdbName}同比`,
				unit: '无',
				frequency: obj.Frequency
            }
        case 7: 
		case 33: 
			return {
				targetName: `${obj.EdbName}同差`,
				unit: obj.Unit,
				frequency: obj.Frequency
			}
		case 8: 
		case 39: 
			return {
				targetName: obj.EdbName,
				unit: obj.Unit,
				frequency: obj.Frequency
			}
		case 14:
		case 45: 
            return {
				targetName: obj.EdbName,
				unit: obj.Unit,
				frequency: '日度'
			}
		case 12:
		case 43: 
			return{
				targetName: `${obj.EdbName}${list.n_num}${obj.Frequency.slice(0,1)}环比`,
				unit: '无',
				frequency: obj.Frequency
			}
		case 13: 
		case 44: 
			return {
				targetName: `${obj.EdbName}${list.n_num}${obj.Frequency.slice(0,1)}环差`,
				unit: '无',
				frequency: obj.Frequency
			}
		case 5:
		case 42: 
			return {
				targetName: obj.EdbName,
				unit: obj.Unit,
				frequency: obj.Frequency
			}
		case 61:
		case 64: 
			return {
			    targetName: obj.EdbName,
				unit: '无',
				frequency: '季度'
			}
		case 62:
		case 65: 
			return {
				targetName: obj.EdbName,
				unit: '无',
				frequency: obj.Frequency
			}
		case 63:
		case 66: 
			return {
				targetName: obj.EdbName,
				unit: '无',
				frequency: obj.Frequency
			}
        case 72:
            return {
                targetName:`${obj.EdbName}指数修匀`,
                unit: obj.Unit,
				frequency: obj.Frequency
            }
        case 75:
            return {
                targetName: `${obj.EdbName}日均值`,
                unit: obj.Unit,
                frequency: obj.Frequency
            }
    }
}

//查看指标数据详情
const showSeeEDBDataList=ref(false)

const edbNameInputFocus=ref(false)//指标名称输入框聚焦
const numberNInputFocus=ref(false)//N值输入框聚焦
const alphaValInputFocus=ref(false)//alpha值输入框聚焦

// 选择单位
const showSelectUnit=ref(false)
function onConfirmSelectUnit(value){
    edbList.value[currentEdbInfoIndex.value].unit=value
}

//选择分类
const showSelectClassify=ref(false)
const selectEDBClassifyINS=ref(null)
function handleConfirmClassify({value,selectedOptions}){
    if(selectedOptions.length===0){
        edbList.value[currentEdbInfoIndex.value].classify=''
        edbList.value[currentEdbInfoIndex.value].classifyName=''
        return
    }
    edbList.value[currentEdbInfoIndex.value].classify=value
    const textArr=selectedOptions.map(item=>item.ClassifyName)
    edbList.value[currentEdbInfoIndex.value].classifyName=`${textArr.join('/')}`
}

//选择频度
const showSelectFrequency=ref(false)
function handleConfirmFrequency(value){
    edbList.value[currentEdbInfoIndex.value].frequency=value
}


// 提交计算
const saveBtnLoading=ref(false)
async function handleSave(){
    const filterArr = edbList.value.filter(item=> item.edbData);
    if(!filterArr.length){
        showToast('请选择指标')
        return
    }
    const isEnough=filterArr.every(item => item.name&&item.unit&&item.classify&&item.frequency)
    console.log(isEnough);
    if(!isEnough){
        showToast('请填写完整信息')
        return
    }
    const params=filterArr.map(item => {
        return {
            CalculateId: item.tag,
            CalculateInfo: {
                ClassifyId: item.classify,
                EdbName: item.name,
                Formula: [72].includes(source.value)?String(item.alphaVal) : String(item.numberN),
                Frequency:item.frequency,
                FromEdbInfoId: item.edbData.EdbInfoId,
                MoveFrequency: "天",
                MoveType: 1,
                Source: source.value,
                Unit: item.unit
            }
        }
    })
    console.log(params);
    // 判断alpha的值
    if([72].includes(source.value)){
        let msg=[]
        params.forEach(item=>{
            if(item.CalculateInfo.Formula<=0||item.CalculateInfo.Formula>=1){
                msg.push(item.CalculateId)
            }

        })
        if(msg.length){
            showDialog({
                allowHtml:true,
                message:'指标'+msg.join('、')+'的alpha值不合法'
            })
            return
        }
    }

    saveBtnLoading.value=true
    const res=await apiDataEDB.batchAddCalculateEDB(params)
    saveBtnLoading.value=false
    if(res.Ret===200){
        const { Fail,Success } = res.Data;
        if(Fail.length){
            let message=''
            Fail.forEach(item=>{
                message+=`${item.CalculateId}:${item.Msg}\n`
            })
            showDialog({
                allowHtml:true,
                message
            }).then(()=>{})
            // 处理失败的
            const failTagArr = Fail.map(_ =>_.CalculateId);
            const arr=edbList.value.filter(_ => failTagArr.includes(_.tag))
            console.log(arr);
            edbList.value=edbList.value.filter(_ => failTagArr.includes(_.tag))
            activeTag.value=edbList.value[0].tag
        }else{
            showToast('添加成功')
            setTimeout(() => {
                router.replace({
                    path:'/dataEDB/detail',
                    query:{
                        edbInfoId:Success[0].EdbInfoId
                    }
                })
            }, 1500);
        }
    }
}

// 显示指标溯源
const showEDBHistory=ref(false)
const edbHistoryId=ref(0)
function handleShowEDBHistory(item){
    //计算指标打开弹窗,基础指标打开新页面
    if(item.EdbType===2){
        /* edbHistoryId.value=item.EdbInfoId
        showEDBHistory.value=true */
        toHistoryPage(item.EdbInfoId)

    }else{
        const routerEl=router.resolve({
            path:'/dataEDB/detail',
            query:{
                edbInfoId:item.EdbInfoId
            }
        })
        window.open(routerEl.href,'_blank')
    }
}


</script>

<template>
    <div class="batch-calculate-wrap">
        <div class="sticky-top-wrap">
        <van-tabs 
            v-model:active="source" 
            border 
            title-active-color="#0052D9" 
            title-inactive-color="#333" 
            line-width="16px"
            @change="handleTabChange"
            v-if="tabsArr.length"
        >
            <van-tab 
                :title="tab.label" 
                :name="tab.key" 
                v-for="tab in tabsArr" 
                :key="tab.key"
            />
        </van-tabs>
        <section class="section edblist-tag-list">
            <ul class="tag-list">
                <li
                    :class="['item-tag',activeTag===item.tag?'item-tag_active':'']"
                    v-for="(item,index) in edbList" 
                    :key="item.tag"
                    @click="activeTag=item.tag"
                >
                    <span>{{item.tag}}</span>
                    <svg-icon name="close" @click.stop="handleDeleteEDBItem(index)" v-if="index>1"></svg-icon>
                </li>
            </ul>
            <van-button type="primary" size="small" @click="handleAddEdbList">添加指标</van-button>
        </section>
        </div>
        <section class="section form-wrap">
            <van-field
                label="选择指标"
                right-icon="arrow"
                @click-input="showSelectEDB=true"
            >
                <template #left-icon>
                    <div class="left-icon">
                        <svg-icon name="edb-history-tag" size="24px" v-if="edbList[currentEdbInfoIndex].edbData" @click="handleShowEDBHistory(edbList[currentEdbInfoIndex].edbData)"/>
                    </div>
                </template>
                <template #input>
                    <div class="select-edbinfo-box">
                        <div class="edb-info" v-if="edbList[currentEdbInfoIndex].edbData">
                            <span class="name">{{edbList[currentEdbInfoIndex].edbData.EdbName}}</span>
                            <span class="time">{{edbList[currentEdbInfoIndex].edbData.StartDate}}至{{edbList[currentEdbInfoIndex].edbData.EndDate}}</span>
                        </div>
                        <span class="placeholder" v-else>请选择指标</span>
                    </div>
                </template>
            </van-field>
            <div class="edbinfo-box">
                <div class="van-cell__title">已选指标</div>
                <div v-if="!edbList[currentEdbInfoIndex].edbData">
                    <img class="list-empty-img" src="https://hzstatic.hzinsights.com/static/ETA_mobile/empty_img.png" alt="">
                    <p style="text-align:center;color:#999">暂无指标</p>
                </div>
                <div class="info-box" v-else>
                    <h2 class="name">{{edbList[currentEdbInfoIndex].edbData?.EdbName}}</h2>
                    <ul class="info-list">
                        <li class="info-item">ID：{{edbList[currentEdbInfoIndex].edbData.EdbCode}}</li>
                        <li class="info-item">起始时间：{{edbList[currentEdbInfoIndex].edbData.StartDate}}</li>
                        <li class="info-item">频度：{{edbList[currentEdbInfoIndex].edbData.Frequency}}</li>
                        <li class="info-item">更新时间：{{edbList[currentEdbInfoIndex].edbData.ModifyTime}}</li>
                        <li class="info-item">单位：{{edbList[currentEdbInfoIndex].edbData.Unit}}</li>
                        <li class="info-item">数据来源：{{edbList[currentEdbInfoIndex].edbData.SourceName}}</li>
                    </ul>
                    <div style="text-align:right">
                        <van-button color="#0052D9" size="small" @click="showSeeEDBDataList=true">查看数据</van-button>
                    </div>
                </div>
            </div>
            <div>
                <van-field 
                    v-model="edbList[currentEdbInfoIndex].name" 
                    label="指标名称" 
                    placeholder="指标名称"
                    input-align="right"
                    required
                    @focus="edbNameInputFocus=true"
                    @blur="edbNameInputFocus=false"
                >
                    <template #right-icon>
                        <svg-icon class="edit-icon" name="edit" :color="edbNameInputFocus?'#0052D9':'#333333'"/>
                    </template>
                </van-field>
                <van-field 
                    :modelValue="edbList[currentEdbInfoIndex].unit"
                    readonly
                    label="单位" 
                    placeholder="请选择单位"
                    input-align="right"
                    right-icon="arrow"
                    required
                    @click-input="showSelectUnit=true"
                    :disabled="[6,7,32,33,75].includes(source)"
                />
                <van-field 
                    :modelValue="edbList[currentEdbInfoIndex].classifyName"
                    readonly
                    label="指标目录" 
                    placeholder="请选择指标目录"
                    input-align="right"
                    right-icon="arrow"
                    required
                    @click-input="showSelectClassify=true"
                />
                <van-field 
                    :modelValue="edbList[currentEdbInfoIndex].frequency"
                    readonly
                    label="频度" 
                    placeholder="请选择指标频度"
                    input-align="right"
                    right-icon="arrow"
                    required
                    @click-input="showSelectFrequency=true"
                    :disabled="[6,7,32,33,5,42,61,64,63,66,75].includes(source)"
                />
                <van-field
                    v-if="[8,12,13,39,43,44].includes(source)"
                    v-model.number="edbList[currentEdbInfoIndex].numberN" 
                    label="N等于" 
                    placeholder="请输入N数值"
                    input-align="right"
                    required
                    @focus="numberNInputFocus=true"
                    @blur="numberNInputFocus=false"
                >
                    <template #right-icon>
                        <svg-icon class="edit-icon" name="edit" :color="numberNInputFocus?'#0052D9':'#333333'"/>
                    </template>
                </van-field>
                <!-- 指数修匀 alpha 值 -->
                <van-field
                    v-if="[72].includes(source)"
                    v-model.number="edbList[currentEdbInfoIndex].alphaVal"
                    type="number"
                    label="alpha值" 
                    placeholder="请输入alpha值"
                    input-align="right"
                    required
                    @focus="alphaValInputFocus=true"
                    @blur="alphaValInputFocus=false"
                    :disabled="isPreview"
                >
                    <template #right-icon>
                        <svg-icon v-if="!isPreview" class="edit-icon" name="edit" :color="alphaValInputFocus?'#0052D9':'#333333'"/>
                    </template>
                </van-field>
            </div>
        </section>

        <div class="formula-intro-btn" @click="showTips=true">
            <svg-icon class="icon" name="warning"></svg-icon>
            <span>公式说明</span>
        </div>
        <div class="opt-btns">
            <van-button class="primary2" @click="$router.back()">取消</van-button>
            <van-button 
                type="primary" 
                :loading="saveBtnLoading"
                loading-text="计算中..."
                @click="handleSave"
            >{{getCalculateBtnText()}}</van-button>
        </div>
    </div>

    <!-- 选择指标 -->
    <SelectEDB v-model:show="showSelectEDB" @select="handleConfirmSelectEDB"/>

    <!-- 选择单位 -->
    <SelectEDBUnit v-model:show="showSelectUnit" @select="onConfirmSelectUnit"/>

    <!-- 选择分类 -->
    <SelectEDBClassify ref="selectEDBClassifyINS" :defaultId="edbList[currentEdbInfoIndex]?.classify" v-model:show="showSelectClassify" @select="handleConfirmClassify" />

    <!-- 选择频度 -->
    <SelectEDBFrequency v-model:show="showSelectFrequency" @select="handleConfirmFrequency"/>

    <!-- 查看指标数据 -->
    <SeeEDBDataList v-model:show="showSeeEDBDataList" :edbInfoId="edbList[currentEdbInfoIndex].edbData?.EdbInfoId" />

    <!-- 指标溯源 -->
    <EDBHistory v-model:show="showEDBHistory" :edbInfoId="edbHistoryId"/>

    <!-- 公式说明 -->
    <van-dialog 
        v-model:show="showTips" 
        :title="$route.query.name"
        confirmButtonText='知道啦'
    >
        <div class="edb-formula-tips-html-box" v-html="tipsContent"></div>
    </van-dialog>

</template>

<style lang="scss" scoped>
.batch-calculate-wrap{
    min-height: 90vh;
    background-color: $page-bg-grey;
    padding-bottom: 210px ;
    .sticky-top-wrap{
        position: sticky;
        top: 0;
        z-index: 10;
    }
}
.section{
    background-color: #fff;
    margin-bottom: 32px;
}
.edblist-tag-list{
    padding: 16px 32px;
    display: flex;
    .tag-list{
        margin-right: 20px;
        flex: 1;
        overflow-x: auto;
        display: flex;
        gap: 0 16px;
        &::-webkit-scrollbar{
            width: 0;
            height: 0;
        }
        .item-tag{
            display: flex;
            gap: 12px;
            align-items: center;
            box-sizing: border-box;
            padding: 6px 32px;
            border-radius: 1998px;
            background-color: #F3F3F3;
            span{
                line-height: 1;
            }
        }
        .item-tag_active{
            background-color: #F2F3FF;
            color: $theme-color;
        }
    }
}
.form-wrap{
    // .left-icon{
    //     width: 48px;
    //     height: 48px;
    // }
    :deep(.van-cell__right-icon){
        align-self: center;
        color: #333;
    }
    .select-edbinfo-box{
        width: 100%;
        text-align: right;
        .placeholder{
            color: var(--van-text-color-3);
        }
        .edb-info{
            display: flex;
            flex-direction: column;
        }
        .time{
            color: $font-grey_999;
            font-size: 24px;
        }
    }
    .edbinfo-box{
        padding: var(--van-cell-horizontal-padding);
        .info-box{
            margin-top: 14px;
            border-radius: 8px;
            border: 1px solid $border-color;
            box-shadow: $box-shadow;
            padding: 20px;
            .name{
                font-size: 32px;
                margin: 0 0 10px 0;
            }
            .info-list{
                display: flex;
                flex-wrap: wrap;
                gap: 10px 0;
                color: $font-grey;
                margin-bottom: 10px;
                .info-item{
                    width: 100%;
                    margin-bottom: 10px;
                }
            }
        }
    }
}

.formula-intro-btn{
    width: 180px;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 5px;
    color: $theme-color;
    line-height: 1;
    background-color: #fff;
    border-radius: 32px;
    margin-left: auto;
    margin-right: var(--van-cell-horizontal-padding);
    .icon{
        width: 24px;
        height: 24px;
    }
}
.opt-btns{
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #fff;
    z-index: 99;
    padding: 48px;
    display: flex;
    justify-content: space-between;
    .van-button{
        width: 48%;
        max-width: 300PX;
    }
}
@media screen and (min-width:$media-width){
    .batch-calculate-wrap{
        padding-bottom: 105px;
    }
    .section{
        margin-bottom: 16px;
    }
    .edblist-tag-list{
        padding: 8px 16px;
        .tag-list{
            margin-right: 10px;
            gap: 0 8px;
            .item-tag{
                gap: 6px;
                padding: 3px 16px;
            }
        }
    }

    .form-wrap{
        // .left-icon{
        //     width: 24px;
        //     height: 24px;
        // }
        .select-edbinfo-box{
            .time{
                font-size: 12px;
            }
        }
        .edbinfo-box{
            .info-box{
                margin-top: 7px;
                border-radius: 4px;
                padding: 10px;
                .name{
                    font-size: 16px;
                    margin: 0 0 5px 0;
                }
                .info-list{
                    gap: 5px 0;
                    margin-bottom: 5px;
                    .info-item{
                        margin-bottom: 5px;
                    }
                }
            }
        }
    }
    .formula-intro-btn{
        width: 90px;
        height: 30px;
        gap: 2px;
        border-radius: 16px;
        .icon{
            width: 12px;
            height: 12px;
        }
    }
    .opt-btns{
        padding: 24px;
        justify-content: center;
        gap: 10px;
    }
}
</style>