<script setup>
import chartBox from './component/chartBox.vue'
import noAuth from './component/noAuth.vue'
import sharePoster from '../components/SharePoster.vue'
import collectBox from './component/collectBox.vue'
import { userChartRenderState } from '../hooks/chartRender'
import { Popup, Toast,Picker,Icon,Tab,Tabs,ActionSheet,DatetimePicker} from 'vant';
import {ref,onMounted, reactive, watch,computed,nextTick} from 'vue'
import {useRoute, useRouter,onBeforeRouteUpdate} from 'vue-router'
import moment from 'moment'
import _ from 'lodash';
import Highcharts from 'highcharts';
import {
    apiChartInfo,
    apiChartList,
    apiChartSave,
    apiChartBeforeAndNext,
    apiChartRefresh,
    apiMyChartDetail,
    apiCommonChartDetail,
    apiCommonChartRefresh,
    apiCommonChartSave,
    apiRelevanceChartRefresh,
    apiMyChartChangeChartList
} from '@/api/hzyb/chart.js'
const router=useRouter()
const route=useRoute()
document.title='图表详情'

localStorage.setItem('hzyb-token',route.query.token)


const { 
    useChartRender,
    hasLeftAxis,
    hasRightAxis,
    hasRightTwoAxis,
    axisLimitData 
} = userChartRenderState();

// 获取用户信息
import {apiUserInfo} from '@/api/hzyb/user'
let canSave=ref(false)//是否有保存功能
const getUserInfo=async ()=>{
    const res=await apiUserInfo({Authorization:route.query.token})
    if(res.code===200){
        if(res.data.is_inner){
            canSave.value=true
        }
    }
}
getUserInfo()



let showDate=ref(false)
let startDate=ref('')
let endDate=ref('')
// 开始-结束时间picker相关信息
const pickerInfo=reactive({
    tabIndex:'1'
})
// picker使用数据
const dateRange=[]
const dateRangeStart=ref(null)
const dateRangeEnd=ref(null)

const DateConfirm=(date,dateType)=>{
    // console.log(date);
    if(dateType=='start'){
        dateRange[0]=moment(date).format('YYYY-MM-DD')
    }else{
        dateRange[1]=moment(date).format('YYYY-MM-DD')
    }
}

const handleShowDate=()=>{
    // 回显
    switch (dateType.value) {
        case 3:
            dateRangeStart.value = new Date('2015-01-01')
            dateRangeEnd.value = new Date(latestDate.value)
            break;
        case 9:
            dateRangeStart.value = new Date('2020-01-01')
            dateRangeEnd.value = new Date(latestDate.value)
            break;
        case 4:
            dateRangeStart.value = new Date('2021-01-01')
            dateRangeEnd.value = new Date(latestDate.value)
            break;
        case 11:
            dateRangeStart.value = new Date('2022-01-01')
            dateRangeEnd.value = new Date(latestDate.value)
            break;
        case 0:
            dateRangeStart.value = new Date(earliestDate)
            dateRangeEnd.value = new Date(latestDate.value)
            break;  
        default:
            dateRangeStart.value = new Date(startDate.value)
            dateRangeEnd.value = new Date(endDate.value)
            break;
    }
    showDate.value=true
}
const startPicker=ref(null)
const endPicker=ref(null)

// 确定选择时间
const handleConfirmDate=()=>{
    startPicker.value.getPicker().confirm()
    endPicker.value.getPicker().confirm()
    
    let start='',end=''
    if(sameOptionType.value.includes(resData.value.ChartInfo.ChartType)
    || resData.value.ChartInfo.ChartType===2){
        start=dateRange[0]
        end=dateRange[1]
    }
    if(new Date(end)>=new Date(start)){
        startDate.value=start
        endDate.value=end
        dateType.value=5
        getChartInfo()
        showDate.value=false
    }else{
        Toast('结束时间不能小于开始时间')
    }
}

const actionSheetShow=ref(false)
const actions=computed(()=>{
    return canSave.value&&[1,2,5].includes(chartSource)?[{ name: '刷新' },{ name: '保存' },{ name: '生成海报' }]:
                            [{ name: '刷新' },{ name: '生成海报' }]
})
const onActionSelect=(action,index)=>{
    if(action.name=='刷新'){
        handleRefreshChart()
    }else if(action.name=='保存'){
        handleSaveChart()
    }else if(action.name=='生成海报'){
        $('.share-poster-wrap div')[0].click()
    }
}
// 选择年份时间段
let dateTypeList=ref([
    {
		name: '15年至今',
		value: 3,
	},
	// {
	// 	name: '18年至今',
	// 	value: 7,
	// },
	// {
	// 	name: '19年至今',
	// 	value: 8,
	// },
	{
		name: '20年至今',
		value: 9,
	},
	{
		name: '21年至今',
		value: 4,
	},
    {
		name: '22年至今',
		value: 11,
	},
    {
		name: '全部',
		value: 0,
	},
])
let dateType=ref(null)
let startYear=ref(null)

const dateTypeClick=(item)=>{
    startDate.value=''
    endDate.value=''
    dateType.value=item.value
    getChartInfo()
} 

let calendarType=ref('')//季节图 公历/农历
// 公历/农历切换
const calendarTypeChange=(val)=>{
    calendarType.value=val
    // startDate.value=''
    // endDate.value=''
    getChartInfo()
}


// 获取详情
let ChartInfoId=route.query.ChartInfoId
let chartSource = Number(route.query.chartSource); //图表来源 1 eta图 2商品价格图 3相关性图表
let chartData=ref({
    series:[],
    xAxis:[],
    yAxis:[],

})// 图表配置数据
let resData=ref(null)//接口详情数据
let loading=ref(false)
const sameOptionType = ref([1,3,4,5,6]);//筛选框一样的图表类型 曲线/面积/柱状/散点/组合 常规图
const chartItemStyleArr = ref([
    { label: '曲线图', key: 1 ,value: 'spline'},
    { label: '面积图', key: 3 ,value: 'areaspline'},
    { label: '柱状图', key: 4 ,value: 'column'},
    { label: '散点图', key: 5 ,value: 'scatter'}
])//组合图配置时可选类型

let nodata=ref(false)
let noauth=ref(false)
let noAuthData=ref(null)

const minDate=ref(null)
const earliestDate=ref(null)
const latestDate=ref(null)

// 设置 起始日期 和 最新日期
const setExtremumDate=(list)=>{
    //过滤、排序 拿到起始日期
    let startDateList = list.map(it => it.StartDate)
                                    .filter(Boolean)
                                    .sort((a,b)=> new Date(a).getTime() - new Date(b).getTime())
    earliestDate.value = moment(startDateList[0]).format('YYYY-MM-DD')
    //过滤、排序 拿到最新日期
    let endDateList = list.map(it => it.LatestDate)
                                    .filter(Boolean)
                                    .sort((a,b)=> new Date(b).getTime() - new Date(a).getTime())
    latestDate.value = moment(endDateList[0]).format('YYYY-MM-DD')
    minDate.value = new Date(earliestDate.value)
    // console.log(earliestDate.value,latestDate.value,'this.latestDate');
    setTypeDate()
}
// dateType为6和20需要 设置时间
const setTypeDate=()=>{
    // 6代表 至今  20代表最近几年
    if(dateType.value==6){
        endDate.value=latestDate.value || ''
    }else if(dateType.value==20){
        let latestYear = parseInt(latestDate.value.substring(0,4))
        startDate.value = `${latestYear-startYear.value+1}-01-01`
        endDate.value=`${latestYear}-12-31`
    }
    // 设置选择器回显
    dateRangeStart.value = new Date(startDate.value)
    dateRangeEnd.value = new Date(endDate.value)
}

// 如果type：init 则是初始化获取数据 
const getChartInfo=async (type)=>{
    // resData.value=null
    loading.value=true

    //通用类根据code获取详情
    if(![1,11,12].includes(chartSource)) return getCommonChartDetail();

    let res=null
    // 如果是从我的图库中来的
    if(route.query.source=='ybxcx_my_chart'){
        res=await apiMyChartDetail({
            ChartInfoId:ChartInfoId,
        })
    }else{
        res=await apiChartInfo({
            ChartInfoId:ChartInfoId,
            DateType:dateType.value,
            // 季节性图也改成了 StartDate和EndDate
            StartDate:startDate.value&&[...sameOptionType.value,2].includes(resData.value.ChartInfo.ChartType)?startDate.value:'',
            EndDate:endDate.value&&[...sameOptionType.value,2].includes(resData.value.ChartInfo.ChartType)?endDate.value:'',
            Calendar:calendarType.value,
            Authorization:route.query.token,
            MyChartClassifyId:Number(route.query.MyChartClassifyId)
        })
    }
    loading.value=false
    if(res.code===200){
        nodata.value=false
        resData.value=res.data
        // document.title=res.data.ChartInfo.ChartName
        
        // 设置highchart配置 ChartType: 1曲线图 2季节图:季节图中公历和农历数据结构不同
        if(type=='init'&&[1,3,4,5,6].includes(res.data.ChartInfo.ChartType)){
            dateType.value=res.data.ChartInfo.DateType
            startYear.value=res.data.ChartInfo.StartYear
            startDate.value=res.data.ChartInfo.StartDate||''
            endDate.value=res.data.ChartInfo.EndDate||''
            calendarType.value=res.data.ChartInfo.Calendar||'公历' 

            setExtremumDate(resData.value.EdbInfoList||[])
        }

        if(type=='init'&&res.data.ChartInfo.ChartType===2){
            dateType.value=res.data.ChartInfo.DateType
            startYear.value=res.data.ChartInfo.StartYear
            startDate.value=res.data.ChartInfo.SeasonStartDate||''
            endDate.value=res.data.ChartInfo.SeasonEndDate||''
            calendarType.value=res.data.ChartInfo.Calendar||'公历'
            setExtremumDate(resData.value.EdbInfoList||[])
        }


        chartData.value = useChartRender(res.data)
        
        // 向小程序发送分享数据
        let postData = {
            params:{
                chartInfoId:ChartInfoId,
                searchVal:decodeURIComponent(route.query.searchVal)||'',
                chartSource,
                MyChartId:route.query.MyChartId||'',
                MyChartClassifyId:route.query.MyChartClassifyId||'',
            },
            title: res.data.ChartInfo.ChartName,
            shareImg:res.data.ChartInfo.ChartImage
        };
        wx.miniProgram.postMessage({ data: postData });
        

    }else if(res.code==403){
        noauth.value=true
        noAuthData.value=res.data
    }else if(res.code===4003){//图表不存在
        console.log('图表不存在');
        nodata.value=true
    }
}

//获取图表详情 除source:1外
const getCommonChartDetail=async ()=>{
    const res = await apiCommonChartDetail({ChartInfoId})
    loading.value=false
    if(res.code===200){
        resData.value=res.data

        chartData.value = useChartRender(res.data)

        // 向小程序发送分享数据
        let postData = {
            params:{
                chartInfoId:ChartInfoId,
                searchVal:decodeURIComponent(route.query.searchVal)||'',
                chartSource,
                MyChartId:route.query.MyChartId||'',
                MyChartClassifyId:route.query.MyChartClassifyId||'',
            },
            title: res.data.ChartInfo.ChartName,
            shareImg:res.data.ChartInfo.ChartImage
        };
        wx.miniProgram.postMessage({ data: postData });

    }else if(res.code==403){
        noauth.value=true
        noAuthData.value=res.data
    }
}
getChartInfo('init')



// 路由改变 解决从搜索页返回数据不刷新问题
onBeforeRouteUpdate((nval)=>{
    console.log('路由改变',nval);
    ChartInfoId=nval.query.ChartInfoId;
    chartSource= Number(nval.query.chartSource);
    chartData.value = {}
    dateType.value=null
    startDate.value=''
    endDate.value=''

    getChartInfo('init')
})

// 上下线设置
let showLimit=ref(false)
// let hasLeftAxis=ref(false)//是否有左轴
// let hasRightAxis=ref(false)//是否有右轴
// let hasRightTwoAxis=ref(false)//是否有右2轴
// let axisLimitData=reactive({//左右轴极值
//     leftMin:0,
//     leftMax:0,
//     rightMin:0,
//     rightMax:0,
//     rightTwoMin:0,
//     rightTwoMax:0,
//     xMin:0,
//     xMax:0,
// })
const handleConfirmSetLimit=()=>{//确定修改极值（研究员会调用一次保存）
    if(canSave.value){
        handleSaveChart()
    }
    showLimit.value=false
}
const handleCloseLimit=()=>{//点击遮罩层关闭弹窗或者点击取消关闭
    getChartInfo()
    showLimit.value=false
}


// 监听极值变化
watch(
    ()=>axisLimitData,
    (nval)=>{
        // 只有当修改极值弹窗弹起时才去修改
        if(!showLimit.value) return
        console.log('极值改变');

        //奇怪柱状图 商品价格图
        if([7,10,11].includes(resData.value.ChartInfo.ChartType) || resData.value.ChartInfo.Source === 2) {
            chartData.value.yAxis[0].max = nval.leftMax;
            chartData.value.yAxis[0].min = nval.leftMin;
            
            if(resData.value.ChartInfo.ChartType === 10) {
                chartData.value.xAxis.max = nval.xMax;
                chartData.value.xAxis.min = nval.xMin;
            }
        }else {
            chartData.value.yAxis.forEach(item=>{
                if(item.IsAxis===1){//左轴
                    item.min=nval.leftMin
                    item.max=nval.leftMax
                }else if(item.IsAxis===2){ //右2
                    item.min=nval.rightTwoMin
                    item.max=nval.rightTwoMax
                }else{
                    item.min=nval.rightMin
                    item.max=nval.rightMax
                }
            })
        }
    },
    {
        deep:true
    }
)

// 前去搜索
const handleGoSearch=()=>{
    router.push({
        path:'/hzyb/chart/search',
        query:{
            token:route.query.token
        }
    })
}

// 获取当前图表
let searchVal=decodeURIComponent(route.query.searchVal)
let searchListData=ref([])//搜索的数据
const getSearchListData=async ()=>{
    const res=await apiChartList({Keywords:searchVal,Page:1,Limit:10000,Authorization:route.query.token})
    if(res.code===200){
        searchListData.value=res.data
    }
}

let chartBeforeAndNextData=ref(null)

// 翻页
const pageChange=async (type)=>{
    // 搜索情况
    if(searchVal){
        if(type==='before'){
            let index=searchListData.value.findIndex(item=>item.ChartInfoId==resData.value.ChartInfo.ChartInfoId)
            if(!searchListData.value[index-1]){
                Toast('当前已是第一张图')
            }else{
                calendarType.value=''
                router.replace({
                    query:{
                        ...route.query,
                        ChartInfoId:searchListData.value[index-1].ChartInfoId,
                        chartSource: searchListData.value[index-1].Source
                    }
                })
            }
        }
        if(type==='next'){
            let index=searchListData.value.findIndex(item=>item.ChartInfoId==resData.value.ChartInfo.ChartInfoId)
            if(!searchListData.value[index+1]){
                Toast('当前已是最后一张图')
            }else{
                calendarType.value=''
                router.replace({
                    query:{
                        ...route.query,
                        ChartInfoId:searchListData.value[index+1].ChartInfoId,
                        chartSource: searchListData.value[index+1].Source
                    }
                })
            }
        }

        return
    }

    // 非搜索情况可切换分类
    const res=await apiChartBeforeAndNext({
        MyChartId:route.query.MyChartId,
        MyChartClassifyId:route.query.MyChartClassifyId,
        Authorization:route.query.token
    })
    if(res.code===200){
        chartBeforeAndNextData.value=res.data
        if(type==='before'){
            if(chartBeforeAndNextData.value.PrevChart.ChartInfoId===0){
                Toast('当前已是第一张图')
            }else{
                if(chartBeforeAndNextData.value.PrevChart.Switch){
                    let temStr=chartBeforeAndNextData.value.PrevChart.MyChartClassifyName
                    setTimeout(() => {
                        Toast({
                            message:`您正在浏览${temStr}中的图表`,
                            duration: 3000,
                        })
                    }, 500);
                }
                calendarType.value=''
                router.replace({
                    query:{
                        ...route.query,
                        ChartInfoId:chartBeforeAndNextData.value.PrevChart.ChartInfoId,
                        chartSource: chartBeforeAndNextData.value.PrevChart.ChartInfoSource,
                        MyChartId:chartBeforeAndNextData.value.PrevChart.MyChartId,
                        MyChartClassifyId:chartBeforeAndNextData.value.PrevChart.MyChartClassifyId,
                        token:route.query.token
                    }
                })
            }
        }else if(type==='next'){
            if(chartBeforeAndNextData.value.NextChart.ChartInfoId===0){
                Toast('当前已是最后一张图')
            }else{
                if(chartBeforeAndNextData.value.NextChart.Switch){
                    let temStr=chartBeforeAndNextData.value.NextChart.MyChartClassifyName
                    setTimeout(() => {
                        Toast({
                            message:`您正在浏览${temStr}中的图表`,
                            duration: 3000,
                        })
                    }, 500);
                }
                calendarType.value=''
                router.replace({
                    query:{
                        ...route.query,
                        ChartInfoId:chartBeforeAndNextData.value.NextChart.ChartInfoId,
                        chartSource: chartBeforeAndNextData.value.NextChart.ChartInfoSource,
                        MyChartId:chartBeforeAndNextData.value.NextChart.MyChartId,
                        MyChartClassifyId:chartBeforeAndNextData.value.NextChart.MyChartClassifyId,
                        token:route.query.token
                    }
                })
                
            }
        }
    }
    
}

onMounted(()=>{
    if(searchVal){
        getSearchListData()
    }
})

// 保存
const handleSaveChart=async ()=>{
    let params = [2,5].includes(resData.value.ChartInfo.Source)
        ? { 
            ChartInfoId:resData.value.ChartInfo.ChartInfoId,
            LeftMin: String(axisLimitData.leftMin),
            LeftMax: String(axisLimitData.leftMax)
          } 
        : setChartParams()
    
    const res = [2,5].includes(resData.value.ChartInfo.Source)
        ? await apiCommonChartSave(params)
        : await apiChartSave(params)
    if(res.code===200){
        Toast.success('保存成功')
    }
}

//设置请求参
const setChartParams = () => {
    let params={}
    if(sameOptionType.value.includes(resData.value.ChartInfo.ChartType)){//曲线图
        let arr=chartData.value.yAxis.map(item=>{
            return {
                ChartColor: item.chartEdbInfo.ChartColor,
                ChartStyle: item.chartEdbInfo.ChartStyle,
                ChartWidth: Number(item.chartEdbInfo.ChartWidth),
                EdbInfoId: item.chartEdbInfo.EdbInfoId,
                EdbInfoType: item.chartEdbInfo.EdbInfoType,
                IsAxis: item.chartEdbInfo.IsAxis,
                IsOrder: item.chartEdbInfo.IsOrder,
                LeadUnit: item.chartEdbInfo.EdbInfoType ? '' : item.chartEdbInfo.LeadUnit,
                LeadValue: item.chartEdbInfo.EdbInfoType ? 0 : Number(item.chartEdbInfo.LeadValue),
                MaxData: Number(item.max),
                MinData: Number(item.min),
            }
        })
        params={
            ChartInfoId: resData.value.ChartInfo.ChartInfoId || 0,
            ChartEdbInfoList: arr,
            DateType: dateType.value,
            StartDate:startDate.value,
            EndDate: endDate.value,
        }
    }
    switch(resData.value.ChartInfo.ChartType) {
        case 2: 
            let arr=resData.value.EdbInfoList.map(item=>{
                return {
                    ChartColor: item.ChartColor,
                    ChartStyle: item.ChartStyle,
                    ChartWidth: Number(item.ChartWidth),
                    EdbInfoId: item.EdbInfoId,
                    EdbInfoType: item.EdbInfoType,
                    IsAxis: item.IsAxis,
                    IsOrder: item.IsOrder,
                    LeadUnit: item.EdbInfoType ? '' : item.LeadUnit,
                    LeadValue: item.EdbInfoType ? 0 : Number(item.LeadValue),
                    MaxData: Number(chartData.value.yAxis[0].max),
                    MinData: Number(chartData.value.yAxis[0].min),
                }
            })
            params={
                ChartInfoId: resData.value.ChartInfo.ChartInfoId || 0,
                ChartEdbInfoList: arr,
                DateType: dateType.value,
                Calendar: calendarType.value,
                StartDate:startDate.value,
                EndDate: endDate.value,
            }
            break;
        case 7:
            params={
                ChartInfoId: resData.value.ChartInfo.ChartInfoId || 0,
                ChartEdbInfoList: barEdbData.value.map(_ =>({ EdbInfoId: _.EdbInfoId })),
                DateType: 6,
                LeftMin: String(axisLimitData.leftMin),
                LeftMax: String(axisLimitData.leftMax),
            }
            break;
        case 10: 
            params = {
                ChartInfoId: resData.value.ChartInfo.ChartInfoId || 0,
                DateType: 6,
                Calendar: "公历",
                ExtraConfig: JSON.stringify({
                    ...JSON.parse(resData.value.ChartInfo.ExtraConfig),
                    XMinValue: String(axisLimitData.xMin),
                    XMaxValue: String(axisLimitData.xMax),
                    YMinValue: String(axisLimitData.leftMin),
                    YMaxValue: String(axisLimitData.leftMax),
                })
            } 
            break;
        
        case 11: 
            params={
                ChartInfoId: resData.value.ChartInfo.ChartInfoId || 0,
                ChartEdbInfoList: resData.value.EdbInfoList.map(_ =>({ EdbInfoId: _.EdbInfoId })),
                DateType: 6,
                LeftMin: String(axisLimitData.leftMin),
                LeftMax: String(axisLimitData.leftMax),
            }
            break;

    }
    
    return params
}

// 刷新图表
const handleRefreshChart=async ()=>{
    let res=null 
    if([1,6,7,8,9,10].includes(resData.value.ChartInfo.Source)){
        res=await apiChartRefresh({ChartInfoId:Number(ChartInfoId)})
    }else if([2,5].includes(resData.value.ChartInfo.Source)){
        res=await apiCommonChartRefresh({ChartInfoId:Number(ChartInfoId)})
    }else if([3,4].includes(resData.value.ChartInfo.Source)){
        res=await apiRelevanceChartRefresh({ChartInfoId:Number(ChartInfoId)})
    }
    if(res.code===200){
        setTimeout(() => {
            Toast.success(res.msg)
        }, 200);
        getChartInfo()
    }
}

let pageBoxPosition=reactive({
    top:window.innerHeight-165,
    left:window.innerWidth-50,
    temTop:0,
    temLeft:0,
})

const pageTouchmove=(e)=>{
    const touchObj=e.touches[0]
    let top=touchObj.clientY-82
    let left=touchObj.clientX-25
    if(left<=0){
        left=0
    }
    if(left>window.innerWidth-50){
        left=window.innerWidth-50
    }
    if(top<=0){
        top=0
    }
    if(top>window.innerHeight-115){
        top=window.innerHeight-115
    }

    pageBoxPosition.top=top
    pageBoxPosition.left=left

    event.preventDefault();//阻止页面移动
}

// 生成海报所需跳转到小程序页面参数
const code_scene=computed(()=>{
    let obj= {
        chartInfoId:ChartInfoId,
        searchVal:decodeURIComponent(route.query.searchVal)||'',
        chartSource,
        MyChartId:route.query.MyChartId||'',
        MyChartClassifyId:route.query.MyChartClassifyId||'',
        from:'share'
    }
    return JSON.stringify(obj)
})
// 生成海报图片所需要的数据
const posterParams=computed(()=>{
    return {
        chart_name:resData.value.ChartInfo.ChartName,
        chart_image:resData.value.ChartInfo.ChartImage
    }
})

/* 折叠source */
const sourceColl = ref(false)
const sourceIconShow=ref(null)
let timer = null
let count = 0
onMounted(()=>{
    timer=setInterval(()=>{
        count++
        if($('.source-item')[0]){
            // 就为了判断是否显示折叠icon
            sourceIconShow.value = $('.source-item')[0].offsetHeight>=$('.source-box')[0].offsetHeight
            clearInterval(timer)
        }else if(count>=30){
            // 预防
            clearInterval(timer)
        }
    },100)
})

// 获取我的图库中切换上一张下一张的数据
let myChartPageChangeList=ref([])
let myChartCurIndex=-1
const getMychartPageChangeData=async ()=>{
    const res=await apiMyChartChangeChartList({classify_id:route.query.classifyId?Number(route.query.classifyId):''})
    if(res.code===200){
        const arr=res.data||[]
        myChartPageChangeList.value=arr
        // 从列表来的
        if(!route.query.classifyId){
            myChartCurIndex=arr.findIndex(e=>e.chart_info_id==route.query.ChartInfoId)
        }else{
            myChartCurIndex=arr.findIndex(e=>e.my_chart_classify_id==route.query.classifyId&&e.chart_info_id==route.query.ChartInfoId)
        }
        
    }
}
if(route.query.source==='ybxcx_my_chart'){
    getMychartPageChangeData()
}
const myChartPageChange=(type)=>{
    console.log(myChartCurIndex);
    if(myChartCurIndex==-1) return
    if(type==='before'){
        if(myChartCurIndex==0){
            Toast('当前已是第一张')
        }else{
            myChartCurIndex--
            ChartInfoId=myChartPageChangeList.value[myChartCurIndex].chart_info_id
            chartSource=myChartPageChangeList.value[myChartCurIndex].chart_info_source
            console.log(ChartInfoId);
            getChartInfo('init')
        }
    }else{
        if(myChartCurIndex==myChartPageChangeList.value.length-1){
            Toast('当前已是最后一张')
        }else{
            myChartCurIndex++
            ChartInfoId=myChartPageChangeList.value[myChartCurIndex].chart_info_id
            chartSource=myChartPageChangeList.value[myChartCurIndex].chart_info_source
            getChartInfo('init')
        }
    }
}

</script>

<template>
    <div class="chart-detail" v-if="!loading&&!noauth&&!nodata">
        <div 
            class="chart-title"
            :style="resData.ChartInfo.ChartThemeStyle?`
                text-align:${JSON.parse(resData.ChartInfo.ChartThemeStyle).titleOptions.align};
                font-size:${JSON.parse(resData.ChartInfo.ChartThemeStyle).titleOptions.style.fontSize}px;
                color:${JSON.parse(resData.ChartInfo.ChartThemeStyle).titleOptions.style.color}
            `:''"
        >
            {{resData.ChartInfo.ChartName}}
        </div>
        <div class="top-box" v-if="$route.query.source!=='ybxcx_my_chart'">
            <div class="flex calendar-box" :style="{'color':startDate?'#1F243A':'#999999'}"
            @click="handleShowDate" v-if="![7,10,11,14].includes(resData.ChartInfo.ChartType) &&resData.ChartInfo.Source===1">
                <img src="../../../assets/hzyb/chart/calendar-new-1.png" alt="">
                <span class="date">{{startDate||'开始日期'}}</span>
                <span style="margin:0 5px">-</span>
                <span class="date">{{endDate||'结束日期'}}</span>
            </div>
            <img class="icon search-icon" src="../../../assets/hzyb/chart/search-new-1.png" alt="" @click="handleGoSearch">
            <share-poster 
                :isSlot="true"
                :shareData="{
                    type:'chart_detail',
                    code_scene:code_scene,
                    code_page:'pages-chart/chartDetail',
                    data:posterParams
                }"
            >
                <!-- <img class="icon" src="@/assets/hzyb/share-poster-chart-icon.png" alt=""> -->
            </share-poster>
            <!-- <img class="icon" src="../../../assets/hzyb/chart/save.png" alt="" @click="handleSaveChart" v-if="canSave&&![3,4,6,7,8,9].includes(chartSource)">
            <img class="icon" src="../../../assets/hzyb/chart/refresh.png" alt="" @click="handleRefreshChart"> -->
            <img class="icon" src="../../../assets/hzyb/chart/more.png" alt="" @click="actionSheetShow=true">
            <ActionSheet v-model:show="actionSheetShow" cancel-text="确定" :actions="actions" 
            @select="onActionSelect" close-on-click-action />
        </div>
        
        <collectBox 
            v-if="$route.query.source=='ybxcx_my_chart'"
            :code="resData.ChartInfo.UniqueCode"
            :myChartInfo="resData.MyChartInfo"
        />

        <chartBox :options='chartData' :chartInfo="resData.ChartInfo" v-if="!loading"></chartBox>

        <div :class="['source-box flex',{'un-coll-sty':sourceColl,'coll-sty': !sourceColl}]" v-if="$route.query.source=='ybxcx_my_chart'">

                <!-- 自定义来源 -->
            <div class="source-item" 
                v-if="resData.ChartInfo.SourcesFrom&&JSON.parse(resData.ChartInfo.SourcesFrom).isShow"
                :style="`
                    color: ${ JSON.parse(resData.ChartInfo.SourcesFrom).color };
                    font-size: ${ JSON.parse(resData.ChartInfo.SourcesFrom).fontSize }px;
                `"
            >
                数据来源：{{ JSON.parse(resData.ChartInfo.SourcesFrom).text}}
            </div>

            <span class="source-item" v-else>数据来源：{{resData&&resData.ChartInfo.ChartSource}}</span>

             <!-- 图表说明 -->
            <div 
                class="chart-instruction text_oneLine"
                v-if="resData.ChartInfo.Instructions&&JSON.parse(resData.ChartInfo.Instructions).isShow"
                v-text="JSON.parse(resData.ChartInfo.Instructions).text"
                :style="`
                color: ${JSON.parse(resData.ChartInfo.Instructions).color};
                fontSize: ${ JSON.parse(resData.ChartInfo.Instructions).fontSize }px
                `"
            ></div>
            
        </div>

        <template v-if="$route.query.source!=='ybxcx_my_chart'">
        <div class="flex source-box">
            <!-- <div :style="{flex:resData&&resData.ChartInfo.ChartType===2?1:2}"><span v-if="resData&&resData.ChartInfo.ChartType!==2">来源：{{resData&&resData.ChartInfo.ChartSource}}</span></div> -->
            <div class="season-change-box" style="flex:1" v-if="resData&&resData.ChartInfo.ChartType===2">
                <span :class="calendarType==='农历'&&'active'" @click="calendarTypeChange('农历')">农历</span>
                <span :class="calendarType==='公历'&&'active'" @click="calendarTypeChange('公历')">公历</span>
            </div>
            <span style="color:#E3B377;flex:1;text-align:right" @click="showLimit=true" v-if="[1,2,5].includes(resData.ChartInfo.Source)">上下限设置</span>
        </div>
        <div :class="['source-box flex',{'un-coll-sty':sourceColl,'coll-sty': !sourceColl}]">
            <!-- 自定义来源 -->
            <div class="source-item" 
                v-if="resData.ChartInfo.SourcesFrom&&JSON.parse(resData.ChartInfo.SourcesFrom).isShow"
                :style="`
                    color: ${ JSON.parse(resData.ChartInfo.SourcesFrom).color };
                    font-size: ${ JSON.parse(resData.ChartInfo.SourcesFrom).fontSize }px;
                `"
            >
                数据来源：{{ JSON.parse(resData.ChartInfo.SourcesFrom).text}}
            </div>
            <span class="source-item" v-else>数据来源：{{resData&&resData.ChartInfo.ChartSource}}</span>
            
            <!-- 图表说明 -->
            <div 
                class="chart-instruction text_oneLine" 
                v-if="resData.ChartInfo.Instructions&&JSON.parse(resData.ChartInfo.Instructions).isShow"
                v-text="JSON.parse(resData.ChartInfo.Instructions).text"
                :style="`
                color: ${JSON.parse(resData.ChartInfo.Instructions).color};
                fontSize: ${ JSON.parse(resData.ChartInfo.Instructions).fontSize }px
                `"
            ></div>
        </div>

        <!-- 日期类型 -->
        <div class="date-type-box" v-if="resData&&sameOptionType.includes(resData.ChartInfo.ChartType)&&resData.ChartInfo.Source===1">
            <div 
                :class="['item',item.value==dateType?'active':'']" 
                v-for="item in dateTypeList" 
                :key="item.value"
                @click="dateTypeClick(item)"
            >{{item.name}}</div>
        </div>

        <!-- 最新值 -->
        <div class="latest-value-wrap" v-if="resData&&resData.ChartInfo.Source===1" 
        :class="{'marginTopZone': sameOptionType.includes(resData.ChartInfo.ChartType)}">
            <!-- <p style="margin-bottom:10px">最新数值</p> -->
            <ul class="list same-option-type-list" v-if="sameOptionType.includes(resData.ChartInfo.ChartType)">
                <li v-for="item in chartData.series" :key="item.name">
                    <p style="color:#333">{{moment(item.LatestDate).format('YYYY-MM-DD')}}</p>
                    <p :style="{color:item.color,flex:1}">{{item.name.length>20?item.name.replace(/<br>/g,''):item.name}}</p>
                    <p style="color:#1F243A">{{item.LatestValue}}</p>
                </li>
            </ul>
            <!-- 季节图 -->
            <ul class="list" v-else-if="resData.ChartInfo.ChartType===2">
                <li>
                    <p style="color:#333">{{latestDate}}</p>
                    <p :style="{color:resData.EdbInfoList[0].ChartColor,flex:1}">{{resData.ChartInfo.ChartName}}</p>
                    <p style="color:#1F243A">{{resData.EdbInfoList[0].LatestValue}}</p>
                </li>
            </ul>
            <!-- 奇怪柱状图 -->
            <ul class="list" v-else-if="resData.ChartInfo.ChartType===7">
                <li v-for="item in barEdbData" :key="item.EdbInfoId">
                    <p style="color:#333">{{moment(item.LatestDate).format('YYYY-MM-DD')}}</p>
                    <p style="{color:#333,flex:1}">{{item.EdbName.length>20?item.EdbName.replace(/<br>/g,''):item.EdbName}}</p>
                    <p style="color:#1F243A">{{item.LatestValue}}</p>
                </li>
            </ul>
        </div>
        </template>

        <!-- 上一张下一张图切换 -->
        <div 
            v-if="$route.query.from!='share'&&$route.query.source!=='ybxcx_my_chart'"
            class="change-page-wrap" 
            :style="{left:pageBoxPosition.left+'px',top:pageBoxPosition.top+'px'}"
            @touchmove.stop="pageTouchmove"
            @touchstart.stop="pageTouchStart"
        >
            <div class="top" @click.stop="pageChange('before')"></div>
            <div class="bot" @click.stop="pageChange('next')"></div>
        </div>

        <!-- 我的图库进入的详情上一张下一张切换 -->
        <div 
            v-if="$route.query.source==='ybxcx_my_chart'"
            class="change-page-wrap" 
            :style="{left:pageBoxPosition.left+'px',top:pageBoxPosition.top+'px'}"
            @touchmove.stop="pageTouchmove"
            @touchstart.stop="pageTouchStart"
        >
            <div class="top" @click.stop="myChartPageChange('before')"></div>
            <div class="bot" @click.stop="myChartPageChange('next')"></div>
        </div>

        <!-- 日期选择 -->
        <!-- 属于同个弹窗多个picker选择多个值，vant4.0以上有 现成组件替换
            这个项目涉及到多个项目，升级vant4.0的兼容处理难于调试
            这里暂时使用多个组件自定义，后续有更新至vant4.0，可以进行修改 -->
        <Popup
            v-model:show="showDate"
            position="bottom"
            round
        >   
            <div class="custom-popup-top">
                <div class="popup-top-item popup-top-cancel">
                    <span @click="showDate=false">取消</span>
                </div>
                <div class="popup-top-item popup-top-title">
                    {{ pickerInfo.tabIndex==1?'选择起始时间':'选择结束时间' }}
                </div>
                <div class="popup-top-item popup-top-confirm">
                    <span @click="handleConfirmDate">确认</span>
                </div>
            </div>
            <Tabs color="#E3B377" v-model:active="pickerInfo.tabIndex"
            line-width="16px" border swipeable title-active-color="#E3B377"
            title-inactive-color="#333333">
                <Tab title="开始时间" name="1">
                    <!-- <Picker ref="startPicker" @confirm="e=> DateConfirm(e,'start')" 
                        :columns="columnsStart" :show-toolbar="false"/> -->
                    <DatetimePicker
                        v-model="dateRangeStart"
                        :min-date="minDate"
                        type="date"
                        :show-toolbar="false"
                        ref="startPicker" 
                        @confirm="e=> DateConfirm(e,'start')" 
                    ></DatetimePicker>
                </Tab>
                <Tab title="结束时间" name="2">
                    <!-- <Picker ref="endPicker" @confirm="e=> DateConfirm(e,'end')" 
                        :columns="columnsEnd" :show-toolbar="false"/> -->
                    <DatetimePicker
                        v-model="dateRangeEnd"
                        type="date"
                        :min-date="minDate"
                        :show-toolbar="false"
                        ref="endPicker" 
                        @confirm="e=> DateConfirm(e,'end')" 
                    ></DatetimePicker>
                </Tab>
            </Tabs>
        </Popup>

        <!-- 上下限设置 -->
        <Popup
            v-model:show="showLimit"
            position="bottom"
            :overlay-style="{background:'rgba(0,0,0,0)'}"
            @click-overlay="handleCloseLimit"
        >
            <div class="set-limit-box">
                <div class="flex limit-top">
                    <span style="color:#A7A7A7" @click="handleCloseLimit">取消</span>
                    <span>上下限设置</span>
                    <span style="color:#E3B377" @click="handleConfirmSetLimit">确定</span>
                </div>
                <div class="con">
                    <p style="margin:20px 0" class="top">
                        <span>上限</span>
                        <span>下限</span>
                    </p>
                    <p style="margin-bottom:25px" v-if="hasLeftAxis">
                        <span style="margin-right:35px">{{resData.ChartInfo.ChartType===10 ? 'Y轴' :'左轴'}}</span>
                        <input type="number" v-model="axisLimitData.leftMax">
                        <span style="margin:0 10px">至</span>
                        <input type="number" v-model="axisLimitData.leftMin">
                    </p>
                    <p v-if="hasRightAxis" style="margin-bottom:25px">
                        <span style="margin-right:35px">右轴</span>
                        <input type="number" v-model="axisLimitData.rightMax">
                        <span style="margin:0 10px">至</span>
                        <input type="number" v-model="axisLimitData.rightMin">
                    </p>
                    <!-- 右2上下限 -->
                    <p v-if="hasRightTwoAxis" style="margin-bottom:25px">
                        <span style="margin-right:35px">右2轴</span>
                        <input type="number" v-model="axisLimitData.rightTwoMax">
                        <span style="margin:0 10px">至</span>
                        <input type="number" v-model="axisLimitData.rightTwoMin">
                    </p>
                    <!-- x轴上下限 -->
                    <p v-if="axisLimitData.xMin" style="margin-bottom:25px">
                        <span style="margin-right:35px">X轴</span>
                        <input type="number" v-model="axisLimitData.xMax">
                        <span style="margin:0 10px">至</span>
                        <input type="number" v-model="axisLimitData.xMin">
                    </p>
                </div>
            </div>
        </Popup>
    </div>
    <!-- 无权限 -->
    <noAuth v-if="noauth&&!nodata" :data="noAuthData"></noAuth>
    <!-- 图表不存在 -->
    <div class="chart-nodata" v-if="nodata">
        <p style="text-align:center;padding-top:200px;font-size:16px">该图表已被删除!</p>
        <collectBox 
            v-if="$route.query.source=='ybxcx_my_chart'"
            :code="$route.query.chartCode"
            :isNodata="true"
        />
        <!-- 我的图库进入的详情上一张下一张切换 -->
        <div 
            v-if="$route.query.source==='ybxcx_my_chart'"
            class="change-page-wrap" 
            :style="{left:pageBoxPosition.left+'px',top:pageBoxPosition.top+'px'}"
            @touchmove.stop="pageTouchmove"
            @touchstart.stop="pageTouchStart"
        >
            <div class="top" @click.stop="myChartPageChange('before')"></div>
            <div class="bot" @click.stop="myChartPageChange('next')"></div>
        </div>
    </div>
</template>

<style lang="scss" scoped>
::v-deep(.highcharts-axis-title) {
    font-size: 20px;
    @media (min-width: 768px){
        font-size: 16px;
    }
}
.chart-nodata{
    .change-page-wrap{
        position: fixed;
        right: 0;
        bottom: 50px;
        width: 50PX;
        height: 115PX;
        background-image: url('../../../assets/hzyb/chart/before-next.png');
        background-size: cover;
        z-index: 10;
        .top,.bot{
            height: 50%;
        }

    }
}
.chart-detail{
    .flex{
        display: flex;
    }
    .chart-title{
        padding: 40px 34px 20px 34px;
        font-size: 32px;
        font-weight: bold;
        color: #1F243A;
        letter-spacing: 2px;
        @media (min-width: 768px){
            padding: 0px 0 20px 0;
            font-size: 18px;
        }
    }
    .top-box{
        padding: 0 34px 0 34px;
        // height: 40px;
        display: flex;
        align-items: center;
        .calendar-box{
            align-items: center;
            background-color:#F6F6F6 ;
            padding: 11px 30px;
            border-radius: 99px;
            width: 466px;
            img{
                width: 48px;
                height: 48px;
                margin-right: 18px;
            }
            .date{
                width: 150px;
                height: 40px;
                // background: #F6F6F6;
                // border: 1px solid #E5E5E5;
                border-radius: 4px;
                text-align: center;
                line-height: 44px;
                font-size: 24px;
                // color: #1F243A;
            }
        }
        .icon{
            // float: right;
            width: 70px;
            height: 70px;
            margin-left: 30px;
        }
        .search-icon{
            margin-left: 40px;
        }
    }
    .select-date-box-head{
        padding: 40px 34px;
        justify-content: space-between;
    }
    .select-date-box{
        // height:50vh;
        .left,.right{
            flex: 1;
        }
    }

    

    .source-box{
        padding: 0 70px 0 34px;
        justify-content: space-between;
        align-items: center;
        font-size: 28px;
        margin-bottom: 10px;
        width: 100vw;
        margin-top: 50px;
        position: relative;
        &.coll-sty {
            /* height: 40px; */
            margin-top:10px;
            overflow:hidden;
        }
        &.un-coll-sty {
            height: auto;margin-top:10px
        }
        .slide-icon {
            position:absolute;
            right: 30px;
            top: 50%;
            transform: translateY(-50%);
        }
        .season-change-box{
            height: 50px;
            margin-bottom: 10px;
            padding-right: 34px;
            span{
                display: inline-block;
                width: 100px;
                line-height: 50px;
                text-align: center;
                border: 1px solid #ededed;
                float: right;
                border-radius: 4px;
                &:first-child{
                    border-left: none;
                }
                &:last-child{
                    border-right: none;
                }
            }

            .active{
                color: #fff;
                background-color: #E3B377;
            }
        }
        @media (min-width: 768px){
            padding: 0;
            font-size: 16px;
        }
        .source-item {
            width: 30%;
            min-width: 150px;
            flex-shrink: 0;
        }
        .chart-instruction {
            flex: 1;
            max-width: 70%;
            margin-left: auto;
            text-align: right;
        }
    }

    .date-type-box{
        padding: 0 34px;
        margin-top: 38px;
        display: flex;
        overflow-x: auto;
        border-bottom: 1px solid #F6F6F6;
        .item{
            // flex: 1;
            width: 20vw;
            padding: 0 8px;
            text-align: center;
            font-size: 24px;
            padding-bottom: 14px;
            color: #1F243A;
        }
        .active{
            color: #E3B377;
            border-bottom: 6px solid #E3B377;
        }
    }

    .van-tabs{
        border-bottom: 1px solid #F6F6F6;
    }

    .latest-value-wrap{
        margin-top: 60px;
        padding: 0 34px;
        margin-bottom: 30px;
        .list{
            box-sizing: border-box;
            li{
                display: flex;
                justify-content: space-between;
                align-items: flex-start;
                padding: 30px 0;
                width: 100%;
                box-sizing: border-box;
                border-top: 1px solid #F6F6F6;
                text-align: center;
                font-size:24px;
                box-sizing: border-box;
                // &:nth-child(odd){
                //     border-right: 1px solid #F6F6F6;
                // }
                p:nth-child(1){
                    width: 150px;
                    flex-shrink: 0;
                }
                p:nth-child(3){
                    flex-shrink: 0;
                    font-size: 28px;
                    width: 150px;
                    line-height: 1;
                    position: relative;
                    top: 3px;
                }
            }
            .one{
                flex: 1;
                border-right: none !important;
            }
        }
        .same-option-type-list{
            li{
                &:first-child{
                    border-top: none;
                }
            }
        }
    }
    .marginTopZone{
        margin-top: 0;
    }
    .set-limit-box{
        min-height: 450px;
        padding-top: 5px;
        .limit-top{
            padding: 30px 34px;
            background: #FFFFFF;
            box-shadow: 0px 0 12px rgba(206, 206, 206, 0.3);
            justify-content: space-between;
            font-size: 32px;
        }
        .con{
            font-size: 28px;
            padding-left: 34px;
            .top{
                span:first-child{
                    margin-left: 196px;
                }
                span:last-child{
                    margin-left: 188px;
                }
            }
            input{
                width: 181px;
                height: 50px;
                font-size: 24px;
                background: #F6F6F6;
                border: 1px solid #E5E5E5;
                border-radius: 4px;
                box-sizing: border-box;
                padding: 0 10px;
            }
        }
    }


    .change-page-wrap{
        position: fixed;
        right: 0;
        bottom: 50px;
        width: 50PX;
        height: 115PX;
        background-image: url('../../../assets/hzyb/chart/before-next.png');
        background-size: cover;
        z-index: 10;
        .top,.bot{
            height: 50%;
        }

    }
    .custom-popup-top{
        height: 88px;
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;
        flex-wrap: nowrap;
        .popup-top-item{
            height: 100%;
            padding: 0 32px;
            display: flex;
            align-items: center;
        }
        .popup-top-cancel{
            font-weight: 400;
            font-size: 32px;
            color: #666666;
        }
        .popup-top-title{
            font-weight: 600;
            font-size: 36px;
            color: #333333;
        }
        .popup-top-confirm{
            font-weight: 400;
            font-size: 32px;
            color: #E3B377;
        }
    }
}
::v-deep(.van-tab) {
    flex: none;
    padding: 0 32px;
}
::v-deep(.van-action-sheet__item) {
    border-bottom: solid 1px #E7E7E7;
}


</style>