<script setup>
import {ref,reactive,watch} from 'vue'
import { useRoute, useRouter } from "vue-router";
import EDBHistory from '@/views/dataEDB/components/EDBHistory.vue'
import SelectEDB from './SelectEDB.vue'
import SelectEDBClassify from '../../components/SelectEDBClassify.vue'
import SelectEDBUnit from '../../components/SelectEDBUnit.vue'
import SelectEDBFrequency from '../../components/SelectEDBFrequency.vue'
import SeeEDBDataList from './SeeEDBDataList.vue'
import {calculateTypeTipsMap} from '../../util/config'
import { showToast } from 'vant';
import apiDataEDB from '@/api/dataEDB'
import { useWindowSize } from '@vueuse/core'

const { width } = useWindowSize()
const route=useRoute()
const router=useRouter()

const props=defineProps({
    edbInfo:{
        type:Object,
        default:null
    }
})

watch(
    ()=>props.edbInfo,
    ()=>{
        if(['edit','preview'].includes(route.query.type)){
            const fromEdbInfo=props.edbInfo.CalculateList[0]
            const edbInfoData=props.edbInfo.EdbInfoDetail
            searchEDBInfoByCode(fromEdbInfo.FromEdbCode)
            baseInfo.name=edbInfoData.EdbName
            baseInfo.unit=edbInfoData.Unit
            baseInfo.classify=edbInfoData.ClassifyId
            baseInfo.frequency=edbInfoData.Frequency
            if(edbInfoData.Source===51){//降频
                baseInfo.valueType=edbInfoData.CalculateFormula
            }
            if(edbInfoData.Source===35){//超季节性
                baseInfo.calendarType=edbInfoData.Calendar
            }
            if(edbInfoData.Source===22){//时间位移
                baseInfo.moveType=edbInfoData.MoveType
                baseInfo.moveUnit=edbInfoData.MoveFrequency
                baseInfo.moveVal=edbInfoData.CalculateFormula
            }
            if([8,12,13,35].includes(edbInfoData.Source)){
                baseInfo.numberN=Number(edbInfoData.CalculateFormula)
            }
            if([72].includes(edbInfoData.Source)){//指数修匀
                baseInfo.alphaVal=Number(edbInfoData.CalculateFormula)
            }

            setTimeout(() => {
                selectEDBClassifyINS.value?.getSelectClassifyOpt(props.edbInfo.EdbInfoDetail.ClassifyId)//获取选择的分类目录
            }, 1000);
        }
    }
)

// 预览页面
const isPreview=ref(route.query.type==='preview'||false)

const moveTypeOpts=[{name:'领先',key:1},{name:'滞后',key:2}]
const moveUnitOpts=[
    {name:'天',key:'天'},
    {name:'周',key:'周'},
    {name:'月',key:'月'},
    {name:'季',key:'季'},
    {name:'年',key:'年'},
]

//公式说明
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,'升频计算'],
		[22,'保存'],
		[35,'超季节性计算'],
		[52,'年化计算'],
		[51,'降频计算'],
		[61,'转季值计算'],
		[62,'累计值计算'],
		[63,'年初至今计算'],
        [72,'指数修匀计算'],
        [75,'日均值计算'],
	])
    str=btnTextMap.get(source.value)

    return str
}

const editEdbInfoId=ref(route.query.edbInfoId||0)//编辑时的指标id
const source=ref(0)//计算类型
const tabsArr=ref([])
// 初始化
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 showSelectEDB=ref(false)
const selectEDBinfo=ref(null)
function handleConfirmSelectEDB(e){
    selectEDBinfo.value=e
    updateBaseInfoData(e)
}
// 编辑时回显选择的指标 通过code去搜索
function searchEDBInfoByCode(code){
    apiDataEDB.edbSearchList({KeyWord:code,CurrentIndex:1,PageSize:1}).then(res=>{
        if(res.Ret===200){
            selectEDBinfo.value=res.Data?.List[0]
        }
    })
}

// 选择指标更新基础信息
function updateBaseInfoData(data){
    const tMap=new Map([
		['日度','D'],
		['周度','W'],
		['旬度','T'],
		['月度','M'],
		['季度','Q'],
		['年度','Y'],
	])
	const name_map = {
		5: data.EdbName,
		8: `${data.EdbName}/${baseInfo.numberN}${tMap.get(data.Frequency)}MA`,
		14: `${data.EdbName}/${data.Frequency}升频`,
		6: `${data.EdbName}同比`,
		7: `${data.EdbName}同差`,
		12: `${data.EdbName}${baseInfo.numberN}${data.Frequency.slice(0,1)}环比`,
		13: `${data.EdbName}${baseInfo.numberN}${data.Frequency.slice(0,1)}环差`,
		35: `${data.EdbName}超季节性/${baseInfo.numberN}年${baseInfo.calendarType==='公历'?'':'/'+baseInfo.calendarType}`,
		52: `${data.EdbName}年化`,
		51: `${data.EdbName}/${data.Frequency}降频`,
		61:  data.EdbName,
		62:  data.EdbName,
		63:  data.EdbName,
        72: `${data.EdbName}指数修匀`,
        75: `${data.EdbName}日均值`
	}
    baseInfo.name=name_map[source.value]||''
    baseInfo.unit=[5,8,14,7,35,72,75].includes(source.value) ? data.Unit : '无',
    baseInfo.frequency=source.value === 14 ? '日度' : source.value === 61 ? '季度' : source.value === 62 ? '' : data.Frequency

    if([72,75].includes(source.value)){//指数修匀目录默认和选择的指标在同一个目录
        selectEDBClassifyINS.value?.getSelectClassifyOpt(data.ClassifyId)//获取选择的分类目录
    }
    
}

// 基础信息
const edbNameInputFocus=ref(false)
const numberNInputFocus=ref(false)
const alphaValInputFocus=ref(false)
const baseInfo=reactive({
    name:'',
    unit:'',
    classify:'',
    frequency:'',
    numberN:1,//N值
    moveVal:'',
    moveType:1,
    moveUnit:'天',
    calendarType:'公历',
    valueType:'期末值',
    alphaVal:'',
})

// 选择单位
const showSelectUnit=ref(false)
function onConfirmSelectUnit(value){
    baseInfo.unit=value
}

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

//选择频度
const showSelectFrequency=ref(false)
function handleConfirmFrequency(value){
    baseInfo.frequency=value
}

//移动方式类型选择
const showMoveType=ref(false)
function onSelectMoveType(e){
    baseInfo.moveType=e.key
}
function getMoveTypeName(e){
    return moveTypeOpts.filter(item=>item.key===e)[0].name
}

//移动方式单位选择
const showMoveUnit=ref(false)
function onSelectMoveUnit(e){
    baseInfo.moveUnit=e.key
}

//超季节性日历选择
const showSelectCalendar=ref(false)

//降频数据取值选择
const showDataValSelect=ref(false)

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

// 提交计算
const saveBtnLoading=ref(false)
async function handleSave(){
    if(!selectEDBinfo.value){
        showToast('指标不能为空')
        return
    }
    if(!baseInfo.name){
        showToast('指标名称不能为空')
        return
    }
    if(!baseInfo.unit){
        showToast('指标单位不能为空')
        return
    }
    if(!baseInfo.classify){
        showToast('指标目录不能为空')
        return
    }
    if(!baseInfo.frequency){
        showToast('指标频度不能为空')
        return
    }
    if([72].includes(source.value)){
        if(baseInfo.alphaVal<=0||baseInfo.alphaVal>=1){
            showToast('请输入>0，<1的alpha数值')
            return
        }
    }

    const valueMap = {
		22: 'moveVal',
		51: 'valueType',
        72: 'alphaVal'
	}
    const params={
        FromEdbInfoId: selectEDBinfo.value.EdbInfoId,
        Source: source.value,
		EdbName: baseInfo.name,
		Unit: baseInfo.unit,
		ClassifyId: baseInfo.classify,
		Frequency: baseInfo.frequency,
		Formula: valueMap[source.value] ? String(baseInfo[valueMap[source.value]]) : String(baseInfo.numberN),
		MoveFrequency: baseInfo.moveUnit,
		MoveType: baseInfo.moveType, 
		Calendar: baseInfo.calendarType,
    }

    saveBtnLoading.value=true
    const res=route.query.type==='edit'?await apiDataEDB.editCalculateEDB({...params,EdbInfoId:Number(route.query.edbInfoId)}) : await apiDataEDB.addCalculateEDB(params)
    saveBtnLoading.value=false
    if(res.Ret===200){
        showToast(res.Msg)
        setTimeout(() => {
            if(route.query.type==='edit'){
                router.back()
            }else{
                router.replace({
                    path:'/dataEDB/detail',
                    query:{
                        edbInfoId:res.Data.EdbInfoId
                    }
                })
            }
        }, 1500);
    }
}

// tab切换重置表单
function handleTabChange(){
    selectEDBinfo.value=null
    baseInfo.name=''
    baseInfo.unit=''
    baseInfo.classify=''
    baseInfo.frequency=''
    baseInfo.numberN=1
    baseInfo.moveVal=''
    baseInfo.moveType=1
    baseInfo.moveUnit='天'
    baseInfo.calendarType='公历'
    baseInfo.valueType='期末值'
    classifyStr.value=''

}

//点击选择的指标左侧图标查看指标详情
const showEDBHistory=ref(false)// 显示指标溯源
const edbHistoryId=ref(0)
function handleShowEDBHistory(data){
    //计算指标打开弹窗,基础指标打开新页面
    if(data.EdbType===2){
        edbHistoryId.value=data.EdbInfoId
        showEDBHistory.value=true
    }else{
        const routerEl=router.resolve({
            path:'/dataEDB/detail',
            query:{
                edbInfoId:data.EdbInfoId
            }
        })
        window.open(routerEl.href,'_blank')
    }
}

</script>

<template>
    <div class="other-calculate-wrap">
        <van-tabs 
            v-model:active="source" 
            sticky
            :offset-top="width>650?60:0"
            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 select-edb-box">
            <van-field
                :modelValue="selectEDBinfo?.EdbName"
                label="选择指标"
                :right-icon="!isPreview?'arrow':''"
                readonly
                placeholder="请选择指标"
                input-align="right"
                @click-input="showSelectEDB=true"
                :disabled="isPreview"
            >
                <template #left-icon>
                    <div class="left-icon" v-if="selectEDBinfo" @click="handleShowEDBHistory(selectEDBinfo)">
                        <svg-icon name="edb-history-tag" size="24px"/>
                    </div>
                </template>
            </van-field>
        </section>
        <section class="section edbinfo-box">
            <div class="van-cell__title">已选指标</div>
            <div v-if="!selectEDBinfo">
                <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">{{selectEDBinfo?.EdbName}}</h2>
                <ul class="info-list">
                    <li class="info-item">ID：{{selectEDBinfo.EdbCode}}</li>
                    <li class="info-item">起始时间：{{selectEDBinfo.StartDate}}</li>
                    <li class="info-item">频度：{{selectEDBinfo.Frequency}}</li>
                    <li class="info-item">更新时间：{{selectEDBinfo.ModifyTime}}</li>
                    <li class="info-item">单位：{{selectEDBinfo.Unit}}</li>
                    <li class="info-item">数据来源：{{selectEDBinfo.SourceName}}</li>
                </ul>
                <div style="text-align:right">
                    <van-button color="#0052D9" size="small" @click="showSeeEDBDataList=true">查看数据</van-button>
                </div>
            </div>
        </section>
        <section class="section baseinfo-box">
            <!-- 时间位移（移动方式） -->
            <van-field
                label="移动方式"
                required
                v-if="source===22"
                :disabled="isPreview"
            >
                <template #input>
                    <div class="move-type-box">
                        <div :class="['btn',isPreview?'disabled':'']" @click="()=>{if(isPreview)return false;showMoveType=true}">
                            <svg-icon name="swap" v-if="!isPreview"></svg-icon>
                            <span>{{getMoveTypeName(baseInfo.moveType)}}</span>
                        </div>
                        <input :disabled="isPreview" class="input" type="number" :min="0" v-model="baseInfo.moveVal">
                        <div :class="['btn',isPreview?'disabled':'']" @click="()=>{if(isPreview)return false;showMoveUnit=true}">
                            <svg-icon name="swap" v-if="!isPreview"></svg-icon>
                            <span>{{baseInfo.moveUnit}}</span>
                        </div>
                    </div>
                </template>
            </van-field>
            <van-field 
                v-model="baseInfo.name" 
                label="指标名称" 
                placeholder="指标名称"
                input-align="right"
                required
                @focus="edbNameInputFocus=true"
                @blur="edbNameInputFocus=false"
                :disabled="isPreview"
            >
                <template #right-icon>
                    <svg-icon v-if="!isPreview" class="edit-icon" name="edit" :color="edbNameInputFocus?'#0052D9':'#333333'"/>
                </template>
            </van-field>
            <van-field 
                :modelValue="baseInfo.unit"
                readonly
                label="单位" 
                placeholder="请选择单位"
                input-align="right"
                :right-icon="!isPreview?'arrow':''"
                required
                @click-input="showSelectUnit=true"
                :disabled="!editEdbInfoId&&[6,7,75].includes(source)||isPreview"
            />
            <van-field 
                :modelValue="classifyStr"
                readonly
                label="指标目录" 
                placeholder="请选择指标目录"
                input-align="right"
                :right-icon="!isPreview?'arrow':''"
                required
                @click-input="showSelectClassify=true"
                :disabled="isPreview"
            />
            <van-field 
                :modelValue="baseInfo.frequency"
                readonly
                label="频度" 
                placeholder="请选择指标频度"
                input-align="right"
                :right-icon="!isPreview?'arrow':''"
                required
                @click-input="showSelectFrequency=true"
                :disabled="[5,14,61,63].includes(source)||(!editEdbInfoId&&[6,7,75].includes(source))||isPreview"
            />
            <van-field
                v-if="[8,12,13,35].includes(source)"
                v-model.number="baseInfo.numberN" 
                label="N等于" 
                placeholder="请输入N数值"
                input-align="right"
                required
                @focus="numberNInputFocus=true"
                @blur="numberNInputFocus=false"
                :disabled="isPreview"
            >
                <template #right-icon>
                    <svg-icon v-if="!isPreview" class="edit-icon" name="edit" :color="numberNInputFocus?'#0052D9':'#333333'"/>
                </template>
            </van-field>
            <!-- 超季节性日历 -->
            <van-field
                v-if="source===35"
                :modelValue="baseInfo.calendarType"
                readonly
                label="日历" 
                placeholder="请选择日历"
                input-align="right"
                :right-icon="!isPreview?'arrow':''"
                required
                @click-input="showSelectCalendar=true"
                :disabled="isPreview"
            />
            <!-- 降频数据取值 -->
            <van-field
                v-if="source===51"
                :modelValue="baseInfo.valueType"
                readonly
                label="数据取值" 
                placeholder="请选择"
                input-align="right"
                :right-icon="!isPreview?'arrow':''"
                @click-input="showDataValSelect=true"
                :disabled="isPreview"
            />
            <!-- 指数修匀 alpha 值 -->
            <van-field
                v-if="[72].includes(source)"
                v-model.number="baseInfo.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>
        </section>

        <div class="formula-intro-btn" @click="showTips=true">
            <svg-icon class="icon" name="warning"></svg-icon>
            <span>公式说明</span>
        </div>
        <div class="opt-btns" v-if="!isPreview">
            <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" :source='source' @select="handleConfirmSelectEDB"/>

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

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

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

    <!-- 查看指标数据 -->
    <SeeEDBDataList v-model:show="showSeeEDBDataList" :edbInfoId="selectEDBinfo?.EdbInfoId" />

    <!-- 移动方式类型选择 -->
    <van-action-sheet v-model:show="showMoveType" close-on-click-action :actions="moveTypeOpts" @select="onSelectMoveType" />
    
    <!-- 移动方式单位选择 -->
    <van-action-sheet v-model:show="showMoveUnit" close-on-click-action :actions="moveUnitOpts" @select="onSelectMoveUnit" />

    <!-- 超季节性日历选择 -->
    <van-action-sheet v-model:show="showSelectCalendar" close-on-click-action :actions="[{name:'公历'},{name:'农历'}]" @select="e=>baseInfo.calendarType=e.name" />

    <!-- 降频数据取值 -->
    <van-action-sheet v-model:show="showDataValSelect" close-on-click-action :actions="[{name:'期末值'},{name:'平均值'}]" @select="e=>baseInfo.valueType=e.name" />
    
    <!-- 指标溯源 -->
    <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>
.other-calculate-wrap{
    min-height: 90vh;
    background-color: $page-bg-grey;
    padding-bottom: 210px ;
}
.section{
    background-color: #fff;
    margin-bottom: 32px;
}
.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;
            }
        }
    }
}
.move-type-box{
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    gap: 20px;
    .input{
        box-sizing: border-box;
        display: block;
        border-radius: 12px;
        width: 150px;
        height: 72px;
        padding: 0 32px;
        background-color: #f6f6f6;
    }
    .btn{
        flex-shrink: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 130px;
        height: 72px;
        border-radius: 12px;
        background-color: #F2F3FF;
        color: $theme-color;
    }
    .disabled{
        background-color: #F6F6F6;
        color: #333;
    }
}
.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){
    .other-calculate-wrap{
        padding-bottom: 105px;
    }
    .section{
        margin-bottom: 16px;
    }
    .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;
                }
            }
        }
    }
    .move-type-box{
        gap: 10px;
        .input{
            border-radius: 6px;
            width: 65px;
            height: 36px;
            padding: 0 16px;
        }
        .btn{
            width: 65px;
            height: 36px;
            border-radius: 6px;
        }
    }
    .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>