<script setup>
import apiDataEDB from '@/api/dataEDB'
import { showToast } from 'vant';
import {computed, nextTick, reactive, ref, watch} from '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 EDBHistory from '@/views/dataEDB/components/EDBHistory.vue'
import {calculateTypeTipsMap,MAXADDEDBNUM} from '../../util/config'
import {generateSeriesArray} from '@/views/dataEDB/util/util.js'
import { useRoute, useRouter } from 'vue-router';
import moment from 'moment';
import {useToHistoryPage} from '@/hooks/edb/useToHistoryPage'
const {toHistoryPage} = useToHistoryPage()

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

watch(
    ()=>props.edbInfo,
    ()=>{
        if(['edit','preview'].includes(route.query.type)){
            edbList.value=props.edbInfo.CalculateList.map(item=>{
                return {
                    tag:item.FromTag,
                    target:item.FromEdbInfoId,
                    startDate:item.StartDate,
                    endDate:item.EndDate,
                    name:item.FromEdbName
                }
            })
            const obj=JSON.parse(props.edbInfo.EdbInfoDetail.CalculateFormula)
            dateContactState.type=obj.DateType//会触发radio的change事件 所有下面用个nextTick
            nextTick(()=>{
                dateContactState.list=obj.CheckList
            })
            baseInfo.name=props.edbInfo.EdbInfoDetail.EdbName
            baseInfo.unit=props.edbInfo.EdbInfoDetail.Unit
            baseInfo.classify=props.edbInfo.EdbInfoDetail.ClassifyId
            baseInfo.frequency=props.edbInfo.EdbInfoDetail.Frequency
            setTimeout(() => {
                selectEDBClassifyINS.value?.getSelectClassifyOpt(props.edbInfo.EdbInfoDetail.ClassifyId)//获取选择的分类目录
            }, 1000);
        }
    }
)

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

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

const source=ref(Number(route.query.source)||0)//计算类型

//公式说明
const showTips=ref(false)
const tipsContent=ref(calculateTypeTipsMap.get(Number(route.query.source))||'')


const letterOpts = generateSeriesArray()||[];//字母数据

//选择的指标集合
const edbList=ref([
    {
        tag:letterOpts[0],
        target:'',
        startDate:'',
        endDate:'',
        name:'',
        EdbType:0
    },
    {
        tag:letterOpts[1],
        target:'',
        startDate:'',
        endDate:'',
        name:'',
        EdbType:0
    }
])
function handleAddEdbList(){
    if(edbList.value.length>=MAXADDEDBNUM){
        showToast('添加指标个数已达上限')
        return
    }
    let tag = edbList.value[edbList.value.length-1].tag;
	let index = letterOpts.findIndex(item => item === tag);
	const item = {
		tag: letterOpts[index+1],
		target: '',
		start_date: '',
		end_date: '',
        name:'',
        EdbType:0
	};
	edbList.value.push(item);
}
function handleDeleteEDBItem(index){
    // 检测dateContactState.list是否有改项有的话删除掉
    const tag=edbList.value[index].tag
    const flagIndex=dateContactState.list.indexOf(tag)
    if(flagIndex!=-1){
        dateContactState.list.splice(flagIndex,1)
    }


    edbList.value.splice(index, 1)
}
// 选择指标
const showSelectEDB=ref(false)
let whichIndex=0
function handleShowSelectEDB(index){
    if(isPreview.value) return
    whichIndex=index
    showSelectEDB.value=true
}
function handleConfirmSelectEDB(e){
    edbList.value[whichIndex].target=e.EdbInfoId
    edbList.value[whichIndex].startDate=e.StartDate
    edbList.value[whichIndex].endDate=e.EndDate
    edbList.value[whichIndex].name=e.EdbName
    edbList.value[whichIndex].EdbType=e.EdbType
}

// 日期合并类型
const dateContactState=reactive({
    type:1,
    list:[],//部分日期并集选择的指标
})
// 显示日期
const dateRange=computed(()=>{
    const arr=edbList.value.filter(_=>dateContactState.list.includes(_.tag)&&_.target)
                     .map(_=>[new Date(_.startDate),new Date(_.endDate)]).flat(Infinity)
    const start=arr.length&&moment(Math.min(...arr)).format('YYYY-MM-DD')
    const end=arr.length&&moment(Math.max(...arr)).format('YYYY-MM-DD')
    if(start&&end) return start+'至'+end

    return ''
})


// 基础信息
const edbNameInputFocus=ref(false)
const baseInfo=reactive({
    name:'',
    unit:'无',
    classify:'',
    frequency:''
})

// 选择单位
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 saveBtnLoading=ref(false)
async function handleSave(){
    const arr=edbList.value.filter(item=>item.target).map(item=>{
        return {
            EdbInfoId: item.target,
            FromTag: item.tag,
        }
    })
    if(!arr.length){
        showToast('请选择指标')
        return
    }
    if(!baseInfo.name){
        showToast('指标名称不能为空')
        return
    }
    if(!baseInfo.unit){
        showToast('指标单位不能为空')
        return
    }
    if(!baseInfo.classify){
        showToast('指标目录不能为空')
        return
    }
    if(!baseInfo.frequency){
        showToast('指标频度不能为空')
        return
    }
    const params={
        Source: source.value,
		EdbName: baseInfo.name,
		Unit: baseInfo.unit,
		ClassifyId: baseInfo.classify,
		Frequency: baseInfo.frequency,
		Formula: JSON.stringify({DateType:dateContactState.type,CheckList:dateContactState.list}),
        EdbInfoIdArr:arr
    }
    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);
    }
}

// 显示指标溯源
const showEDBHistory=ref(false)
const edbHistoryId=ref(0)
function handleShowEDBHistory(item){
    //计算指标打开弹窗,基础指标打开新页面
    if(item.EdbType===2){
        /* edbHistoryId.value=item.target
        showEDBHistory.value=true */
        toHistoryPage(item.target)
    }else{
        const routerEl=router.resolve({
            path:'/dataEDB/detail',
            query:{
                edbInfoId:item.target
            }
        })
        window.open(routerEl.href,'_blank')
    }
}


</script>

<template>
    <div class="diffusionIndex-wrap">
        <section class="section select-edb-box">
            <van-swipe-cell  v-for="(item,index) in edbList" :key="item.tag" :disabled="index<2||isPreview">
                <van-field 
                    :label="item.tag"
                    :right-icon="!isPreview?'arrow':''"
                    @click-input="handleShowSelectEDB(index)"
                    :disabled="isPreview"
                >
                    <template #left-icon>
                        <div class="left-icon">
                            <svg-icon name="edb-history-tag" size="24px" v-if="item.target" @click="handleShowEDBHistory(item)"/>
                        </div>
                    </template>
                    <template #input>
                        <div class="edb-info-box">
                            <div class="edb-info" v-if="item.target">
                                <span class="name">{{item.name}}</span>
                                <span class="time">{{item.startDate}}至{{item.endDate}}</span>
                            </div>
                            <span class="placeholder" v-else>请选择指标</span>
                        </div>
                    </template>
                </van-field>
                <template #right>
                    <van-button square type="danger" text="删除" @click="handleDeleteEDBItem(index)"/>
                </template>
            </van-swipe-cell>
            <div class="van-cell add-edb-box" @click="handleAddEdbList" v-if="!isPreview">
                <img src="@/assets/imgs/icon01.png" alt="">
                <span>添加更多参数</span>
            </div>
            <van-field label="指标扩散日期">
                <template #input>
                    <div class="contact-date-box">
                        <van-radio-group :disabled="isPreview" v-model="dateContactState.type" shape="dot" @change="dateContactState.list=[]">
                            <van-radio :name="1">全部日期并集</van-radio>
                            <van-radio :name="2">部分日期并集</van-radio>
                        </van-radio-group>
                        <van-checkbox-group 
                            v-model="dateContactState.list"
                            direction="horizontal"
                            shape="square" 
                            v-if="dateContactState.type===2"
                            :disabled="isPreview"
                        >
                            <van-checkbox
                                v-for="item in edbList"
                                :key="item.tag"
                                :name="item.tag"
                            >{{item.tag}}</van-checkbox>
                        </van-checkbox-group>
                        <div class="time" v-if="dateContactState.type===2">{{dateRange}}</div>
                    </div>
                </template>
            </van-field>
        </section>

        <section class="section baseinfo-box">
            <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
            />
            <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="isPreview"
            />
        </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"
            >扩散指数计算</van-button>
        </div>
    </div>

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

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

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

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

    <!-- 指标溯源 -->
    <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>
.diffusionIndex-wrap{
    min-height: 90vh;
    background-color: $page-bg-grey;
    padding-bottom: 210px ;
}

.section{
    background-color: #fff;
    margin-bottom: 32px;
}

.select-edb-box{
    .left-icon{
        width: 48px;
        height: 48px;
    }
    :deep(.van-cell__right-icon){
        align-self: center;
        color: #333;
    }
    .edb-info-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;
        }
    }
    .add-edb-box{
        display: flex;
        justify-content: flex-end;
        align-items: center;
        color: $theme-color;
        font-size: 32px;
        padding: 32px var(--van-cell-horizontal-padding);
        img{
            width: 48px;
            height: 48px;
        }
    }

}

.contact-date-box{
    width: 100%;
    .van-radio{
        justify-content: flex-end;
        margin-bottom: 10px;
    }
    .van-checkbox-group--horizontal{
        justify-content: flex-end;
        gap: 8px;
    }
    .time{
        color: $theme-color;
        text-align: right;
        margin-top: 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){
    .diffusionIndex-wrap{
        padding-bottom: 105px;
    }
    .section{
        margin-bottom: 16px;
    }
    .select-edb-box{
        .left-icon{
            width: 24px;
            height: 24px;
        }
        .edb-info-box{
            .time{
                font-size: 12px;
            }
        }
        .add-edb-box{
            font-size: 16px;
            padding: 16px var(--van-cell-horizontal-padding);
            img{
                width: 24px;
                height: 24px;
            }
        }
    }
    .contact-date-box{
        .van-radio{
            margin-bottom: 5px;
        }
        .van-checkbox-group--horizontal{
            gap: 4px;
        }
        .time{
            margin-top: 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>