<script setup name="DataEDBAddBaseEDB">
import {ref,computed} from 'vue'
import apiDataEDB from '@/api/dataEDB'
import { showToast } from 'vant'
import EditBaseEDB from './components/EditBaseEDB.vue'
import AddDateSequenceEdb from './components/AddDateSequenceEdb.vue'
import { useRouter } from 'vue-router'
import {windCommonIndexCodeArr,THSCommonIndexStockCodeArr,THSCommonIndexFuturesCodeArr} from './util/config'

const router=useRouter()

//显示目录
function getClassifyName(data){
    const arr=data||[]
    let str=''
    // slice()生成新的数组，不能改变原数组，改变原数组会触发监听，造成死循环
    arr.slice().reverse().map((item) => str += item.ClassifyName + '/')
    return str
}

const hasDateSequence = computed(() => {
    return [1,2].includes(dataSourceVal.value)
})
const isComplete = computed(() => {
    return StockCode.value && (EdbCodeArr.value.length>0 || EdbCodeCommonChecked.value.length>0)
})
const EdbCodeCommonArr = computed(() => {
    if(dataSourceVal.value==2){
        return windCommonIndexCodeArr
    }else if(dataSourceVal.value==1){
        if(codeTypeVal.value==1){
            // 期货
            return THSCommonIndexFuturesCodeArr
        }else{
            // 股票
            return THSCommonIndexStockCodeArr
        }
    }
})

const EdbCodeCommonHintText = computed(() => {
    if(dataSourceVal.value==2){
        return '提示：Wind金融终端输入“CG”会弹出代码生成器，可在代码生成器上获取其他指标的代码'
    }else if(dataSourceVal.value==1){
        return '提示：可用Excel同花顺插件/日期序列功能，根据所选指标获取指标代码，期货和股票常用代码可在下方勾选'
    }
})



// 数据库
const showSelectDatabase=ref(false)
const edbDatabaseOpts=[{value:'0',label:'经济数据库'},{value:'1',label:'日期序列'}]
const databaseText=ref('经济数据库')
const databaseVal=ref('0')

const onConfirmDatabase=(e)=>{
    databaseText.value=e.selectedOptions[0].label
    databaseVal.value=e.selectedOptions[0].value
    showSelectDatabase.value=false
}

// 证券代码
const StockCode=ref('')
// 指标代码
const EdbCode=ref('')
const EdbCodeArr=ref([])

const EdbCodeCommonChecked=ref([])

const codeFormatter=(e)=>{
    return (e+'').replaceAll(' ','')
}
const codeInputBlur=()=>{
    EdbCodeArr.value = Array.from(new Set([...EdbCodeArr.value,...EdbCode.value.split(',')])).filter(Boolean)
    EdbCode.value=''
}

const delEdbCode=(index)=>{
    EdbCodeArr.value.splice(index,1)
}
// 同花顺常用指标类型
const showSelectCodeType=ref(false)
const edbCodeTypeOpts=[{value:1,label:'期货常用指标'},{value:2,label:'股票常用指标'}]
const codeTypeText=ref('期货常用指标')
const codeTypeVal=ref(1)

const onConfirmCodeType=(e)=>{
    codeTypeText.value=e.selectedOptions[0].label
    codeTypeVal.value=e.selectedOptions[0].value
    EdbCodeCommonChecked.value=[]
    showSelectCodeType.value=false
}

// 检验重复弹窗
const showRepeatDialog=ref(false)
const queryLoading=ref(false)
const repeatEdbs=ref([])


// 数据来源
const showSelectDataSource=ref(false)
const edbSourceOpts=ref([])
const dataSourceText=ref('')
const dataSourceVal=ref(0)
async function getEDBSourceOpts(){
    const res=await apiDataEDB.getEDBSourceOpts({IsBase:1})
    if(res.Ret===200){
        edbSourceOpts.value=res.Data||[]
        dataSourceText.value=edbSourceOpts.value[0]?.SourceName
        dataSourceVal.value=edbSourceOpts.value[0]?.EdbSourceId
    }
}
getEDBSourceOpts()
function onConfirmDataSource(e){
    console.log(e);
    dataSourceText.value=e.selectedOptions[0].SourceName
    dataSourceVal.value=e.selectedOptions[0].EdbSourceId
    showSelectDataSource.value=false

    databaseText.value='经济数据库'
    databaseVal.value='0'
    StockCode.value=''
    EdbCode.value=''
    EdbCodeArr.value=[]
    EdbCodeCommonChecked.value=[]
    codeTypeText.value='期货常用指标'
    codeTypeVal.value=1
}




// 指标名称/ID
const searchEDBTxt=ref('')
// 公司ID
const searchCompanyTxt=ref('')

// 搜索指标
const result=ref(null)
async function getEDBInfo(){
    const res=await apiDataEDB.edbSearch({
        Source:dataSourceVal.value,
        EdbCode:searchEDBTxt.value,
        CompanyCode:searchCompanyTxt.value
    })
    if(res.Ret===200){
        result.value=res.Data
    }else{
        result.value=null
    }

}

function onSearch(){
    if(!searchEDBTxt.value){
        showToast('请输入指标ID')
        return
    }
    if(dataSourceText.value==='彭博财务'&&!searchCompanyTxt.value){
        showToast('请输入公司ID')
        return
    }
    getEDBInfo()
}

// 下一步指标基本信息填写
const showEditBaseEDB=ref(false)
const baseInfo=ref({})
function handleShowEditBaseEDB(){
    let obj={
        EdbCode: result.value.SearchItem.EdbCode,
		EndDate: result.value.SearchItem.EndDate,
		StartDate: result.value.SearchItem.StartDate,
		Source: dataSourceVal.value,
    }
    //隆众指标和手工指标、交易所等将名称 频度 单位带到下一步
    // if([9, 10, 11, 15, 16, 17, 18, 19, 20, 21, 26,38,41,57,60,71,76].includes(dataSourceVal.value)){
        // 不做限制了，为空带出来就是空
        obj={
            ...obj,
            edb_name: result.value.SearchItem.EdbName || '',
			unit: result.value.SearchItem.Unit || '',
			frequency: result.value.SearchItem.Frequency || '',
        }
    // }
    baseInfo.value=obj
    showEditBaseEDB.value=true
}
function handleEditBaseEdbSuccess(){
    setTimeout(() => {
        router.back()
    }, 1500);
}

//清空状态
function handleClearPage(){
    searchEDBTxt.value=''
    searchCompanyTxt.value=''
    result.value=null
}

// ----------------日期序列
// 检查是否指标重复
const indexExsitCheck=()=>{
    setTimeout(()=>{
        if(isComplete.value){
            let params={
                Source:dataSourceVal.value,
                SubSource:databaseVal.value,
                EdbCode:Array.from(new Set([...EdbCodeArr.value,...EdbCodeCommonChecked.value])).join(','),
                StockCode:StockCode.value
            }
            apiDataEDB.existEDBCheck(params).then(res=>{
                if(res.Ret == 200){
                    // console.log(res,'res');
                    // return 
                    if(res.Data.IndexExist){
                        // 有重复
                        repeatEdbs.value=[]
                        let existEdbInfo=res.Data.ExistEdbInfo || []
                        let text=''
                        existEdbInfo.map(item =>{
                            text=`${item.EdbName}（${item.EdbCode}）`
                            repeatEdbs.value.push({text,id:item.EdbInfoId})
                        })
                        showRepeatDialog.value=true
                    }else{
                        // 没有重复
                        queryLoading.value=true

                        apiDataEDB.edbSearch(params).then(res => {
                            if(res.Ret == 200){
                                // console.log(res,'res');
                                // return 
                                let stockList = res.Data.SearchItem.StockList || []
                                edbIndexDatas.value=[]
                                stockList.map((item,index) =>{
                                    let isCommon = EdbCodeCommonArr.value.find(it => it.value == item.EdbCode)
                                    let params={
                                        Source:dataSourceVal.value,
                                        ClassifyId:0,
                                        Unit:'',
                                        Frequency:'日度',
                                        EdbName:isCommon?`${item.StockCode}${isCommon.label}`:`${item.StockCode}${item.EdbCode}`,
                                        EdbCode:item.EdbCode,
                                        StockCode:item.StockCode,
                                        DataList:item.DataList
                                    }
                                    edbIndexDatas.value.push(params)
                                })
                                showAddDateSequence.value=true
                            }
                        }).finally(()=>{
                            queryLoading.value=false
                        })
                    }
                }
            })
        }
    },50)
}

const edbNavigator=({id})=>{
    const { href } = router.resolve({ path: '/dataEDB/detail',query:{edbInfoId:id}});
    window.open(href, '_blank');
}

// 日期序列指标 下一步
const edbIndexDatas=ref([])
const showAddDateSequence=ref(false)


</script>

<template>
    <div class="add-baseEDB-page">
        <van-cell title="数据来源" is-link :value="dataSourceText" @click="showSelectDataSource=true"/>
        <van-cell title="数据库" is-link :value="databaseText" @click="showSelectDatabase=true" v-if="hasDateSequence"/>
        <template v-if="databaseVal == '0'">
            <div class="search-box">
                <van-search
                    v-model="searchEDBTxt"
                    show-action
                    shape="round"
                    placeholder="指标ID/指标名称"
                    @clear="searchEDBTxt=''"
                    @search="onSearch"
                >
                    <template #action>
                        <span class="right-btn" @click="onSearch">查询</span>
                    </template>
                </van-search>
            </div>
            <div class="search-box" style="padding-top:0" v-if="dataSourceText==='彭博财务'">
                <van-search
                    v-model="searchCompanyTxt"
                    show-action
                    shape="round"
                    placeholder="公司ID"
                    @clear="searchCompanyTxt=''"
                    @search="onSearch"
                >
                    <template #action>
                        <span class="right-btn" @click="onSearch">查询</span>
                    </template>
                </van-search>
            </div>

            <div class="warn_txt" v-if="result?.Status===1">
                该数据已存在数据库，名称为：{{result.SearchItem.EdbName}}，目录为：{{ getClassifyName(result.ClassifyList) }}，如需重新添加，请删除原指标
            </div>
            <div class="warn_txt" v-if="result?.Status===3">
                该数据已存在数据库，名称为：{{result.SearchItem.EdbName}}，目录为：{{ getClassifyName(result.ClassifyList) }}
            </div>

            <div class="no-auth" v-if="result?.Status===3">您当前暂无权限查看该指标，如需查看，请联系管理员</div>
            <template v-else>
                <template v-if="result?.Status===1||result?.SearchItem.DataList?.length">
                    <van-cell title="指标ID" :value="result?.SearchItem.EdbCode" />
                    <van-cell title="起始时间" :value="result?.SearchItem.StartDate" />
                    <van-cell title="终止时间" :value="result?.SearchItem.EndDate"/>
                    <ul class="data-value-wrap">
                        <li class="item" style="font-weight:bold">时间</li>
                        <li class="item" style="font-weight:bold">值</li>
                        <template v-if="result?.SearchItem.DataList">
                            <template v-for="item,index in result?.SearchItem.DataList" :key="index">
                                <li class="item">{{item.DataTime}}</li>
                                <li class="item"><span class="val-box">{{item.Value}}</span></li>
                            </template>
                        </template>
                        <div class="data-empty" v-else>
                            <img src="https://hzstatic.hzinsights.com/static/ETA_mobile/empty_img.png" alt="">
                            <p>暂无对应的数据</p>
                        </div>
                    </ul>
                </template>

                <div class="search-empty-wrap" v-else>
                    <img src="https://hzstatic.hzinsights.com/static/ETA_mobile/empty_img.png" alt="">
                    <p>未搜索到该指标</p>
                </div>
            </template>
        </template>
        <template v-else>
            <van-field 
                v-model="StockCode" 
                label="证券代码" 
                placeholder="每次只查询一个证券代码"
                input-align="right"
                :formatter="codeFormatter"
                format-trigger="onBlur">
            </van-field>
            <van-field 
                v-model="EdbCode" 
                label="指标代码" 
                placeholder="多个指标代码用英文逗号分隔"
                input-align="right"
                :formatter="codeFormatter"
                format-trigger="onBlur"
                @blur="codeInputBlur">
            </van-field>
            <div class="edb-code-hint" :style="{marginBottom:dataSourceVal==2?'20px':''}">{{ EdbCodeCommonHintText }}</div>
            <van-cell :title="codeTypeText" is-link @click="showSelectCodeType=true" style="margin-bottom: 20px;"
            v-if="dataSourceVal==1"/>
            <van-checkbox-group v-model="EdbCodeCommonChecked" shape="square" icon-size="12px"
            direction="horizontal" class="ebd-code-checkbox-group" style="margin:0 16Px;">
                <van-checkbox :name="item.value" v-for="item in EdbCodeCommonArr" :key="item.value" 
                style="" class="ebd-code-checkbox">{{ item.label }}</van-checkbox>
            </van-checkbox-group>
            <div class="edb-code-tags-box">
                <div class="edb-code-tags-item" v-for="(item,index) in EdbCodeArr" :key="item">
                    <span class="edb-code-item-text">{{ item }}</span>
                    <img name="cross" class="edb-code-item-icon" src="@/assets/imgs/dataEDB/close_outline_black.png" @click="delEdbCode(index)"/>
                </div>
            </div>
        </template>

        <div class="btns-wrap">
            <van-button block type="primary" style="max-width:300px;margin: 0 auto" v-if="result?.Status===2" :disabled="!result?.SearchItem.DataList?.length" @click="handleShowEditBaseEDB">下一步</van-button>
            <van-button block type="primary" style="max-width:300px;margin: 0 auto" v-else-if="[1,3].includes(result?.Status)" @click="handleClearPage">知道了</van-button>
            <van-button block type="primary" style="max-width:300px;margin: 0 auto" v-else-if="databaseVal=='1'" 
            @click="indexExsitCheck" :disabled="!isComplete" :loading="queryLoading" loading-text="查询中">查询数据</van-button>
        </div>
    </div>

    <!-- 选择数据来源 -->
    <van-popup 
        v-model:show="showSelectDataSource"
        round
        position="bottom"
    >
        <van-picker
            title="数据来源"
            :columns="edbSourceOpts"
            :columns-field-names="{text:'SourceName',value:'EdbSourceId'}"
            @confirm="onConfirmDataSource"
            @cancel="showSelectDataSource=false"
        />
    </van-popup>
    <!-- 选择数据库 -->
    <van-popup 
        v-model:show="showSelectDatabase"
        round
        position="bottom"
    >
        <van-picker
            title="数据库"
            :columns="edbDatabaseOpts"
            :columns-field-names="{text:'label',value:'value'}"
            @confirm="onConfirmDatabase"
            @cancel="showSelectDatabase=false"
        />
    </van-popup>
    <!-- 选择常用指标类型 -->
    <van-popup 
        v-model:show="showSelectCodeType"
        round
        position="bottom"
    >
        <van-picker
            title="常用指标"
            :columns="edbCodeTypeOpts"
            :columns-field-names="{text:'label',value:'value'}"
            @confirm="onConfirmCodeType"
            @cancel="showSelectCodeType=false"
        />
    </van-popup>
    <!-- 检验重复弹窗 -->
    <van-dialog 
        v-model:show="showRepeatDialog" 
        title="指标库中已存在以下指标，请勿重复录入！" 
        confirmButtonText="知道了"
        id="repeat-dialog"
    >
        <div class="repeated-box">
            <!-- <div class="repeated-text"></div> -->
            <div class="repeated-row">
                <div class="repeated-item" v-for="(item,index) in repeatEdbs" :key="item.id"
                @click="edbNavigator(item)">
                    {{ index+1 }}、
                    <span>{{ item.text }}</span>
                </div>
            </div>

        </div>

    </van-dialog>

    <!-- 新增基础指标 -->
    <EditBaseEDB 
        v-model="showEditBaseEDB" 
        :baseInfo="baseInfo"
        @addSuccess="handleEditBaseEdbSuccess"
    />

    <!-- 新增日期序列指标 -->
    <AddDateSequenceEdb 
        v-model="showAddDateSequence" 
        :dateSequenceEdbList="edbIndexDatas"
        @addDateSequenceSuccess="handleEditBaseEdbSuccess"
    />

</template>

<style lang="scss" scoped>
.add-baseEDB-page{
    padding-bottom: 100PX;
    :deep(.van-cell__right-icon){
        color: #333;
    }
}
.warn_txt{
    text-align: center;
    padding: var(--van-padding-md);
    color: #FF4E00;
    line-height: 1.7;
}
.search-box{
    padding: var(--van-padding-md);
    .van-search{
        padding: 6px;
        background-color: #F0F2F6;
        border-radius: var(--van-radius-max);
    }
    :deep(.van-search__content){
        background: transparent !important;
        border: none;
    }
    :deep(.van-search__field .van-field__left-icon){
        color: #333;
    }
    .right-btn{
        display: inline-block;
        color: #fff;
        background-color: $theme-color;
        width: 112px;
        height: 56px;
        text-align: center;
        line-height: 56px;
        border-radius: var(--van-radius-max);
    }
}
.data-value-wrap{
    margin-top: 66px;
    display: flex;
    flex-wrap: wrap;
    border-top: 1px solid $border-color;
    .item{
        width: 50%;
        padding: 32px;
        border-bottom: 1px solid $border-color;
        &:nth-child(odd){
            border-right: 1px solid $border-color;
        }
        .val-box{
            display: inline-block;
            background-color: #F2F3FF;
            color: $theme-color;
            text-align: center;
            padding: 0 30px;
            line-height: 48px;
            border-radius: 8px;
        }
    }
    .data-empty{
        width: 100%;
        text-align: center;
        color: $font-grey;
        img{
            width: 200PX;
        }
    }
}
.search-empty-wrap{
    text-align: center;
    color: $font-grey;
    img{
        width: 200PX;
    }
}
.no-auth{
    width: 80%;
    max-width: 500PX;
    padding: 10PX 20PX;
	margin: 30PX auto;
	text-align: center;
	background: #ECECEC;
	color: #FF4E00;
	border: 1px dashed #FF4E00;
}

.edb-code-hint{
    padding:0 16PX;
    color: #B1B1B1;
    font-size: 24px;
    margin: 20px 0 0 0;
}
.ebd-code-checkbox-group{
    .ebd-code-checkbox{
        margin-bottom: 8PX;
        margin-right: 0;
        padding-right: 12PX;
        min-width: 33.33%;
    }
}

.edb-code-tags-box{
    display: flex;
    align-items: center;
    padding: 0 16PX;
    margin-top: 40px;
    flex-wrap: wrap;

    .edb-code-tags-item{
        display: flex;
        align-items: center;
        height: 56px;
        padding: 0 16px;
        margin-right: 20px;
        background-color: #F6F6F6;
        margin-bottom: 8px;
        max-width: calc(100vw - 32PX);
        .edb-code-item-text{
            font-size: 28px;
            color: #333;
            margin-right: 8px;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        .edb-code-item-icon{
            cursor: pointer;
            height: 36px;
            width: 36px;
        }
    }
}


.btns-wrap{
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    padding: 20PX;
    z-index: 99;
    background-color: #fff;
    text-align: center;
}

.repeated-box{
    padding: 20PX;
    .repeated-text{
        font-size: 16PX;
        color: #000;
    }
    .repeated-row{
        max-height: 400px;
        overflow-y: auto;
        .repeated-item{
            margin-top: 16PX;
            &:first-child{
                margin-top: 0;
            }
            span{
                word-break: break-all;
                cursor: pointer;
                text-decoration: underline;
                color: #0052D9;
            }
        }
    }

}



@media screen and (min-width:$media-width){
    .search-box{
        .van-search{
            padding: 6px;
        }
        .right-btn{
            width: 56px;
            height: 28px;
            line-height: 28px;
        }
    }
    .data-value-wrap{
        margin-top: 33px;
        .item{
            padding: 16px;
            .val-box{
                padding: 0 15px;
                line-height: 28px;
                border-radius: 4px;
            }
        }
    }
    .edb-code-hint{
        font-size: 16px;
        margin: 20px 0 0 0;
    }
    .ebd-code-checkbox-group{
        justify-content: flex-start;
        .ebd-code-checkbox{
            margin-right: 0;
            min-width: 0;
        }
    }
    .edb-code-tags-box{
        margin-top: 40px;
        .edb-code-tags-item{
            height: 36px;
            padding: 0 8px;
            margin-right: 20px;
            margin-bottom: 8px;
            max-width: calc(100vw - 32PX);
            .edb-code-item-text{
                font-size: 18px;
                margin-right: 8px;
            }
            .edb-code-item-icon{
                height: 28px;
                width: 28px;
            }
        }
    }
}
</style>
<style lang="scss">
#repeat-dialog{
    .van-dialog__header{
        padding: 24PX 24PX 0;
        font-size: 18PX;
    }
}
</style>