<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 { 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)

// 散点x轴
const scatterXAxis = {
    tickPosition: 'inside',
    lineColor: '#bfbfbf',
    tickColor: '#bfbfbf',
    tickLength:5,
    ordinal: false,
    type: 'linear',
}

// 基础y轴配置
const basicYAxis = {
    tickWidth: 1,
    tickLength: 5,
    lineWidth: 1,
    lineColor: '#bfbfbf',
    tickColor: '#bfbfbf',
    // offset: 0,
    visible: true,
    gridLineWidth: 0,
    tickPosition: 'inside',
    endOnTick: false,
    startOnTick: false,
    showLastLabel: true,
    tickPixelInterval: 50,
}

//基础x轴配置
const basicXAxis={
    tickPosition: 'inside',
    lineColor: '#bfbfbf',
    tickColor: '#bfbfbf',
    tickLength:5,
    type: 'datetime',
    ordinal: false,
    dateTimeLabelFormats: {
        day: '%y/%m',
        week: '%y/%m',
        month: '%y/%m',
        year: '%y/%m',
    },
    xDateFormat:'%Y-%m-%d'
}
//季节性图设置
const seasonOptions = {
    //默认颜色配置
    colors:['#4B0082','#7FFFAA','#FF4500','#808000','#EEE8AA','#849EC1','#8A4294','#578B5A','#FDA8C7','#53B3FF','#999999','#000000','#FFDF0C','#FF0000','#0033FF'],
    yAxis: {
        lineWidth: 1,
        lineColor: '#bfbfbf',
        tickColor: '#bfbfbf',
        offset: 0,
        opposite: false,
        reversed: false,
        visible: true,
        gridLineWidth: 0,
        tickWidth: 1,
        tickLength:5,
        tickPosition: 'inside',
        endOnTick: false,
        startOnTick: false,
        showLastLabel: true, //显示最后刻度值
        tickPixelInterval: 50
    }
}


// 获取用户信息
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')
    }
}

// let columnsStart=ref([])
// let columnsEnd=ref([])
// type 1:年-月 2:年
// const makeTimeData=(type,dateType)=>{
//     let curYear=new Date().getFullYear()
//     let yearArr=[]
//     let monthArr=[]
//     for (let i = 2010; i <= curYear; i++) {
//         yearArr.push(i.toString())
//     }
//     for (let i = 1; i < 13; i++) {
//         monthArr.push(i<10?'0'+i:i.toString())
//     }
//     const date = dateType=='start'?startDate:endDate
//     if(type==1){
//         let index1=yearArr.indexOf(date.value.split('-')[0])
//         let index2=monthArr.indexOf(date.value.split('-')[1])
//         return [
//             {values:yearArr,defaultIndex: index1>-1?index1:yearArr.length-1},
//             {values:monthArr,defaultIndex: index2>-1?index2:monthArr.length-1}
//         ]
//     }else{
//         let index1=yearArr.indexOf(date)
//         return [
//             {values:yearArr,defaultIndex: index1>-1?index1:yearArr.length-1}
//         ]
//     }
// }
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(![2,7,10,11,14].includes(res.data.ChartInfo.ChartType)){
            if(type=='init'){
                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||[])
            }
            const chartSetMap = {
                1: setSplineOpt,
                3: setStackOrCombinChart,
                4: setStackOrCombinChart,
                5: setScatterOptions,
                6: setStackOrCombinChart
            };

            chartSetMap[res.data.ChartInfo.ChartType](res.data.EdbInfoList)
        }else if(res.data.ChartInfo.ChartType ===2 ) {
            if(type=='init'){
                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||[])
            }
            setSeasonOpt(res.data.EdbInfoList[0])    
        }
        
        //奇怪柱形图依赖数据
        res.data.ChartInfo.ChartType === 7 && initBarData(res.data);

        //截面散点图
        res.data.ChartInfo.ChartType === 10 && initSectionScatterData(res.data);

        //雷达图
        res.data.ChartInfo.ChartType === 11 && initRadarData(res.data);

        // 截面组合图
        res.data.ChartInfo.ChartType === 14 && initSectionalCombinationChart(res.data);

        // 区间分析
        res.data.ChartInfo.Source===12 &&initIntervalAnalysisChartData(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

        if([2,5].includes(res.data.ChartInfo.Source)) {//商品价格曲线 利润曲线
            initCommodityData(res.data);
        }else if([3].includes(res.data.ChartInfo.Source)) { //相关性
            relevanceChartData.value=res.data
            initRelevanceChart(res.data);
        }else if([4,6,7,8].includes(res.data.ChartInfo.Source)) { //滚动相关性 拟合方程曲线 标准差 百分比
            setSplineOpt([res.data.DataResp])
        }else if(res.data.ChartInfo.Source===9) { //统计频率
            statisticFrequencyData.value = res.data.DataResp;
            setStatisticFrequency();
        }else if(res.data.ChartInfo.Source===10) { //跨品种分析
            initCrossVarietyChartData(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')

// 截面组合图初始化
function initSectionalCombinationChart(data){
    const {XDataList,UnitList,SeriesList,IsHeap}=data.DataResp
    /* 主题样式*/
    const chartTheme =  resData.value.ChartInfo.ChartThemeStyle ? JSON.parse(resData.value.ChartInfo.ChartThemeStyle) : null;
      
    let leftIndex = SeriesList.findIndex((item) => item.IsAxis===1);
    let rightIndex = SeriesList.findIndex((item) => !item.IsAxis);
    let rightTwoIndex = SeriesList.findIndex((item) => item.IsAxis ===2);
    axisLimitData.leftMin=data.ChartInfo.LeftMin
    axisLimitData.leftMax=data.ChartInfo.LeftMax
    axisLimitData.rightTwoMin=data.ChartInfo.Right2Min
    axisLimitData.rightTwoMax=data.ChartInfo.Right2Max
    axisLimitData.rightMin=data.ChartInfo.RightMin
    axisLimitData.rightMax=data.ChartInfo.RightMax
    if(leftIndex!=-1) {
        hasLeftAxis.value=true
    }
    if(rightIndex!=-1){
        hasRightAxis.value=true
    }
    if(rightTwoIndex!=-1){
        hasRightTwoAxis.value=true
    }

    //x轴
    const xAxis={
        categories:XDataList.map(_=>_.Name),
        tickWidth: 1,
        labels: {
          style:{
            ...chartTheme&&chartTheme.xAxisOptions.style
          },
        },
        plotBands: setAxisPlotAreas(3),
        plotLines: setAxisPlotLines(3)
    }

    let yAxis=[]
    let seriesData=[]

    //有右二轴时排个序 按照左 右 右2的顺序
    const chartDataList = SeriesList.some(_ =>_.IsAxis===2) ? changeEdbOrder(SeriesList) : _.cloneDeep(SeriesList);
    chartDataList.forEach((item,index)=>{
        //轴位置值相同的下标
        const sameSideIndex = chartDataList.findIndex(
          (i) => i.IsAxis === item.IsAxis
        );

        const yTitleMap={
          1:['LeftName','LeftNameEn'],
          0:['RightName','RightNameEn'],
          2:['RightTwoName','RightTwoNameEn'],
        }

        let minLimit = 0,maxLimit = 0
        const limitMap = {
            0:['rightMin','rightMax'],
            1:['leftMin','leftMax'],
            2:['rightTwoMin','rightTwoMax']
        }
        if(limitMap[item.IsAxis]){
            minLimit = axisLimitData[`${limitMap[item.IsAxis][0]}`]||0
            maxLimit = axisLimitData[`${limitMap[item.IsAxis][1]}`]||0
        }

        let yItem = {
          ...basicYAxis,
          title: {
            text: UnitList[yTitleMap[item.IsAxis][0]],
            style:{
              ...chartTheme&&chartTheme.yAxisOptions.style
            },
            align: 'high',
            rotation: 0,
            y: -12,
            // x: (item.IsAxis===0 && this.rightTwoIndex>-1) ? -chartData[this.rightTwoIndex].Unit.length*12 : 0,
            textAlign: item.IsAxis===1 ? 'left' : 'right',
            reserveSpace: false
          },
          labels: {
            formatter: function (ctx) {
              return ctx.value;
            },
            align: 'center',
            x: [0,2].includes(item.IsAxis) ? 5 : -5,
            style: {
              ...chartTheme&&chartTheme.yAxisOptions.style,
            }
          },
          opposite: [0,2].includes(item.IsAxis),
          min: Number(minLimit),
          max: Number(maxLimit),
          tickWidth: 1,
          visible: sameSideIndex === index,
          plotBands: setAxisPlotAreas(item.IsAxis),
          plotLines: setAxisPlotLines(item.IsAxis)
        };

        //堆叠图的yAxis必须一致 数据列所对应的y轴
        let serie_yIndex = index;
        if(IsHeap==1) {
          // 类型为堆叠图时公用第一个指标y轴 
          serie_yIndex =  0;
        }

        //数据列
        let dataArr=item.DataList||[]
        // 根据NoDataEdbIndex 将对应位置的值置为null
        dataArr.forEach((i,index)=>{
          if(item.NoDataEdbIndex.includes(index)){
            dataArr[index]=null
          }
        })
        //图表可配置的线条数就10条,第11条用第1条的配置，索引取下模
		const lineIndex = chartTheme ? index%chartTheme.lineOptionList.length : index
        let obj={
          data:dataArr,
          type: item.ChartStyle||'',
          dashStyle: (chartTheme&&chartTheme.lineOptionList[lineIndex].dashStyle)||'Solid',
          chartType:'linear',
          yAxis: serie_yIndex,
          name:item.SeriesName,
          nameCh:item.SeriesName,
          nameEn:item.SeriesNameEn,
          color: item.ChartColor,
          lineWidth: Number(item.ChartWidth)||(chartTheme&&chartTheme.lineOptionList[lineIndex].lineWidth),
          borderWidth: 1,
          borderColor: item.ChartColor,
          marker: {//展示数据点
            enabled:item.ChartStyle!='column'&&item.IsPoint?true:false,
            radius: (chartTheme&&chartTheme.lineOptionList[lineIndex].radius)||5,
          },
          dataLabels: {//展示数值
            enabled: item.IsNumber?true:false,
            align:item.ChartStyle=='column'?'center':undefined,
            y:item.ChartStyle=='column'?-20:0,
            inside: item.ChartStyle=='column'?false:undefined,
            crop: item.ChartStyle=='column'?false:true,
          },
          stacking:IsHeap==1?'normal':undefined,
          zIndex: ['line','spline'].includes(item.ChartStyle) ? 1 : 0, //防止组合图曲线被遮住
        }

        yAxis.push(yItem)
        seriesData.push(obj)
    })
    
    console.log(seriesData);

    const tooltip={
        formatter:function () { 
          let str=`<b>${this.points[0].x}</b>`
          this.points.forEach(item=>{
            const sObj=seriesData.find(_=>_.name===item.series.name)
            str=str+`<br><span style="color:${item.color}">\u25CF</span>${sObj.name}:${item.y} ${sObj.unitNameCh}`
          })
          return str
        },
        formatterCh:function () { 
          let str=`<b>${this.points[0].x}</b>`
          this.points.forEach(item=>{
            const sObj=seriesData.find(_=>_.name===item.series.name)
            str=str+`<br><span style="color:${item.color}">\u25CF</span>${sObj.nameCh}:${item.y} ${sObj.unitNameCh}`
          })
          return str
        },
        formatterEn:function () { 
          let str=`<b>${this.points[0].x}</b>`
          this.points.forEach(item=>{
            const sObj=seriesData.find(_=>_.name===item.series.name)
            str=str+`<br><span style="color:${item.color}">\u25CF</span>${sObj.nameEn}:${item.y} ${sObj.unitNameEn}`
          })
          return str
        },
        shared:true
    }
    

    chartData.value = {
        title: {
            text:''
        },
        tooltip,
        series: seriesData,
        yAxis: yAxis,
        xAxis,
    };

      
}

//相关性图表设置
const relevanceChartData=ref(null)
const initRelevanceChart=(data)=>{

    /* 主题样式*/
    const chartTheme =  data.ChartInfo.ChartThemeStyle ? JSON.parse(data.ChartInfo.ChartThemeStyle) : null;

    // 处理X轴
    let xAxis={
        categories: data.ChartInfo.Source===3 ? data.XEdbIdValue : data.DataResp.XDateTimeValue,
        tickWidth: 1,
        title: {
            text:  data.ChartInfo.Source===3 ? `期数（${data.CorrelationChartInfo.LeadUnit}）` : null,
            align: 'high',
            rotation: 0,
            x: 0,
            y:10,
            offset: 20,
            style: {
                ...chartTheme&&chartTheme.xAxisOptions.style
            },
        },
        labels: {
            style: {
              ...chartTheme&&chartTheme.xAxisOptions.style
            }
        },
        tickInterval: 1,
        offset:0,
        tickmarkPlacement:'on'
    }

    // 处理Y轴
    let yAxis={
        ...basicYAxis,
        title: {
          text: '相关性系数',
          textCh: '相关性系数',
          textEn: 'Correlation coefficient',
          align: 'high',
          rotation: 0,
          y: -15,
          textAlign: 'left',
          reserveSpace: false,
          style:{
            ...chartTheme&&chartTheme.yAxisOptions.style
          },
        },
        labels: {
          formatter: function (ctx) {
            let val = ctx.value;
            return val;
          },
          align: 'center',
          style:{
            ...chartTheme&&chartTheme.yAxisOptions.style
          },
        },
        opposite: false,
        tickWidth: 1,
    }

    //处理series
    let seriesData=[]
    data.YDataList.forEach((item,index)=>{
        // 图表可配置的线条数就10条,第11条用第1条的配置，索引取下模
        const lineIndex = chartTheme ? index%chartTheme.lineOptionList.length : index
        let serie_item = {
          data: item.Value,
          type: (chartTheme&&chartTheme.lineOptionList[lineIndex].lineType) || 'spline',
          dashStyle: (chartTheme&&chartTheme.lineOptionList[lineIndex].dashStyle)||'Solid',
          yAxis: 0,
          name: item.Name||data.ChartInfo.ChartName,
          nameCh: item.Name||data.ChartInfo.ChartName,
          nameEn: item.NameEn||data.ChartInfo.ChartName,
          color: item.Color||'#00f',
          chartType: 'linear',
          lineWidth: (chartTheme&&chartTheme.lineOptionList[lineIndex].lineWidth) || 3,
          visible:true,
          marker: {
            enabled: false
          }
        };
        seriesData.push(serie_item)
    })

    const { LeadValue,LeadUnit } = data.CorrelationChartInfo;
    let tooltip = {
        formatter: function() {
          let str = `<p>相关性系数：${this.y.toFixed(4)}</p><br><p>领先${ data.ChartInfo.Source===3 ?this.x+'期' : LeadValue+LeadUnit}</p>`
          return str
        }
    }
    
    nextTick(()=>{
        // if(data.ChartInfo.Source===3) {
        //     const hEl=document.getElementById('chart-box')
        //     console.log(hEl.offsetHeight);
        //     xAxis.offset=-(hEl.offsetHeight-74)/2
        // }
        chartData.value = {
            isRelevanceChart:data.ChartInfo.Source===3,
            title: {
                text:''
            },
            series: seriesData,
            yAxis: [yAxis] ,
            xAxis:xAxis,
            tooltip
        }
    })
    
}


/* 奇怪柱形图 */
const barDateList = ref([]);//柱形图的绘图数据
const barXData = ref([]);//柱形图的x轴
const barEdbData = ref([]);//柱形图的表格数据 只用于取值
 /* 获取图表详情后赋值柱状图数据 */
const initBarData = (data) => {
    const { XEdbIdValue,YDataList,EdbInfoList,ChartInfo } = data;

    let xData = XEdbIdValue.map(_ => EdbInfoList.find(edb => edb.EdbInfoId===_).EdbAliasName)
    console.log(xData)

    barDateList.value = YDataList;
    barXData.value = xData;
    barEdbData.value = EdbInfoList;

    hasLeftAxis.value=true;
    axisLimitData.leftMin=Number(ChartInfo.LeftMin)
    axisLimitData.leftMax=Number(ChartInfo.LeftMax)

    setBarChart();
}
/* 奇怪柱状图 和其他逻辑无公用点 依赖数据为单独的数据
    x轴为指标名称的柱形图 以日期作为series
*/
const setBarChart = () => {
    let seriesData = [];
    const data = _.cloneDeep(barDateList.value);
    const { ChartInfo } = resData.value;

     /* 主题样式*/
    const chartTheme =  ChartInfo.ChartThemeStyle ? JSON.parse(ChartInfo.ChartThemeStyle) : null;

    //x轴
    let xAxis = {
        ...scatterXAxis,
        categories: barXData.value,
        tickWidth: 1,
        labels: {
            style: {
              ...chartTheme&&chartTheme.xAxisOptions.style
            }
        }
    }

    const { leftMin,leftMax } = axisLimitData;
    console.log(leftMin,leftMax)
    //y轴
    let yAxis = {
        ...basicYAxis,
        title: {
            text: ChartInfo.Unit,
            align: 'high',
            rotation: 0,
            y: -15,
            textAlign: 'left',
            reserveSpace: false,
            style:{
                ...chartTheme&&chartTheme.yAxisOptions.style
            },
        },
        labels: {
            formatter: function (ctx) {
            let val = ctx.value;
            return val;
            },
            align: 'center',
            style:{
                ...chartTheme&&chartTheme.yAxisOptions.style
            },
        },
        min: Number(leftMin),
        max: Number(leftMax),
        opposite: false,
        tickWidth: 1,
        plotBands: setAxisPlotAreas(1),
        plotLines: setAxisPlotLines(1)
    }

    //数据列
    data.forEach(item => {
        let serie_item = {
            data: item.Value,
            type: 'column',
            yAxis: 0,
            name: item.Name || item.Date,
            color: item.Color,
            chartType: 'linear',              
            visible:true,
        };
        seriesData.push(serie_item)
    })
    
    chartData.value = {
        title: {
            text:''
        },
        plotOptions: {
            column:{
            stacking: null,
            },
        },
        series: seriesData,
        yAxis: [ yAxis ],
        xAxis
    }
}


/* 商品价格图 */
const commodityChartData = ref([]);//商品价格图的绘图数据
const commodityXData = ref([]);//商品价格图的x轴
const commodityEdbList = ref([]);//商品价格图的表格数据 只用于取值
 /* 商品价格曲线获取详情赋值 */
const initCommodityData = (data) => {
    const { XDataList,YDataList,EdbInfoList,ChartInfo,DataResp } = data;

    commodityEdbList.value = EdbInfoList;
    commodityChartData.value = ChartInfo.Source===5?DataResp.YDataList:YDataList;
    commodityXData.value = ChartInfo.Source===5?DataResp.XDataList:XDataList;

    hasLeftAxis.value=true;
    axisLimitData.leftMin=Number(ChartInfo.LeftMin)
    axisLimitData.leftMax=Number(ChartInfo.LeftMax)

    setCommodityChart();
}
/* 商品价格曲线设置 绘图逻辑同奇怪柱形图*/
const setCommodityChart = () => {

    const { ChartInfo } = resData.value;
    /* 主题样式*/
    const chartTheme =  ChartInfo.ChartThemeStyle ? JSON.parse(ChartInfo.ChartThemeStyle) : null;
    
    let seriesData = [];
    const data = _.cloneDeep(commodityChartData.value);

    //x轴
    let xAxis = {
        ...scatterXAxis,
        categories: commodityXData.value.filter(_=>_.IsHide===0).map(_ => _.Name),
        tickWidth: 1,
        labels: {
            style: {
              ...chartTheme&&chartTheme.xAxisOptions.style
            }
        }
    }

    const { leftMin,leftMax } = axisLimitData;
    //y轴
    let yAxis = {
        ...basicYAxis,
        title: {
            text: commodityEdbList.value[0].Unit,
            align: 'high',
            rotation: 0,
            y: -15,
            textAlign: 'left',
            reserveSpace: false,
            style:{
              ...chartTheme&&chartTheme.yAxisOptions.style
            },
        },
        labels: {
            formatter: function (ctx) {
            let val = ctx.value;
            return val;
            },
            align: 'center',
            style:{
                ...chartTheme&&chartTheme.yAxisOptions.style
            },
        },
        min: Number(leftMin),
        max: Number(leftMax),
        opposite: false,
        tickWidth: 1,
    }

    //数据列
    data.forEach((item,index) => {
        //处理首或/尾全是无效数据的以null填充
        let filterData = filterInvalidData(item)
        // 图表可配置的线条数就10条,第11条用第1条的配置，索引取下模
        const lineIndex = chartTheme ? index%chartTheme.lineOptionList.length : index
        let serie_item = {
            data: filterData,
            type: (chartTheme&&chartTheme.lineOptionList[lineIndex].lineType) || 'spline',
            dashStyle: (chartTheme&&chartTheme.lineOptionList[lineIndex].dashStyle)||'Solid',
            yAxis: 0,
            name: item.Name,
            color: item.Color,
            chartType: 'linear',
            lineWidth: (chartTheme&&chartTheme.lineOptionList[lineIndex].lineWidth) || 3,
            visible: true,
            marker: {
                enabled: false
            }
        };
        seriesData.push(serie_item)
    })

    //tooltip
    let tooltip = {
        formatter: function() {
            const ctx = this;
            let str = '';
            ctx.points.forEach(item => {
              let obj_item = data.find(_ => _.Name === item.series.name);
              let index = commodityXData.value.findIndex(_ => _.Name === ctx.x);

                //合约显示
                let haveContract = obj_item.XEdbInfoIdList[index];
                
                if(haveContract) {
                    // 利润曲线指标名
                    const isEdb=commodityEdbList.value.some(_=>_.EdbInfoId===haveContract)
                    let edb_name = resData.value.ChartInfo.Source === 5 
                    ? (isEdb? obj_item.NameList[index] : `${resData.value.DataResp.ProfitName}(${obj_item.NameList[index]})`)
                    : commodityEdbList.value.find(_ => _.EdbInfoId === obj_item.XEdbInfoIdList[index]).EdbName;
                    str+=`<b>${ edb_name }</b>`

                    if(!obj_item.NoDataEdbList.includes(obj_item.XEdbInfoIdList[index])) {
                        str += `<br><span style="color:${item.color}">\u25CF</span>${obj_item.Date}: ${item.y}<br>`
                    }else {
                        str += `<br><span style="color:${item.color}">\u25CF</span>${obj_item.Date}: 无<br>`
                    }
                }

            })
            return str||'无合约'
        },
        shared: true
    }
    
    chartData.value = {
        title: {
            text:''
        },
        series: seriesData,
        yAxis: [ yAxis ],
        xAxis,
        tooltip
    }
};
/* 处理无效数据为null */
const filterInvalidData = (item)=> {
    let validateArr = item.XEdbInfoIdList.filter(_ =>_&&!item.NoDataEdbList.includes(_));

    let first_index = item.XEdbInfoIdList.findIndex(_ => _ === validateArr[0]);
    let last_index = item.XEdbInfoIdList.findIndex(_ => _ === validateArr[validateArr.length-1]);
    console.log('first_index',first_index)
    console.log('last_index',last_index)

    let arr = item.Value.map((item,index) => {
    if(index < first_index || index > last_index) {
        return null
    }else {
        return item
    }
    })
    // 根据设置的x轴显示隐藏去除值
    let temArr=[]
    commodityXData.value.forEach((i,index)=>{
        if(i.IsHide!==1){
            temArr.push(arr[index])
        }
    })

    return temArr;
}


/* 散点截面图 */
const sectionScatterData = ref({});
/* 截面散点图获取详情赋值 */
const initSectionScatterData = ({ DataResp }) => {
    sectionScatterData.value = DataResp;

    hasLeftAxis.value=true;
    axisLimitData.leftMin=Number(DataResp.YMinValue)
    axisLimitData.leftMax=Number(DataResp.YMaxValue)
    axisLimitData.xMin=Number(DataResp.XMinValue)
    axisLimitData.xMax=Number(DataResp.XMaxValue)
    setSectionScatterChart()
}
/* 截面散点图设置 sectionScatterData */
const setSectionScatterChart = () => {
    const { DataList,XName,XNameEn,XUnitName,XUnitNameEn,YName,YNameEn,YUnitName,YUnitNameEn } = sectionScatterData.value;
    const { leftMin,leftMax,xMin,xMax }  = axisLimitData;
    const { ChartInfo } = resData.value;
    
     /* 主题样式*/
    const chartTheme =  ChartInfo.ChartThemeStyle ? JSON.parse(ChartInfo.ChartThemeStyle) : null;

    //y轴
    let yAxis = {
        ...basicYAxis,
        title: {
            text: YName,
            align: 'middle',
            style:{
                ...chartTheme&&chartTheme.yAxisOptions.style
            },
        },
        labels: {
            style:{
              ...chartTheme&&chartTheme.yAxisOptions.style
            },
        },
        opposite: false,
        reversed: false,
        min: Number(leftMin),
        max: Number(leftMax),
        tickWidth: 1,
        plotBands: setAxisPlotAreas(1),
        plotLines: setAxisPlotLines(1)
    }

    //x轴
    let xAxis = {
        ...scatterXAxis,
        title: {
            text: XName,
            align: 'middle',
            style: {
                ...chartTheme&&chartTheme.xAxisOptions.style
            },
        },
        labels: {
            style:{
              ...chartTheme&&chartTheme.xAxisOptions.style
            },
        },
        min: Number(xMin),
        max: Number(xMax),
        plotBands: setAxisPlotAreas(3),
        plotLines: setAxisPlotLines(3)
    }

    //数据列
    let series = [];
    DataList.forEach((item,index) => {
        // 图表可配置的线条数就10条,第11条用第1条的配置，索引取下模
        const lineIndex = chartTheme ? index%chartTheme.lineOptionList.length : index
        //数据列
        let series_item = {
            data: [],
            type: 'scatter',
            name: item.Name,
            color: item.Color,
            lineWidth: 0,
            chartType: 'linear',
            zIndex:1,
            marker: {
                radius: (chartTheme&&chartTheme.lineOptionList[lineIndex].radius)||5,
            },
            visible: true
        }
        item.EdbInfoList.forEach(_ => {
            series_item.data.push({
            x: _.XValue,
            y: _.YValue,
            dataLabels: {
                enabled: _.IsShow,
                allowOverlap: true,
                align: 'left',
                format: _.Name,
                formatCh: _.Name,
                formatEn: _.NameEn
            }
            })
        })
        series.push(series_item);

    //趋势线
    if(item.ShowTrendLine)  {
        
        let trend_data = item.TrendLimitData.map((_,_index) => (
            _index === item.TrendLimitData.length-1 ? {
                x: _.X,
                y: _.Y,
                dataLabels: {
                enabled: item.ShowRSquare || item.ShowFitEquation,
                align: 'left',
                color: '#666',
                x: 20,
                y: 30,
                zIndex: 9,
                allowOverlap: true,
                formatter: function(){
                    let tag = '';
                    item.ShowRSquare && item.ShowFitEquation
                    ? tag =`<span>${item.TrendLine}</span><br><span>R²=${item.RSquare}</span>`
                    : item.ShowRSquare && !item.ShowFitEquation
                    ? tag =`<span>R²=${item.RSquare}</span>`
                    : item.ShowFitEquation && !item.ShowRSquare
                    ? tag =`<span>${item.TrendLine}</span>`
                    : ''
                    return tag
                }
                }
            } : {
                x: _.X,
                y: _.Y,
            }
        ))

        let trend_item = {
            data: trend_data,
            type: 'spline',
            linkedTo: ':previous',
            color: item.Color,
            lineWidth: 1,
            chartType: 'linear',
            enableMouseTracking: false,
            dashStyle:'Dash',
            zIndex: 2,
            visible: true,
            marker: {
                enabled: false
            }
        }
        series.push(trend_item)
    }
    })

    let tooltip = {
        formatter: function() {
            let series_obj = DataList.find(_ => _.Name === this.series.name);
            let ponit_obj = series_obj.EdbInfoList.find(_ => _.XValue ===this.x && _.YValue===this.y);

            let str=`<b>${ ponit_obj.Name }</b>`;
            str += `<br><span style="color:${this.color}">\u25CF</span>${ponit_obj.XName}: ${this.x} ${ponit_obj.XDate}<br>`;
            str += `<span style="color:${this.color}">\u25CF</span>${ponit_obj.YName}: ${this.y} (${ponit_obj.YDate})`;

            return str
        }
    }
    
    chartData.value = {
        title: {
            text:''
        },
        series,
        yAxis: [yAxis],
        xAxis,
        tooltip
    }
}

/* 统计频率图 */
const statisticFrequencyData = ref({})
const setStatisticFrequency = () => {
    const { DataList,LeftMaxValue,LeftMinValue,RightMaxValue,RightMinValue } = statisticFrequencyData.value;
    const { ChartInfo } = resData.value;

     /* 主题样式*/
    const chartTheme =  ChartInfo.ChartThemeStyle ? JSON.parse(ChartInfo.ChartThemeStyle) : null;
    
    let xAxis = {
        ...scatterXAxis,
        tickWidth: 1,
        labels: {
            style: {
                ...chartTheme&&chartTheme.xAxisOptions.style
            }
        }
    }

    //y和系列
    let yAxis = [],series = [];
    DataList.forEach((item,index) => {
    let y_item = {
        ...basicYAxis,
        title: {
            text: item.Unit,
            align: 'high',
            rotation: 0,
            y: -15,
            reserveSpace: false,
            style:{
                ...chartTheme&&chartTheme.yAxisOptions.style
            },
        },
        labels: {
            style:{
              ...chartTheme&&chartTheme.yAxisOptions.style
            },
        },
        opposite: item.IsAxis===1?false:true,
        min: index===0? Number(LeftMinValue):Number(RightMinValue),
        max: index===0? Number(LeftMaxValue):Number(RightMaxValue),
        tickWidth: 1,
    }
    // 图表可配置的线条数就10条,第11条用第1条的配置，索引取下模
    const lineIndex = chartTheme ? index%chartTheme.lineOptionList.length : index
    let series_item = {
        data: item.Value.map(_ =>[_.X,_.Y]),
        dashStyle: (chartTheme&&chartTheme.lineOptionList[lineIndex].dashStyle)||'Solid',
        type: (chartTheme&&chartTheme.lineOptionList[lineIndex].lineType) || 'spline',
        yAxis: index,
        name: item.Name,
        color: item.Color,
        lineWidth: (chartTheme&&chartTheme.lineOptionList[lineIndex].lineWidth)||3,
        chartType: 'linear',
        visible: true,
        zIndex:1
    }

    series.push(series_item);
    yAxis.push(y_item)
    })

    let tooltip = {
    formatter: function() {
        let that = this;
        let xList = DataList[0].Value.map(_ =>_.X);
        let step = xList[1]-xList[0];
        let data_interval = `[${Number(that.x).toFixed(2)},${Number(that.x+step).toFixed(2)}]`;

        let str=`<b>${ data_interval }</b>`;
        that.points.forEach(item => {
        str += `<br><span style="color:${item.color}">\u25CF</span>${item.series.name}: ${item.y}%<br>`
        })
        return str
    },
    shared: true
    }

    chartData.value = {
        title: {
            text:''
        },
        tooltip,
        series,
        yAxis,
        xAxis
    }
}

/* 跨品种分析 */
const crossVarietyChartData = ref({})
const initCrossVarietyChartData = ({DataResp,ChartInfo,EdbInfoList}) => {
    crossVarietyChartData.value = DataResp;

    hasLeftAxis.value=false;

    axisLimitData.leftMin=ChartInfo.LeftMin ? Number(ChartInfo.LeftMin) : Number(DataResp.YMinValue)
    axisLimitData.leftMax=ChartInfo.LeftMax ? Number(ChartInfo.LeftMax) : Number(DataResp.YMaxValue)
    axisLimitData.xMin=ChartInfo.XMin ? Number(ChartInfo.XMin) : Number(DataResp.XMinValue)
    axisLimitData.xMax=ChartInfo.XMax ? Number(ChartInfo.XMax) : Number(DataResp.XMaxValue)

    setCrossVarietyChart()
}
const setCrossVarietyChart = () => {
    const { EdbInfoList,ChartInfo } = resData.value;
    
    const { leftMin,leftMax,xMin,xMax }  = axisLimitData;

    const { DataList,XName,YName } = crossVarietyChartData.value;
     /* 主题样式*/
    const chartTheme =  ChartInfo.ChartThemeStyle ? JSON.parse(ChartInfo.ChartThemeStyle) : null;

    //y轴
    let yAxis = {
        ...basicYAxis,
        title: {
            text: YName,
            align: 'middle',
            style: {
                ...chartTheme&&chartTheme.xAxisOptions.style
            }
        },
        labels: {
            style: {
              ...chartTheme&&chartTheme.xAxisOptions.style
            }
        },
        opposite: false,
        reversed: false,
        min: Number(leftMin),
        max: Number(leftMax),
        tickWidth: 1,
    }

    // x轴
    let xAxis = {
        ...scatterXAxis,
        title: {
            text: XName,
            align: 'middle',
            style: {
                ...chartTheme&&chartTheme.xAxisOptions.style
            }
        },
        labels: {
            style: {
                ...chartTheme&&chartTheme.xAxisOptions.style
            }
        },
        min: Number(xMin),
        max: Number(xMax),
    }

    //数据列
    let series = [];
    const tagMap = { //标签对应文字
        1: '最新',
        3: 'Fix'
    }
    DataList.forEach(item => {
        //数据列
        let series_item = {
            data: [],
            type: 'scatter',
            name: item.Name,
            color: item.Color,
            lineWidth: 0,
            chartType: 'linear',
            zIndex:1,
            visible: true
        }
        item.CoordinatePointData.forEach(_ => {
            series_item.data.push({
                x: _.X,
                y: _.Y,
                dataLabels: {
                enabled: _.ShowTips===1,
                allowOverlap: true,
                align: 'left',
                format: tagMap[_.DateType] || `-${_.DaysAgo}D`,
                }
            })
        })
        series.push(series_item);
    })

    let tooltip = {
        formatter: function() {

            let that = this;
            let str = '';

            let series_obj = DataList.find(_ => _.Name === that.series.name);
            let ponit_obj = series_obj.CoordinatePointData.find(_ => _.X ===that.x && _.Y===that.y);
            
            let xEdbInfo = EdbInfoList.find(_ => _.EdbInfoId===ponit_obj.XEdbInfoId);
            let yEdbInfo = EdbInfoList.find(_ => _.EdbInfoId===ponit_obj.YEdbInfoId);

            str=`<b>${ that.series.name }</b>`;
            str += `<br><span style="color:${that.color}">\u25CF</span>${xEdbInfo.EdbName}: ${that.x} ${ponit_obj.XDate}<br>`;
            str += `<span style="color:${that.color}">\u25CF</span>${yEdbInfo.EdbName}: ${that.y} ${ponit_obj.YDate}`;

            return str
        }
    }

    chartData.value = {
        title: {
            text:''
        },
        series,
        yAxis: [yAxis],
        xAxis,
        tooltip
    }
}


/* 雷达图 */
const radarChartRenderData =  ref({})
const initRadarData = (data) => {
    const { DataResp,EdbInfoList,ChartInfo } = data;
    
    radarChartRenderData.value = {
        YDataList: DataResp.YDataList,
        XDataList: EdbInfoList.filter(_ => DataResp.XEdbIdValue.includes(_.EdbInfoId))
    }

    hasLeftAxis.value=true;
    axisLimitData.leftMin=Number(ChartInfo.LeftMin)
    axisLimitData.leftMax=Number(ChartInfo.LeftMax)

    setRadarChart();
}
const setRadarChart = () => {
  const { YDataList,XDataList } = radarChartRenderData.value;

  const { ChartInfo } = resData.value;

    /* 主题样式*/
    const chartTheme =  ChartInfo.ChartThemeStyle ? JSON.parse(ChartInfo.ChartThemeStyle) : null;

    let categories = XDataList.map(_ => _.EdbAliasName||_.EdbName);

    //x轴
    let xAxis = {
      lineWidth: 0,
      tickLength: 0,
      tickmarkPlacement: 'on',
      categories,
      labels: {
        allowOverlap: true,
        autoRotationLimit: 40,
        style: {
          ...chartTheme&&chartTheme.xAxisOptions.style
        }
      }
    }

    //y轴
    const { leftMin,leftMax } = axisLimitData;
    let yAxis = [{
      gridLineInterpolation: 'polygon',
      gridLineWidth: 1,
      lineWidth: 0,
      endOnTick: false,
      startOnTick: false,
      showLastLabel: true,
      // tickAmount:4,
      title: {
        text:  ChartInfo.Unit ,
        align: 'high',
        rotation: 0,
        y: 5,
        x:10,
        textAlign: 'left',
        reserveSpace: false,
        style:{
          ...chartTheme&&chartTheme.yAxisOptions.style
        },
      },
      labels: {
        allowOverlap: true,
        style:{
          ...chartTheme&&chartTheme.yAxisOptions.style
        }
      },
      min: Number(leftMin),
      max: Number(leftMax),
    }]

    //系列
    let series = [];
    YDataList.forEach((item,index) => {
        // 图表可配置的线条数就10条,第11条用第1条的配置，索引取下模
        const lineIndex = chartTheme ? index%chartTheme.lineOptionList.length : index
        let serie_item = {
            data: item.Value,
            pointPlacement: 'on',
            type: (chartTheme&&chartTheme.lineOptionList[lineIndex].lineType) || 'line',
            dashStyle: (chartTheme&&chartTheme.lineOptionList[lineIndex].dashStyle)||'Solid',
            yAxis: 0,
            name: item.Name || item.Date,
            color: item.Color,
            lineWidth: (chartTheme&&chartTheme.lineOptionList[lineIndex].lineWidth) || 1,
            chartType: 'linear',
            visible: true
        };
        series.push(serie_item)
    })

    chartData.value = {
        chart: {
            ...chartTheme.drawOption,
            spacing: [2,10,2,10],
            polar:true,
        },
        title: {
            text:''
        },
        pane: {
            size: '85%'
        },
        series,
        yAxis,
        xAxis
    }
}

//区间分析
const initIntervalAnalysisChartData=(data)=>{
    setSplineOpt(data.EdbInfoList)
}


// 路由改变 解决从搜索页返回数据不刷新问题
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
}


// 设置常规图配置 曲线
const setSplineOpt=(data)=>{
    let series=[]
    let yAxis=[]
    let xAxis = {}

    let temYLeftArr=[]
    let temYRightArr=[]
    let temYRightTwoArr = []
    let temYLeftIndex=data.findIndex((item) => item.IsAxis===1)
    let temYRightIndex=data.findIndex((item) => !item.IsAxis)
    let temYRightTwoIndex = data.findIndex((item) => item.IsAxis===2)

     /* 主题样式*/
    const chartTheme =  resData.value.ChartInfo.ChartThemeStyle ? JSON.parse(resData.value.ChartInfo.ChartThemeStyle) : null;

    let minAndMaxTimeTemArr=[]//存放所有指标的最大最小时间

    //有右二轴时排个序 按照左 右 右2的顺序
    let newData = data.some(_ =>_.IsAxis===2) ? changeEdbOrder(data) : data;
    

    newData.forEach((item,index)=>{

         //轴位置值相同的下标
        let sameSideIndex = newData.findIndex(i => i.IsAxis === item.IsAxis);

        let dynamic_title = item.EdbName;
        let dynamic_arr = newData.filter(
          (item) => dynamic_title === item.EdbName
        );
        //处理数据列name
        let temName= setDyncmicSerieName(item,dynamic_arr)  

        //预测指标配置
        let predict_params = item.EdbInfoCategoryType === 1 ? getPredictParams(item) : {};
        // 图表可配置的线条数就10条,第11条用第1条的配置，索引取下模
        const lineIndex = chartTheme ? index%chartTheme.lineOptionList.length : index
        let seriesItemObj={
            data:[],
            dataGrouping:{
                enabled:false
            },
            type: (chartTheme&&chartTheme.lineOptionList[lineIndex].lineType) || 'spline',
            dashStyle: (chartTheme&&chartTheme.lineOptionList[lineIndex].dashStyle)||'Solid',
            yAxis:index,
            name:temName,
            color: item.ChartColor,
            lineWidth: Number(item.ChartWidth)|| (chartTheme&&chartTheme.lineOptionList[lineIndex].lineWidth)||1,
            visible:true,
            LatestDate:item.LatestDate,
            LatestValue:item.LatestValue,
            marker: chartTheme && chartTheme.lineOptionList[lineIndex].dataMark && chartTheme.lineOptionList[lineIndex].dataMark!='none'?{
                enabled:true,
                symbol: chartTheme.lineOptionList[lineIndex].markType || 'circle',
                fillColor:chartTheme.lineOptionList[lineIndex].markColor,
                radius: chartTheme.lineOptionList[lineIndex].markSize
            }:{},
            ...predict_params
        }
        item.DataList = item.DataList || [];
        for (let i of item.DataList) {
          seriesItemObj.data.push([i.DataTimestamp, i.Value]);
        }
        series.push(seriesItemObj)
        

        // 设置y轴
        if(item.IsAxis){
            temYLeftArr.push(item)
        }else{
            temYRightArr.push(item)
        }

        let yItem={
            ...basicYAxis,
            IsAxis:item.IsAxis,
            labels: {
                formatter: function (ctx) {
                    return sameSideIndex !== index ? '' : ctx.value;
                },
                align: 'center',
                x: [0,2].includes(item.IsAxis) ? 5 : -5,
                style:{
                    ...chartTheme&&chartTheme.yAxisOptions.style
                },
            },
            tickWidth: sameSideIndex !== index ? 0 : 1,
            title: {
                text:  sameSideIndex !== index ? '' : `${resData.value.ChartInfo.Source==12?item.ConvertUnit : item.Unit||''}`,
                align: 'high',
                rotation: 0,
                y: -15,
                x: (item.IsAxis===0 && temYRightTwoIndex>-1) ? -newData[temYRightTwoIndex].Unit.length*12 : 0,
                textAlign: item.IsAxis===1 ? 'left' : 'right',
                reserveSpace: false,
                style:{
                    ...chartTheme&&chartTheme.yAxisOptions.style
                },
            },
            opposite: [0,2].includes(item.IsAxis),
            reversed: item.IsOrder,
            min: item.MinData,
            max: item.MaxData,
            visible: sameSideIndex === index,
            plotBands: setAxisPlotAreas(item.IsAxis),
            plotLines: setAxisPlotLines(item.IsAxis),
            chartEdbInfo:item//指标数据用于在保存时读取指标数据
        }
        yAxis.push(yItem)
        
        if(item.DataList.length>0){
            minAndMaxTimeTemArr.push(item.DataList[0].DataTimestamp)
            minAndMaxTimeTemArr.push(item.DataList[item.DataList.length-1].DataTimestamp)
        }
        
    })

    // 设置值
    chartData.value.series=series
    
    
    // 设置x轴
    // 找出所有指标的最大和最小时间 分成6段
    let minTime=Math.min.apply(null,minAndMaxTimeTemArr)
    let maxTime=Math.max.apply(null,minAndMaxTimeTemArr)


    const isLessThanOneYear = xTimeDiffer(minTime,maxTime)
    xAxis={
        ...basicXAxis,
        tickInterval:((maxTime-minTime)/6)/(24*3600*1000)>30?(maxTime-minTime)/6:24*3600*1000*30,
        labels: {
            formatter:  (ctx)=> {
                return isLessThanOneYear
                ? Highcharts.dateFormat('%m/%d', ctx.value)
                : Highcharts.dateFormat('%y/%m', ctx.value);
            },
            style: {
                ...chartTheme&&chartTheme.xAxisOptions.style
            }
        },
        plotBands: setAxisPlotAreas(3,'datetime'),
        plotLines: setAxisPlotLines(3,'datetime')
    }
    
    chartData.value.xAxis=[xAxis]
    

    yAxis.forEach(item=>{
        if(item.IsAxis===1){//左轴
            hasLeftAxis.value=true

            // item.min=getAxisMaxOrMin(temYLeftArr,'min')
            // item.max=getAxisMaxOrMin(temYLeftArr,'max')
            // axisLimitData.leftMin=getAxisMaxOrMin(temYLeftArr,'min')
            // axisLimitData.leftMax=getAxisMaxOrMin(temYLeftArr,'max')
            item.min=data[temYLeftIndex].MinData
            item.max=data[temYLeftIndex].MaxData
            axisLimitData.leftMin=data[temYLeftIndex].MinData
            axisLimitData.leftMax=data[temYLeftIndex].MaxData
        }else if (item.IsAxis===2){ // 右2轴
            hasRightTwoAxis.value=true
            item.min=data[temYRightTwoIndex].MinData
            item.max=data[temYRightTwoIndex].MaxData
            axisLimitData.rightTwoMin=data[temYRightTwoIndex].MinData
            axisLimitData.rightTwoMax=data[temYRightTwoIndex].MaxData
        }else{
            hasRightAxis.value=true

            // item.min=getAxisMaxOrMin(temYRightArr,'min')
            // item.max=getAxisMaxOrMin(temYRightArr,'max')
            // axisLimitData.rightMin=getAxisMaxOrMin(temYRightArr,'min')
            // axisLimitData.rightMax=getAxisMaxOrMin(temYRightArr,'max')
            item.min=data[temYRightIndex].MinData
            item.max=data[temYRightIndex].MaxData
            axisLimitData.rightMin=data[temYRightIndex].MinData
            axisLimitData.rightMax=data[temYRightIndex].MaxData
        }
    })
    chartData.value.yAxis=yAxis
    chartData.value.rangeSelector={ enabled: false}

     //滚动相关性独立tooltip
    if(resData.value.ChartInfo.Source === 4) {
        const { LeadValue,LeadUnit } = resData.value.CorrelationChartInfo;
        chartData.value.tooltip = {
          formatter: function() {
            let str = `${Highcharts.dateFormat('%Y/%m/%d',this.x)}<br><p>相关性系数：${this.y.toFixed(4)}</p><br><p>领先${LeadValue+LeadUnit}</p>`
           
            return str
          }
        }
    }

}

/* 堆叠图/组合图设置  
    本来和曲线图逻辑基本一致兼容下即可 为了以后便于维护和阅读还是拆开写吧
*/
const setStackOrCombinChart = data => {
    //图表类型
    const chartTypeMap = {
        3: 'areaspline',
        4: 'column',
        6: ''
    };
    let chartStyle = chartTypeMap[resData.value.ChartInfo.ChartType];

    /* 主题样式*/
    const chartTheme =  resData.value.ChartInfo.ChartThemeStyle ? JSON.parse(resData.value.ChartInfo.ChartThemeStyle) : null;

    let series=[]
    let yAxis=[]
    let xAxis = {}

    let temYLeftArr=[]
    let temYRightArr=[]
    let temYRightTwoArr = []
    let temYLeftIndex,temYRightIndex,temYRightTwoIndex;

    let minAndMaxTimeTemArr=[]//存放所有指标的最大最小时间

    //有右二轴时排个序 按照左 右 右2的顺序
    let newData = data.some(_ =>_.IsAxis===2) ? changeEdbOrder(data) : data;

    newData.forEach((item,index)=>{

        //轴位置值相同的下标
        let sameSideIndex = newData.findIndex(i => i.IsAxis === item.IsAxis);

        //堆叠图的yAxis必须一致 数据列所对应的y轴
        let serie_yIndex = index;
        if([3,4].includes(resData.value.ChartInfo.ChartType)) {
            // 类型为堆叠图时公用第一个指标y轴 
            serie_yIndex =  0;
        } else if(resData.value.ChartInfo.ChartType ===6 && ['areaspline','column'].includes(item.ChartStyle)) {
            // 组合图找第一个堆叠柱状或面积的作为公用
            serie_yIndex = newData.findIndex(i => i.ChartStyle === item.ChartStyle);
        }
        //数据对应的y轴是公用轴则配置也共享
        item.IsAxis = serie_yIndex === index ? item.IsAxis : newData[serie_yIndex].IsAxis;
        item.IsOrder = serie_yIndex === index ? item.IsOrder : newData[serie_yIndex].IsOrder;

        temYLeftIndex = [3,4].includes(resData.value.ChartInfo.ChartType) 
            ? (newData[serie_yIndex].IsAxis ? serie_yIndex : -1)
            : data.findIndex((item) => item.IsAxis===1);
        temYRightIndex = [3,4].includes(resData.value.ChartInfo.ChartType) 
            ? (newData[serie_yIndex].IsAxis ? -1 : serie_yIndex)
            : data.findIndex((item) => !item.IsAxis);
        temYRightTwoIndex = [3,4].includes(resData.value.ChartInfo.ChartType) 
            ? -1
            : data.findIndex((item) => item.IsAxis===2);

        let dynamic_title = item.EdbName;
        let dynamic_arr = newData.filter(
          (item) => dynamic_title === item.EdbName
        );
        //处理数据列name
        let temName= setDyncmicSerieName(item,dynamic_arr)  

        //预测指标配置
        let predict_params = item.EdbInfoCategoryType === 1 ? getPredictParams(item,chartStyle) : {};

        let seriesItemObj={
            data:[],
            dataGrouping:{
                enabled:false
            },
            type: chartStyle || item.ChartStyle,
            yAxis:serie_yIndex,
            name:temName,
            color: item.ChartColor,
            lineWidth: Number(item.ChartWidth),
            fillColor: (resData.value.ChartInfo.ChartType === 3 || (resData.value.ChartInfo.ChartType === 6 && item.ChartStyle === 'areaspline')) ? item.ChartColor : undefined,
            visible:true,
            LatestDate:item.LatestDate,
            LatestValue:item.LatestValue,
            borderWidth: 1,
            borderColor: item.ChartColor,
            ...predict_params,
            stacking:resData.value.ChartInfo.ChartType==6&&!resData.value.DataResp.IsHeap?undefined:'normal',
        }
        item.DataList = item.DataList || [];
        for (let i of item.DataList) {
          seriesItemObj.data.push([i.DataTimestamp, i.Value]);
        }
        series.push(seriesItemObj)
        

        // 设置y轴
        if(item.IsAxis){
            temYLeftArr.push(item)
        }else{
            temYRightArr.push(item)
        }

        let yItem={
            ...basicYAxis,
            IsAxis:item.IsAxis,
            labels: {
                formatter: function (ctx) {
                    return sameSideIndex !== index ? '' : ctx.value;
                },
                align: 'center',
                x: [0,2].includes(item.IsAxis) ? 5 : -5,
                style:{
                    ...chartTheme&&chartTheme.yAxisOptions.style
                },
            },
            title: {
                text:  sameSideIndex !== index ? '' : `${item.Unit}`,
                align: 'high',
                rotation: 0,
                y: -15,
                x: (item.IsAxis===0 && temYRightTwoIndex>-1) ? -newData[temYRightTwoIndex].Unit.length*12 : 0,
                textAlign: item.IsAxis===1 ? 'left' : 'right',
                reserveSpace: false,
                style:{
                    ...chartTheme&&chartTheme.yAxisOptions.style
                },
            },
            opposite: [0,2].includes(item.IsAxis),
            reversed: item.IsOrder,
            min: item.MinData,
            max: item.MaxData,
            tickWidth: sameSideIndex !== index ? 0 : 1,
            visible: serie_yIndex === index && sameSideIndex ===index,
            chartEdbInfo:item,//指标数据用于在保存时读取指标数据
            plotBands: setAxisPlotAreas(item.IsAxis),
            plotLines: setAxisPlotLines(item.IsAxis)
        }
        yAxis.push(yItem)
        
        if(item.DataList.length>0){
            minAndMaxTimeTemArr.push(item.DataList[0].DataTimestamp)
            minAndMaxTimeTemArr.push(item.DataList[item.DataList.length-1].DataTimestamp)
        }
        
    })

    // 设置值
    chartData.value.series=series
    
    
    // 设置x轴
    // 找出所有指标的最大和最小时间 分成6段
    let minTime=Math.min.apply(null,minAndMaxTimeTemArr)
    let maxTime=Math.max.apply(null,minAndMaxTimeTemArr)


    const isLessThanOneYear = xTimeDiffer(minTime,maxTime)
    xAxis={
        ...basicXAxis,
        tickInterval:((maxTime-minTime)/6)/(24*3600*1000)>30?(maxTime-minTime)/6:24*3600*1000*30,
        labels: {
            formatter: (ctx)=> {
                return isLessThanOneYear
                ? Highcharts.dateFormat('%m/%d', ctx.value)
                : Highcharts.dateFormat('%y/%m', ctx.value);
            },
            style: {
                ...chartTheme&&chartTheme.xAxisOptions.style
            }
        },
        plotBands: setAxisPlotAreas(3,'datetime'),
        plotLines: setAxisPlotLines(3,'datetime')
    }
    
    chartData.value.xAxis=[xAxis]
    

    yAxis.forEach(item=>{
        if(item.IsAxis === 1){//左轴
            hasLeftAxis.value=true
            item.min=data[temYLeftIndex].MinData
            item.max=data[temYLeftIndex].MaxData
            axisLimitData.leftMin=data[temYLeftIndex].MinData
            axisLimitData.leftMax=data[temYLeftIndex].MaxData
        }else if (item.IsAxis===2){ // 右2轴
            hasRightTwoAxis.value=true
            item.min=data[temYRightTwoIndex].MinData
            item.max=data[temYRightTwoIndex].MaxData
            axisLimitData.rightTwoMin=data[temYRightTwoIndex].MinData
            axisLimitData.rightTwoMax=data[temYRightTwoIndex].MaxData
        }else{
            hasRightAxis.value=true
            item.min=data[temYRightIndex].MinData
            item.max=data[temYRightIndex].MaxData
            axisLimitData.rightMin=data[temYRightIndex].MinData
            axisLimitData.rightMax=data[temYRightIndex].MaxData
        }
    })
    chartData.value.yAxis=yAxis
    chartData.value.rangeSelector={ enabled: false}
}

/* 拼接数据列动态name */
const setDyncmicSerieName = (item,dynamic_arr) => {
    const { IsAxis,IsOrder,EdbInfoType,LeadValue,LeadUnit }  = item;
    // IsAxis左轴1 右轴0 2右2轴 
      //IsOrder正序false 逆序true 
      //EdbInfoType是否是领先指标
    const axisLabelMap = {
        0: '右轴',
        2: '右2轴'
    }
    const orderLabelMap = {
        1: '逆序'
    }
    const edbInfoMap = {
        0: '领先'
    }

    let axis_tag = axisLabelMap[IsAxis] || '';
      //逆序拼接
    let order_tag = orderLabelMap[Number(IsOrder)] ? `${axis_tag ? '，': ''}${orderLabelMap[Number(IsOrder)]}` : ''
      //领先拼接
    let edb_tag = edbInfoMap[EdbInfoType] ? `${(axis_tag||order_tag) ? '，' : '' }${edbInfoMap[EdbInfoType]}${LeadValue}${LeadUnit}` : '';

    let dynamic_tag = (axis_tag || order_tag || edb_tag) ? `(${axis_tag}${order_tag}${edb_tag})` : '';

    let temName = dynamic_arr.length > 1
                ? `${item.EdbName}(${item.SourceName})${dynamic_tag}`
                : `${item.EdbName}${dynamic_tag}`
    if(temName.length>20){
        let temArr=[]
        for(let i=0;i<temName.length/20;i++){
            temArr.push(temName.slice(i*20,i*20+20))
        }
        // console.log(temArr);
        temName=temArr.join('<br>')
    }

    return temName
}

/* 指标顺序调整  IsAxis: 0右轴 1左轴 2右2*/
const changeEdbOrder = (data) => {
    // 左轴指标
    let left_edbs = data.filter(_ => _.IsAxis===1);
    //右轴指标
    let right_edbs = data.filter(_ => !_.IsAxis);
    // 右2轴指标
    let right_two_edbs = data.filter(_ => _.IsAxis === 2);
    // 按 左 右 右2顺序排列
    return [left_edbs,right_edbs,right_two_edbs].flat(Infinity);
}

//获取RGBA的透明度
function parseRgbaColor(color='rgba(51, 51, 51, 1)'){
    const arr = color.match(/(\d(\.\d+)?)+/g) || ['','','',1];
    return parseFloat(arr[3]||1)
}
//设置季节图配置
const setSeasonOpt=(data)=>{
    hasLeftAxis.value=true

    /* 主题样式*/
    const chartTheme =  resData.value.ChartInfo.ChartThemeStyle ? JSON.parse(resData.value.ChartInfo.ChartThemeStyle) : null;

    const colorsArr=chartTheme&&chartTheme.colorsOptions.reverse();

    let series=[],yAxis=[]
    //农历默认选中一年数据并隐藏按钮  公历显示全部数据
    // let rangeSelector={}

    // 公历
    // if(calendarType.value==='公历'){
    // ETA1.0.5 农历数据需要去除第一项 除此之外 农历和公历处理逻辑一样
    const chartDataHandle = calendarType.value === '农历'?
                            data.DataList.slice(1,data.DataList.length)||[]:
                            data.DataList

    // 跟颜色对应
    chartTheme && (chartTheme.lineOptionList=chartTheme.lineOptionList.reverse().slice(-chartDataHandle.length))
    //常规左轴
    chartDataHandle.forEach((item,index)=>{
            //预测指标配置
        let predict_params =  data.EdbInfoCategoryType === 1 ? getSeasonPredictParams(item.CuttingDataTimestamp) : {};
        // 图表可配置的线条数就10条,第11条用第1条的配置，索引取下模
        const lineIndex = chartTheme ? index%chartTheme.lineOptionList.length : index
        let seriesItem={
            data:[],
            dataGrouping:{
                enabled:false
            },
            type: (chartTheme&&chartTheme.lineOptionList[lineIndex].lineType) || data.ChartStyle,
            dashStyle: (chartTheme&&chartTheme.lineOptionList[lineIndex].dashStyle)||'Solid',
            yAxis:0,
            name:item.ChartLegend,
            lineWidth: (chartTheme&&chartTheme.lineOptionList[lineIndex].lineWidth) || 1,
            color:colorsArr.slice(-chartDataHandle.length)[lineIndex],       
            visible:true,
            marker: chartTheme && chartTheme.lineOptionList[lineIndex].dataMark && chartTheme.lineOptionList[lineIndex].dataMark!='none'?{
                enabled:true,
                symbol: chartTheme.lineOptionList[lineIndex].markType || 'circle',
                fillColor:chartTheme.lineOptionList[lineIndex].markColor,
                radius: chartTheme.lineOptionList[lineIndex].markSize
            }:{},
            ...predict_params
        }
        item.DataList=item.DataList||[]
        for(let i of item.DataList){
            seriesItem.data.push([i.DataTimestamp, i.Value])
        }
        series.push(seriesItem)

    })
    //同期上下限/均线/标准差
    const {MaxMinLimits={},SamePeriodAverage={},SamePeriodStandardDeviation={}} = resData.value.DataResp||{}
    if(MaxMinLimits.IsShow&&MaxMinLimits.List&&MaxMinLimits.List.length){
        let serieItem = {
            type:'arearange',//上下限是一个范围
            data:[],
            name:MaxMinLimits.Legend||'同期上下限',
            color:MaxMinLimits.Color||'#075EEE' ,
            fillOpacity:parseRgbaColor(MaxMinLimits.Color||'')>0.75?0.75:parseRgbaColor(MaxMinLimits.Color||''), //透明度最高0.75 
            visible:true,
        }
        MaxMinLimits.List.forEach(item=>{
            serieItem.data.push([item.DataTimestamp,item.MinValue,item.MaxValue])
        })
        series.push(serieItem)
    }
    if(SamePeriodAverage.IsShow&&SamePeriodAverage.List){
        let serieItem = {
            type:'line',
            data:[],
            lineWidth:SamePeriodAverage.LineWidth,
            dashStyle:SamePeriodAverage.LineType,
            name:SamePeriodAverage.Legend||'同期均值',
            color:SamePeriodAverage.Color||'#075EEE',
            visible:true,
        }
        SamePeriodAverage.List.forEach(item=>{
            serieItem.data.push([item.DataTimestamp,item.Value])
        })
        series.push(serieItem)
    }
    if(SamePeriodStandardDeviation.IsShow&&SamePeriodStandardDeviation.List){
        let serieItem = {
            type:'arearange',//标准差也是一个范围
            data:[],
            name:SamePeriodStandardDeviation.Legend||'同期标准差',
            color:SamePeriodStandardDeviation.Color||'#075EEE',
            fillOpacity:parseRgbaColor(SamePeriodStandardDeviation.Color||'')>0.75?0.75:parseRgbaColor(SamePeriodStandardDeviation.Color||''),
            visible:true,
        }
        SamePeriodStandardDeviation.List.forEach(item=>{
            serieItem.data.push([item.DataTimestamp,item.MinValue,item.MaxValue])
        })
        series.push(serieItem)
    }
    //右轴
    const {RightAxis:SeasonRightConfig={}} = resData.value.DataResp||{}
    if(SeasonRightConfig.IsShow){
        //右轴的设置
        let serieConfig = SeasonRightConfig.Style==='column'?{
            //柱形
            type:'column',
            color:SeasonRightConfig.ChartColor,
            visible:true,
        }:{
            //标记点
            type:'spline',
            lineWidth:SeasonRightConfig.LineWidth,
            dashStyle:SeasonRightConfig.LineStyle,
            color:SeasonRightConfig.IsConnected?SeasonRightConfig.LineColor:'rgba(255, 255, 255, 0)',//没有连线颜色设置为透明
            marker:{
                enabled:true,
                symbol:SeasonRightConfig.Shape,
                fillColor:SeasonRightConfig.ChartColor,
                radius:SeasonRightConfig.Size
            },
            visible:true,
        }
        let serieItem = {
            ...serieConfig,
            name:SeasonRightConfig.Legend||'',
            data:[],
            yAxis:1,
        }
        const DataList = (SeasonRightConfig.IndicatorType===1?SeasonRightConfig.EdbInfoList[0].DataList:e.EdbInfoList[1]?.DataList)||[]
        DataList.forEach(item=>{
            serieItem.data.push([item.DataTimestamp,item.Value])
        })
        series.push(serieItem)
    }

    yAxis=[{
        IsAxis:data.IsAxis,
        labels: {
            // formatter: function (ctx) {
            //     return ctx.value;
            // },
            align: 'center',
            y:5,
            style: {
                ...chartTheme&&chartTheme.yAxisOptions.style
            }
        },
        title: {
            text:  `${data.Unit}`,
            align: 'high',
            rotation: 0,
            y: -15,
            x: 0,
            textAlign: 'left',
            reserveSpace: false,
            style:{
                ...chartTheme&&chartTheme.yAxisOptions.style
            },
        },
        max: Number(data.MaxData),
        min: Number(data.MinData),
        plotBands: setAxisPlotAreas(1),
        plotLines: setAxisPlotLines(1),
        lineWidth: 1,
        lineColor: '#bfbfbf',
        tickColor: '#bfbfbf',
        offset: 0,
        opposite: false,
        reversed: false,
        visible: true,
        gridLineWidth: 0,
        tickWidth: 1,
        tickLength:5,
        tickPosition: 'inside',
        endOnTick: false,
        startOnTick: false,
        showLastLabel: true, //显示最后刻度值
        tickPixelInterval: 50,
        // chartEdbInfo:item//指标数据
    }]

    //如果有右轴,yAxis加上右轴
    if(SeasonRightConfig.IsShow){
        const rightEdb = (SeasonRightConfig.IndicatorType===1?SeasonRightConfig.EdbInfoList[0]:e.EdbInfoList[1])||{Unit:''}
        //左轴同比：text为空或% 右轴指标：取指标单位
        if(SeasonRightConfig.IndicatorType===1){
            rightEdb.Unit = SeasonRightConfig.NumFormat===1?'%':''
        }else{
            rightEdb.Unit = e.EdbInfoList[1]&&(e.EdbInfoList[1].ConvertUnit||e.EdbInfoList[1].Unit)||''
        }
        yAxis.push({
            ...seasonOptions.yAxis,
            opposite: true,//右轴
            labels: {
                align: 'center',
                y:5,
                style: {
                  ...chartTheme&&chartTheme.yAxisOptions.style
                }
              },
              title: {
                text: rightEdb.Unit||'',
                style:{
                  ...chartTheme&&chartTheme.yAxisOptions.style
                },
                align: 'high',
                rotation: 0,
                y: -5,
                x: 0,
                textAlign: 'right',
                reserveSpace: false,
              },
              max: Number(rightEdb.MaxData||''),
              min: Number(rightEdb.MinData||''),
        })
    }

    chartData.value.series=series
    chartData.value.yAxis=yAxis
    // chartData.value.rangeSelector=rangeSelector
    // 设置坐标轴极值
    hasLeftAxis.value=true
    axisLimitData.leftMin=Number(data.MinData)
    axisLimitData.leftMax=Number(data.MaxData)

    // 季节图x轴显示月/日
    let xAxis={
        tickPosition: 'inside',
		lineColor: '#bfbfbf',
    	tickColor: '#bfbfbf',
		tickLength:5,
		type: 'datetime',
		ordinal: false,
		dateTimeLabelFormats: {
			day: '%y/%m',
			week: '%y/%m',
			month: '%y/%m',
			year: '%y/%m',
		},
        labels: {
            formatter: (ctx)=> {
                return Highcharts.dateFormat('%m/%d', ctx.value)
            },
            style: {
                ...chartTheme&&chartTheme.xAxisOptions.style
            }
        },
        plotBands: setAxisPlotAreas(3,'datetime'),
        plotLines: setAxisPlotLines(3,'datetime')
    }

    xAxis={
        ...xAxis,
        tickInterval:24*3600*1000*60,//季节图
    }
    

    chartData.value.xAxis=[xAxis]

    // 季节图提示框显示 月/日
    chartData.value.tooltip={
        split: false,
        shared: true,
        dateTimeLabelFormats: {
          // 时间格式化字符
          day: '%m/%d',
          week: '%m/%d',
          month: '%m/%d',
          year: '%m/%d',
        },
        xDateFormat: '%m/%d',
    }

}

/* 预测配置 分区 */
const getPredictParams = ({LatestDate,MoveLatestDate,PredictChartColor,ChartStyle},chartStyle) => {
    return {
    zoneAxis: 'x',
    zones: [{
        value: new Date(MoveLatestDate||LatestDate).getTime()+1
    }, {
        dashStyle: 'ShortDot',
        color: (ChartStyle==='column' || chartStyle==='column') ? 'transparent' : PredictChartColor
    }]
    }
}

/* 季节图预测数据 年份=分割点年份做分割 年份>分割点年份全为预测 */
const getSeasonPredictParams = (timestamp) => {
    return timestamp
    ? {
        zoneAxis: 'x',
        zones: [{
            value: new Date(timestamp).getTime()+1
        }, {
            dashStyle: 'ShortDot',
        }]
        }
    : {}
}

/* 散点图 第一个指标值为x轴 第二个指标为y轴*/
const setScatterOptions = (dataList) => {
    const { ChartInfo } = resData.value;

     /* 主题样式*/
    const chartTheme = ChartInfo.ChartThemeStyle ? JSON.parse(ChartInfo.ChartThemeStyle) : null;

    // 取2个指标中日期相同的数据
    const real_data = [];
    let tmpData_date = {};//用来取点对应的日期
    let data1 =  _.cloneDeep(dataList)[0].DataList || [];
    let data2 =  _.cloneDeep(dataList)[1].DataList || [];
    data1.forEach((_item) => {
        data2.forEach((_item2) => {
            if(_item.DataTimestamp === _item2.DataTimestamp) {
                //日期
                let itemIndex =_item.Value + "_" +_item2.Value
                if(tmpData_date[itemIndex]) {
                    tmpData_date[itemIndex].push( moment(_item.DataTimestamp).format('YYYY/MM/DD'))
                } else {
                    tmpData_date[itemIndex] = [moment(_item.DataTimestamp).format('YYYY/MM/DD')]
                }
            
                //值
                real_data.push({
                    x: _item.Value,
                    y: _item2.Value
                })
            }
        })
    })
    real_data.sort((x,y) => x-y);

    //悬浮窗 拼接日期 原始指标名称
    let tooltip = {
        formatter: function() {
            return `<strong>${ tmpData_date[this.x+'_'+this.y].length > 4 ? tmpData_date[this.x+'_'+this.y].slice(0,4).join()+'...' : tmpData_date[this.x+'_'+this.y].join() }</strong><br>
            ${dataList[0].EdbName}: <span style="font-weight: 600">	${this.x}</span><br>
            ${dataList[1].EdbName}: <span style="font-weight: 600">	${this.y}</span>
            `
        }
    }

    const { IsOrder,ChartColor } = dataList[0];
    //y轴
    let yAxis = {
        title: {
            text:  `${dataList[1].Unit}`,
            align: 'high',
            rotation: 0,
            y: -15,
            x:0,
            textAlign: 'left',
            reserveSpace: false,
            style:{
                ...chartTheme&&chartTheme.yAxisOptions.style
            },
        },
        labels: {
            formatter: function (ctx) {
            return ctx.value;
            },
            align: 'center',
            style:{
                ...chartTheme&&chartTheme.yAxisOptions.style
            },
        },
        opposite: false,
        reversed: IsOrder,
        min: Number(dataList[0].MinData),
        max: Number(dataList[0].MaxData),
        plotBands: setAxisPlotAreas(1),
        plotLines: setAxisPlotLines(1),
        tickWidth: 1,
        tickLength: 5,
        lineWidth: 1,
        lineColor: '#bfbfbf',
        tickColor: '#bfbfbf',
        offset: 0,
        visible: true,
        gridLineWidth: 0,
        tickPosition: 'inside',
        endOnTick: false,
        startOnTick: false,
        showLastLabel: true,
        tickPixelInterval: 50
    }

    //数据列
    let series = {
        data: [],
        type: 'scatter',
        name: `${ChartInfo.ChartName}${IsOrder ? '(逆序)' : ''}`,
        color: ChartColor,
        visible:true,
        chartType: 'linear',
        marker: {
          radius: (chartTheme&&chartTheme.lineOptionList[0].radius)||5,
        },
    }
    real_data.forEach(_ => {
        series.data.push([_.x,_.y])
    })
    
    chartData.value = {
        title: {
            text:''
        },
        series: [ series ],
        yAxis,
        xAxis: {
            ...scatterXAxis,
            title: {
                text:  `${dataList[0].Unit}`,
                align: 'high',
                rotation: 0,
                x: 0,
                offset: 20,
                style: {
                    ...chartTheme&&chartTheme.xAxisOptions.style
                },
            },
            labels: {
                style: {
                  ...chartTheme&&chartTheme.xAxisOptions.style
                }
            },
            plotBands: setAxisPlotAreas(3),
            plotLines: setAxisPlotLines(3)
        },
        tooltip
    }
}

// 查询范围为1年内 x轴显示为月/日 否则默认年/月
const xTimeDiffer=(minTime,maxTime)=>{
    //年限差
    let year_differ=moment(maxTime).diff(moment(minTime),'years',true)
    console.log('年限差',year_differ)
    if (year_differ<=1) {
        console.log('true');
        return true;
    } else {
        console.log('false');
        return false;
    }
}

// 找出最大最小值 arr 数据, type:min max
const getAxisMaxOrMin=(arr,type)=>{
    let minArr=[],maxArr=[],resNum=0

    arr.forEach(item=>{
        minArr.push(item.MinData)
        maxArr.push(item.MaxData)
    })

    if(type==='min'){
        resNum=Math.min.apply(null,minArr)
    }else{
        resNum=Math.max.apply(null,maxArr)
    }

    return resNum
}

 /* 处理轴的标识线结构 在指定轴位置上拼接标识线 
    0：右轴 1：左轴 2：右2轴 x轴固定3
    axisType表示x轴类型 处理时间轴的值 datetime/null 
*/
const setAxisPlotLines = (axis,axisType) => {
    const { MarkersLines,ChartType } = resData.value.ChartInfo;
    const { EdbInfoList } = resData.value;
    if(!MarkersLines) return []

    let markerLines = JSON.parse(MarkersLines);

    let arr = markerLines.filter(_ => _.isShow&&_.axis===axis)
    let plotLines = arr.map(_ => {
        //是否是x时间轴
        let isXDateAxis = axis===3&&axisType==='datetime';
        let markerValue;
        if(isXDateAxis) {
            //季节图x轴额外拼个年份
            let nowYear = ChartType===2 ? new Date(EdbInfoList[0].DataList[1].DataList
                [0].DataTimestamp).getFullYear() : '';
            markerValue = ChartType===2 
                ? new Date(`${nowYear}-${_.value}`).getTime()
                : new Date(_.value).getTime()
        }else {
            markerValue = Number(_.value)
        }

        return { 
        value: markerValue,
        dashStyle: _.dashStyle,
        width: Number(_.lineWidth),
        color: _.color,
        label: {
            text: _.text||'',
            verticalAlign: _.textPosition,
            style: {
            color: _.textColor,
            fontSize: _.textFontSize
            }
        }
        }
    })
    return plotLines
}

/* 处理标识区拼接 axisType表示x轴类型处理时间轴的值 datetime/null */
const setAxisPlotAreas = (axis,axisType) => {
    const { MarkersAreas,ChartType } = resData.value.ChartInfo;
    const { EdbInfoList } = resData.value;
    if(!MarkersAreas) return []

    let markerAreas = JSON.parse(MarkersAreas);

    let arr = markerAreas.filter(_ => _.isShow&&_.axis===axis)
    let plotBands = arr.map(_ => {
        //是否是x时间轴
        let isXDateAxis = axis===3&&axisType==='datetime';
        let fromMarkerValue,toMarkerValue;
        if(isXDateAxis) {
            //季节图x轴额外拼个年份
            let nowYear = ChartType===2 ? new Date(EdbInfoList[0].DataList[1].DataList
                [0].DataTimestamp).getFullYear() : '';
                console.log(nowYear)
            fromMarkerValue = ChartType===2 
                ? new Date(`${nowYear}-${_.fromValue}`).getTime()
                : new Date(_.fromValue).getTime()

            toMarkerValue = ChartType===2 
                ? new Date(`${nowYear}-${_.toValue}`).getTime()
                : new Date(_.toValue).getTime()
        }else {
            fromMarkerValue = Number(_.fromValue);
            toMarkerValue = Number(_.toValue);
        }

        //默认label有些偏移 重新归正下
        let positionMapValue = {
            'top': 12,
            'middle': 0,
            'bottom': -10
        }

        return { 
            from: fromMarkerValue,
            to: toMarkerValue,
            color: _.color,
            label: {
                text: _.text||'',
                verticalAlign: _.textPosition,
                y: positionMapValue[_.textPosition],
                style: {
                    color: _.textColor,
                    fontSize: _.textFontSize
                }
            }
        }
    })

    return plotBands
}

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

        //奇怪柱状图 商品价格图
        if([7,10].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].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.xMin">
                        <span style="margin:0 10px">至</span>
                        <input type="number" v-model="axisLimitData.xMax">
                    </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>