import {
  defaultOpts,
  seasonOptions,
  yearSelector,
} from '@/utils/defaultOptions';
import Highcharts from 'highcharts';
import { dataBaseInterface } from '@/api/api';
import * as preDictEdbInterface from '@/api/modules/predictEdbApi.js';
import futuresInterface from '@/api/modules/futuresBaseApi';
import chartRelevanceApi from '@/api/modules/chartRelevanceApi';
import { fittingEquationInterface,statisticFeatureInterface } from '@/api/modules/chartRelevanceApi';

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


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

export const chartSetMixin = {
	data() {
		return {
			year_select: yearSelector[0].value, //默认区间15年至今
      sameOptionType:[1,3,4,5,6],// 头部一样 配置一样的图表类型 曲线 散点 柱状 面积 组合
      yearSelector, //年份按钮组
      select_date: '', //自定义时间段
      isDateDia: false, // 时间段弹窗
      dateForm: {},
      dateTip: '请选择时间段',
      predefineColors: defaultOpts.colors.slice(0, 2), //定义颜色蓝，红 默认颜色
      fre_options: ['年', '季', '月', '周', '天'], //领先指标频度配置
      //领先频度对应英文
      leadUnitEnMap: {
        '年': 'Y',
        '季': 'Q',
        '月': 'M',
        '周': 'W',
        '天': 'D',
      },
      tableColums: [
        {
          label: '指标名称',
          key: 'EdbName',
          enKey:'EdbNameEn',
					inputTip:'点击输入英文指标名称',
          minwidthsty: '150px',
        },
        {
          label: '指标ID',
          key: 'EdbCode',
          widthsty: '120px',
        },
        {
          label: '更新频度',
          key: 'Frequency',
          enKey:'FrequencyEn',
          minwidthsty: '60px',
        },
        {
          label: '单位',
          key: 'Unit',
          enKey:'UnitEn',
					inputTip:'英文单位',
          minwidthsty: '50px',
        },
        {
          label: '起始时间',
          key: 'StartDate',
          minwidthsty: '100px',
        },
        {
          label: '最新日期',
          key: 'LatestDate',
          minwidthsty: '90px',
        },
        {
          label: '最新值',
          key: 'LatestValue',
          minwidthsty: '90px',
        },
        {
          label: '最近更新',
          key: 'ModifyTime',
          minwidthsty: '100px',
        },
        {
          label: '数据来源',
          key: 'SourceName',
        },
      ],//表格列
      tableData: [],//表格指标数据
			options: {}, //配置options
      leftIndex: -1, //左侧上下限对应下标
      rightIndex: -1, //右侧上下限对应下标
      rightTwoIndex: -1,//右2上下限对应下标
      left_extreme: [],
      right_extreme: [],
      
			chartItemStyleArr:[
				{ label: '曲线图', key: 1 ,value: 'spline'},
        // { label: '堆积面积图', key: 3 ,value: 'areaspline'},
        { label: '堆积柱状图', key: 4 ,value: 'column'},
			],//组合图可选样式

      isSetExtremeValue: false,//控制添加散点图时是否重置上下限

      isShowSaveOther: false,//图表另存为弹窗
      // -------------切换图表中英文
      currentLang:'ch', // ch(中文) en(英文)
      setEnName:false,
      // 传入的formItem所需内容
      formItemArray:[],

      /* 奇怪柱形图 */
      barDateList: [],//柱形图的绘图数据
      barXData: [],//柱形图的x轴
      barXIdList: [],//x轴id数组 用于切换英文遍历用
      barEdbData: [],//柱形图的表格数据 只用于取值
      chartLimit: {},

      /* 商品价格曲线 本来逻辑分开写 但需求又得加入myeta和eta图库共存 还是写一块算了 */
      commodityChartData: [],
      commodityXData: [],
      commodityEdbList: [],

      /* 时间截面散点图 */
      sectionScatterData: {},

      /* 相关性图表 */
      relevanceChartData:null,
      relevanceUnitEnMap:{
        '年': 'Year',
        '季': 'Season',
        '月': 'Month',
        '周': 'Week',
        '天': 'Day',
      },

      /* 统计频率图 */
      statisticFrequencyData: {}
		}
	},
  watch: {
    
    /* 奇怪柱状图数据  */
		barDateList: {
			handler(newval) {
				console.log('bar')
				newval.length && this.barXData.length && this.setBarChart();
			},
			deep: true
		},

    sectionScatterData: {
      handler(newval) {
				newval.DataList && this.setSectionScatterChart();
			},
			deep: true
    }
  },
	methods: {
    /* --------------------------------------------切换中英文 */
		async changeLanguage(lang){
      this.search_txt = '';
			this.currentLang = lang;
      
      if(this.$route.path === '/chartsetting') {
        await dataBaseInterface.setUserLang({
          ConfigCode: 'chart_language',
          ConfigValue: lang === 'en' ? 'EN' : 'CN'
        })
        this.setLangIntoStore();
        if(!this.selected_chartid) return
      }

      //不同图表来源 1eta图 2商品价格图 3相关性图表
      const sourceMap = {
        1: this.changeOptions,
        2: this.changeCommodityOptions,
        3: this.changeRelevanceOptions,
        4: this.changeRelevanceOptions,
        5: this.changeCommodityOptions,
      }

      sourceMap[this.chartInfo.Source]()
		},
    // 打开设置英文信息弹窗
    openEnNameDia(){
      this.formItemArray={}
      this.formItemArray.chartInfo=[]
      this.formItemArray.chartsList=[]
      this.formItemArray.chartInfo.push({
        label:'图表名称',
        value:this.chartInfo.ChartName,
        key:'ChartName',
        id:this.chartInfo.ChartInfoId,
        notEdit:true
      },
      {
        label:'英文图表名称',
        value:this.chartInfo.ChartNameEn,
        key:'ChartNameEn',
        id:this.chartInfo.ChartInfoId,
        placeholder:'请输入英文图表名称'
      })
      if(![3,6,7,8,9].includes(this.chartInfo.Source)){//相关性图表
        this.tableData.map(item =>{
          if(item.Unit){
            this.formItemArray.chartsList.push([
              {
                label:'指标名称',
                value:item.EdbName,
                key:'EdbName',
                id:item.EdbInfoId,
                notEdit:true
              },
              {
                label:'单位',
                value:item.Unit,
                key:'Unit',
                id:item.EdbInfoId,
                notEdit:true
              },
              {
                label:'英文指标名称',
                value:item.EdbNameEn,
                key:'EdbNameEn',
                id:item.EdbInfoId,
                placeholder:'请输入英文指标名称'
              },
              {
                label:'英文单位',
                value:item.UnitEn,
                key:'UnitEn',
                id:item.EdbInfoId,
                placeholder:'请输入英文单位'
              }
            ])
          }else{
            this.formItemArray.chartsList.push([
              {
                label:'指标名称',
                value:item.EdbName,
                key:'EdbName',
                id:item.EdbInfoId,
                notEdit:true
              },
              {
                label:'英文指标名称',
                value:item.EdbNameEn,
                key:'EdbNameEn',
                id:item.EdbInfoId,
                placeholder:'请输入英文指标名称'
              }
            ])
          }
        })
      }

      //价格曲线
      if(this.chartInfo.Source===2) {
        this.formItemArray.chartInfo.push({
          label:'期货名称',
          value:this.commodityEdbList[1].EdbName,
          key:'FutureGoodName',
          id:this.chartInfo.ChartInfoId,
          notEdit:true
        },
        {
          label:'英文期货名称',
          value:this.commodityEdbList[1].EdbNameEn,
          key:'FutureGoodNameEn',
          id:this.chartInfo.ChartInfoId,
          placeholder:'请输入英文期货名称'
        })
      }

      //利润曲线
      if(this.chartInfo.Source===5) {
        this.formItemArray.chartInfo.push({
          label:'盘面利润名称',
          value:this.chartInfo.ProfitName,
          key:'ProfitName',
          id:this.chartInfo.ChartInfoId,
          notEdit:true
        },
        {
          label:'英文盘面利润名称',
          value:this.chartInfo.ProfitNameEn,
          key:'ProfitNameEn',
          id:this.chartInfo.ChartInfoId,
          placeholder:'请输入英文盘面利润名称'
        })
      }
      this.setEnName = true
    },
    // 更新英文信息
    async updateEnName(enNameData){
      // console.log(enNameData)
      let res=null
      if([2,5].includes(this.chartInfo.Source)){//商品价格
        res=await futuresInterface.editChartEn({
          ChartInfoId: enNameData.ChartInfoId,
          ChartNameEn: enNameData.ChartNameEn,
          UnitEn: enNameData.ChartEdbInfoList[0].UnitEn || '',
          EdbNameEn: enNameData.ChartEdbInfoList[0].EdbNameEn || '',
          FutureGoodNameEn: enNameData.FutureGoodNameEn || '',
          ProfitNameEn: enNameData.ProfitNameEn || ''
        })
      }else if(this.chartInfo.Source===3){//相关性
        res=await chartRelevanceApi.editChartEn({
          ChartInfoId: enNameData.ChartInfoId,
          ChartNameEn: enNameData.ChartNameEn
        })
      }else if(this.chartInfo.Source===6){//拟合方程
        res=await fittingEquationInterface.editChartEn({
          ChartInfoId: enNameData.ChartInfoId,
          ChartNameEn: enNameData.ChartNameEn
        })
      }else if([7,8,9].includes(this.chartInfo.Source)){//统计特征
        res=await statisticFeatureInterface.editChartEn({
          ChartInfoId: enNameData.ChartInfoId,
          ChartNameEn: enNameData.ChartNameEn
        })
      }else{
        res = await dataBaseInterface.chartInfoEditEn(enNameData)
      }

			if(res.Ret !==200) return

			this.$message({
				message:res.Msg,
				type:"success"
			})
      this.getChartInfo()
			this.setEnName = false
    },

    /* 切换柱形图中英文 */
    changeBarOptions() {
      //x轴
      this.options.xAxis.categories = this.barXIdList.map(_ => this.currentLang == 'ch' 
        ? this.barEdbData.find(edb => edb.EdbInfoId===_).EdbAliasName
        : this.barEdbData.find(edb => edb.EdbInfoId===_).EdbNameEn)

      // 单位
      this.options.yAxis.forEach(item => {
        item.title.text = this.currentLang == 'ch' ? this.chartInfo.Unit : this.chartInfo.Unit;
      });
    },
    // 切换中英文时，更改图表配置
    changeOptions(){
      // console.log(this.tableData,'tableData');
      // console.log(this.currentLang,this.chartInfo.ChartType);
      console.log(this.options,'options');
      // 散点图
      if(this.chartInfo.ChartType == 5){
          this.options.yAxis.title.text = this.currentLang == 'ch' ? this.options.yAxis.title.textCh : this.options.yAxis.title.textEn;
          this.options.xAxis.title.text = this.currentLang == 'ch' ? this.options.xAxis.title.textCh : this.options.xAxis.title.textEn
          this.options.series.forEach(item => {
            item.name = this.currentLang == 'ch' ? item.nameCh : item.nameEn;
          });
          this.options.tooltip.formatter = this.currentLang == 'ch' ? this.options.tooltip.formatterCh : this.options.tooltip.formatterEn;
      }else{
        // 单位
        this.options.yAxis.forEach(item => {
          item.title.text = this.currentLang == 'ch' ? item.title.textCh : item.title.textEn;
        });
        // 图例  名称
        if(this.chartInfo.ChartType != 2){
          // 季节图 不更改图例名称
          this.options.series.forEach(item => {
            item.name = this.currentLang == 'ch' 
              ? item.nameCh 
              : (item.nameEn||item.nameCh)
          });
        }
        //截面散点 x轴标题
        if(this.chartInfo.ChartType === 10){
          this.options.xAxis.title.text = this.currentLang == 'ch' ? this.options.xAxis.title.textCh : this.options.xAxis.title.textEn;
          this.options.tooltip.formatter = this.currentLang == 'ch' ? this.options.tooltip.formatterCh : this.options.tooltip.formatterEn;
          this.options.series.forEach(item => {
            if(!item.linkedTo) {
              item.data.forEach(point => {
                point.dataLabels.format = this.currentLang == 'ch' ? point.dataLabels.formatCh : (point.dataLabels.formatEn||point.dataLabels.formatCh);
                point.dataLabels.color = (this.currentLang==='en' && !point.dataLabels.formatEn) ? '#999' : '#333'
              })
            }
          });
        } 

        //柱形图额外设置x轴中英文
        this.chartInfo.ChartType ===7 && this.changeBarOptions();
      }
    },

    /* 切换商品价格图中英文 */
    changeCommodityOptions() {
      console.log(this.options)
        this.options.yAxis.forEach(item => {
          item.title.text = this.currentLang == 'ch' ? item.title.textCh : item.title.textEn
        });
        //图例
        this.options.series.forEach(item => {
          item.name = this.currentLang == 'ch' ? item.nameCh : item.nameEn
        });
        //tooltip
        this.options.tooltip.formatter = this.currentLang == 'ch' ? this.options.tooltip.formatterCh : this.options.tooltip.formatterEn
        //x轴
        this.options.xAxis.categories = this.commodityXData.map(_ => this.currentLang == 'ch' ? _.Name:_.NameEn);
    },

    /* 切换相关性图中英文 */
    changeRelevanceOptions(){
      console.log(this.options)
        this.options.yAxis.forEach(item => {
          item.title.text = this.currentLang == 'ch' ? item.title.textCh : item.title.textEn
        });
        //图例
        this.options.series.forEach(item => {
          item.name = this.currentLang == 'ch' ? item.nameCh : item.nameEn
        });
        //tooltip
        this.options.tooltip.formatter = this.currentLang == 'ch' ? this.options.tooltip.formatterCh : this.options.tooltip.formatterEn
        this.options.xAxis.title.text=this.currentLang == 'ch' ? this.options.xAxis.title.textCh : this.options.xAxis.title.textEn
    },


    /* ================================================================ */
    /* 图表的配置项*/
    setChartOptionHandle(newval) {
      /* 显示类型  数据结构单独处理 */
      const chartSetMap = {
        1: this.setDefaultChart,
        2: this.setSeasonChart,
        3: this.setStackOrCombinChart,
        4: this.setStackOrCombinChart,
        5: this.setScatterChart,
        6: this.setStackOrCombinChart
      };

      chartSetMap[this.chartInfo.ChartType]&&chartSetMap[this.chartInfo.ChartType](newval)

      //myeta内或者数据指标库内
      if(this.$route.path === '/mychart'||this.$route.path==='/database')  this.showData = true;
    },

    /* 曲线图设置 */
    setDefaultChart(newval) {
      /* 上下限显示和值的设置 */
      if([6,7,8].includes(this.chartInfo.Source)) {
        this.leftIndex = -1;
        this.rightIndex = -1;
        this.rightTwoIndex = -1;
        this.chartLimit = {};
      }else {
        this.leftIndex = newval.findIndex((item) => item.IsAxis===1);
        this.rightIndex = newval.findIndex((item) => !item.IsAxis);
        this.rightTwoIndex = newval.findIndex((item) => item.IsAxis ===2);
      }

      //拼接标题 数据列
      let data = [];
      let ydata = [];
      // let chartData =  _.cloneDeep(newval);
      //有右二轴时排个序 按照左 右 右2的顺序
      let chartData = newval.some(_ =>_.IsAxis===2) ? this.changeEdbOrder(newval) : _.cloneDeep(newval);

      chartData.forEach((item, index) => {
        //轴位置值相同的下标
        let sameSideIndex = chartData.findIndex(
          (i) => i.IsAxis === item.IsAxis
        );

        //y轴
        let yItem = {
          ...basicYAxis,
          title: {
            text: item.Unit,
            textCh:item.Unit, // 中文
            // 中文不存在，无论英文有无都显示空
            textEn:item.UnitEn||item.Unit, // 英文
            style:{},
            styleEn:{}, // 英文样式
            align: 'high',
            rotation: 0,
            y: -15,
            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
          },
          opposite: [0,2].includes(item.IsAxis),
          reversed: item.IsOrder,
          // // min: Number(chartData[sameSideIndex].MinData),
          // // max: Number(chartData[sameSideIndex].MaxData),
          min: Number(item.MinData),
          max: Number(item.MaxData),
          tickWidth: 1,
          visible: sameSideIndex === index
        };

        //拼接标题 判断相同指标名称拼接来源
        let dynamic_title = item.EdbName;
        let dynamic_arr = chartData.filter(
          (item) => dynamic_title === item.EdbName
        );

        // 拼接配置  IsAxis左轴1 右轴0 右2轴2 IsOrder正序false 逆序true EdbInfoType是否是领先指标
        let dynamic_tag = this.concatDynamicTag(item);
        let dynamic_tag_en = this.concatDynamicTag(item,'en');
          
        //预测指标配置
        let predict_params = item.EdbInfoCategoryType === 1 ? this.getPredictParams(item) : {};

        //数据列
        let obj = {
          data: [],
          type: 'spline',
          yAxis: sameSideIndex,
          name:
            dynamic_arr.length > 1
              ? `${item.EdbName}(${item.SourceName})${dynamic_tag}`
              : `${item.EdbName}${dynamic_tag}`,
          nameCh:dynamic_arr.length > 1
          ? `${item.EdbName}(${item.SourceName})${dynamic_tag}`
          : `${item.EdbName}${dynamic_tag}`,
          nameEn:item.EdbNameEn?`${item.EdbNameEn}${dynamic_tag_en}`:`${item.EdbName}${dynamic_tag}`,
          color: item.ChartColor,
          lineWidth: Number(item.ChartWidth),
          ...predict_params
        };
        item.DataList = item.DataList || [];
        for (let i of item.DataList) {
          obj.data.push([i.DataTimestamp, i.Value]);
        }

        data.push(obj);
        ydata.push(yItem);
      });

      this.xLabelDealHandle();
      this.options = {
        series: data,
        yAxis: ydata,
      };
      if(this.currentLang=='en') this.changeOptions()
    },

    /* 堆叠图/组合图设置  
    本来和曲线图逻辑基本一致兼容下即可 为了以后便于维护和阅读还是拆开写吧
     */
    setStackOrCombinChart(newval) {

      const chartTypeMap = {
        3: 'areaspline',
        4: 'column',
        6: ''
      };
      let chartStyle = chartTypeMap[this.chartInfo.ChartType];

      //拼接标题 数据列
      let data = [];
      let ydata = [];
      // let chartData =  _.cloneDeep(newval);
      //有右二轴时排个序 按照左 右 右2的顺序
      let chartData = newval.some(_ =>_.IsAxis===2) ? this.changeEdbOrder(newval) : _.cloneDeep(newval);

      chartData.forEach((item, index) => {
        //轴位置值相同的下标
        let sameSideIndex = chartData.findIndex(
          (i) => i.IsAxis === item.IsAxis
        );

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

        /* 上下限显示的设置 */
        this.leftIndex = [3,4].includes(this.chartInfo.ChartType) 
          ? (chartData[serie_yIndex].IsAxis ? serie_yIndex : -1)
          : newval.findIndex((item) => item.IsAxis===1);
        this.rightIndex = [3,4].includes(this.chartInfo.ChartType) 
        ? (chartData[serie_yIndex].IsAxis ? -1 : serie_yIndex)
        : newval.findIndex((item) => !item.IsAxis);
        this.rightTwoIndex = [3,4].includes(this.chartInfo.ChartType) 
        ? -1
        : newval.findIndex((item) => item.IsAxis===2);

        //y轴
        let yItem = {
          ...basicYAxis,
          title: {
            // text: sameSideIndex !== index ? '' : `${item.Unit}`,
            text: item.Unit,
            textCh:item.Unit, // 中文
            // 中文不存在，无论英文有无都显示空
            textEn:item.UnitEn||item.Unit, // 英文
            style:{},
            styleEn:{}, // 英文样式
            align: 'high',
            rotation: 0,
            y: -15,
            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 sameSideIndex !== index ? '' : ctx.value;
              return ctx.value;
            },
            align: 'center',
            x: [0,2].includes(item.IsAxis) ? 5 : -5
          },
          opposite: [0,2].includes(item.IsAxis),
          reversed: item.IsOrder,
          min: Number(chartData[sameSideIndex].MinData),
          max: Number(chartData[sameSideIndex].MaxData),
          // tickWidth: sameSideIndex !== index ? 0 : 1,
          tickWidth: 1,
          visible: serie_yIndex === index && sameSideIndex ===index
        };

        //拼接标题 判断相同指标名称拼接来源
        let dynamic_title = item.EdbName;
        let dynamic_arr = chartData.filter(
          (item) => dynamic_title === item.EdbName
        );

        // 拼接配置  IsAxis左轴1 右轴0 IsOrder正序false 逆序true EdbInfoType是否是领先指标
        let dynamic_tag = this.concatDynamicTag(item);
        let dynamic_tag_en = this.concatDynamicTag(item,'en');

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

        //数据列
        let obj = {
          data: [],
          type: chartStyle || item.ChartStyle,
          yAxis: serie_yIndex,
          name:
            dynamic_arr.length > 1
              ? `${item.EdbName}(${item.SourceName})${dynamic_tag}`
              : `${item.EdbName}${dynamic_tag}`,
          nameCh:dynamic_arr.length > 1
          ? `${item.EdbName}(${item.SourceName})${dynamic_tag}`
          : `${item.EdbName}${dynamic_tag}`,
          nameEn:item.EdbNameEn?`${item.EdbNameEn}${dynamic_tag_en}`:`${item.EdbName}${dynamic_tag}`,
          color: item.ChartColor,
          lineWidth: (this.chartInfo.ChartType === 6 && item.ChartStyle === 'spline') ? Number(item.ChartWidth) : 0,
          fillColor: (this.chartInfo.ChartType === 3 || (this.chartInfo.ChartType === 6 && item.ChartStyle === 'areaspline')) ? item.ChartColor : undefined,
          borderWidth: 1,
          borderColor: item.ChartColor,
          zIndex: (this.chartInfo.ChartType === 6 && item.ChartStyle === 'spline') ? 1 : 0, //防止组合图曲线被遮住
          ...predict_params
        };
        item.DataList = item.DataList || [];
        for (let i of item.DataList) {
          obj.data.push([i.DataTimestamp, i.Value]);
        }

        data.push(obj);
        ydata.push(yItem);
      });

      this.xLabelDealHandle();
      
      this.options = {
        series: data,
        yAxis: ydata,
      };
      if(this.currentLang=='en') this.changeOptions()
    },

    /* 季节图设置 农历 公历 */
    setSeasonChart(newval) {
      /* 季节性图的图表配置 */
      this.leftIndex = 0;
      this.rightIndex = -1;
      this.rightTwoIndex = -1;
      const chartData = newval[0];
      let seasonYdata = [],
        seasonData = [];

        /* 公历数据处理 处理数据列 y轴 */
        if (this.calendar_type === '公历')
        for (let j of chartData.DataList) {
          //预测指标配置
          let predict_params =  chartData.EdbInfoCategoryType === 1 ? this.getSeasonPredictParams(j.CuttingDataTimestamp) : {};
          
          let serie_item = {
            data: [],
            type: chartData.ChartStyle,
            yAxis: 0,
            name: j.Year,
            ...predict_params
          };
          const data_array = _.cloneDeep(j.DataList);
          data_array &&
            data_array.forEach((item) => {
              serie_item.data.push([item.DataTimestamp, item.Value]);
            });
          const index = chartData.DataList.findIndex(
            (item) => item.Year === j.Year
          );
          const s_yItem = {
            labels: {
              formatter: function () {
                let val = this.value;
                return index !== 0 ? '' : val;
              },
              align: 'center',
            },
            title: {
              text:  `${chartData.Unit}`,
              textCh:chartData.Unit, // 中文
              // 中文不存在，无论英文有无都显示空
              textEn:chartData.UnitEn||chartData.Unit, // 英文
              style:{},
              styleEn:{}, // 英文样式
              // text:  null,
              align: 'high',
              rotation: 0,
              y: -15,
              offset: -(12 * chartData.Unit.length),
            },
            max: Number(chartData.MaxData),
            min: Number(chartData.MinData),
            ...seasonOptions.yAxis,
          };
          seasonData.push(serie_item);
          seasonYdata.push(s_yItem);
        }

      /* 农历数据处理  */
      let filterArr =
        this.calendar_type === '农历'
          ? chartData.DataList.List.filter((item, index) => index > 0)
          : [];
      if (this.calendar_type === '农历')
        for (let j of filterArr) {
           //预测指标配置
          let predict_params =  chartData.EdbInfoCategoryType === 1 ? this.getSeasonPredictParams(j.CuttingDataTimestamp) : {};

          let serie_item = {
            data: [],
            type: chartData.ChartStyle,
            yAxis: 0,
            name: j.Year,
            ...predict_params
          };
          const data_array = _.cloneDeep(j.Items);
          data_array &&
            data_array.forEach((item) => {
              serie_item.data.push([item.DataTimestamp, item.Value]);
            });
          const index = filterArr.findIndex((item) => item.Year === j.Year);
          const s_yItem = {
            labels: {
              formatter: function () {
                let val = this.value;
                return index !== 0 ? '' : val;
              },
              align: 'center',
            },
            title: {
              text:  `${chartData.Unit}`,
              textCh:chartData.Unit, // 中文
              // 中文不存在，无论英文有无都显示空
              textEn:chartData.UnitEn||chartData.Unit, // 英文
              styleEn:{}, // 英文样式
              // text:  null,
              align: 'high',
              rotation: 0,
              y: -15,
              offset: -(12 * chartData.Unit.length),
            },
            max: Number(chartData.MaxData),
            min: Number(chartData.MinData),
            ...seasonOptions.yAxis,
          };
          seasonData.push(serie_item);
          seasonYdata.push(s_yItem);
        }

      /* x轴显示月日  提示框显示月日*/
      defaultOpts.xAxis.labels = {
        formatter: function () {
          return Highcharts.dateFormat('%m/%d', this.value);
        },
      };
      
      const tooltip = {
        ...defaultOpts.tooltip,
        dateTimeLabelFormats: {
          // 时间格式化字符
          day: '%m/%d',
          week: '%m/%d',
          month: '%m/%d',
          year: '%m/%d',
        },
        xDateFormat: '%m/%d',
      }
      let rangeSelector =
        this.calendar_type === '农历'
          ? {
              enabled: true,
              selected: 0,
              inputStyle: {
                display: 'none',
              },
              labelStyle: {
                display: 'none',
              },
              buttonTheme: {
                style: {
                  display: 'none',
                },
              },
              buttons: [
                {
                  type: 'month',
                  count: 12,
                  text: '12月',
                },
                {
                  type: 'month',
                  count: 15,
                  text: '15月',
                },
                {
                  type: 'all',
                  text: '全部',
                  type: 'all',
                },
              ],
            }
          : {
              enabled: false,
            };

      this.options = {
        colors:
          this.calendar_type === '公历'
            ? seasonOptions.colors.slice(-chartData.DataList.length)
            : seasonOptions.colors.slice(-filterArr.length),
        series: seasonData,
        yAxis: seasonYdata,
        rangeSelector,
        tooltip
      };
      if(this.currentLang=='en') this.changeOptions()
    },

    /* 散点图设置  只允许2指标画图第一个指标值为x轴 第二个指标为y轴  */
    setScatterChart(newval) {
      console.log(newval);
      this.leftIndex = 0;
      this.rightIndex = -1;
      this.rightTwoIndex = -1;
      if(newval.length !== 2) {
        this.options = {}
        return
      };
      console.log('===========:',this.isSetExtremeValue)

      // 取2个指标中日期相同的数据
      let real_data = [];
      let tmpData_date = {};//用来取点对应的日期
      let data1 =  _.cloneDeep(newval)[0].DataList || [];
      let data2 =  _.cloneDeep(newval)[1].DataList || [];
      data1.forEach(_item => {
        data2.forEach(_item2 => {
          if(_item.DataTimestamp === _item2.DataTimestamp) {
            
            _item.DataTime = _item.DataTime.replace(/-/g,'/');
            //日期
            let itemIndex =_item.Value + "_" +_item2.Value
            if(tmpData_date[itemIndex]) {
              tmpData_date[itemIndex].push(_item.DataTime)
            } else {
              tmpData_date[itemIndex] = [_item.DataTime]
            }
            
            //值
            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>
          ${newval[0].EdbName}: <span style="font-weight: 600">	${this.x}</span><br>
          ${newval[1].EdbName}: <span style="font-weight: 600">	${this.y}</span>
          `
        },
        // 中文
        formatterCh: 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>
          ${newval[0].EdbName}: <span style="font-weight: 600">	${this.x}</span><br>
          ${newval[1].EdbName}: <span style="font-weight: 600">	${this.y}</span>
          `
        },
        // 英文
        formatterEn: function() {
          let str1 = newval[0].EdbNameEn||newval[0].EdbName;
          let str2 = newval[1].EdbNameEn||newval[1].EdbName;
          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>
          ${str1}: <span style="font-weight: 600">	${this.x}</span><br>
          ${str2}: <span style="font-weight: 600">	${this.y}</span>
          `
        }
      }
    
      // 目前指标限制死2个 为了简单 配置项直接关联第一个指标算了  自定义极值只在新增时用
      if(!this.chartInfo.ChartInfoId && this.isSetExtremeValue) {
        let maxYData = Math.max(...real_data.map(_ => _.y));
        let minYData = Math.min(...real_data.map(_ => _.y));
        newval[0].MaxData = maxYData;
        newval[0].MinData = minYData;
        this.isSetExtremeValue = false;
      }

      const { IsOrder,ChartColor } = newval[0];
      //y轴
      let yAxis = {
        ...basicYAxis,
        title: {
          text:  `${newval[1].Unit}`,
          textCh:newval[1].Unit,// 中文
          // 中文不存在，无论英文有无都显示空
          textEn:newval[1].UnitEn||newval[1].Unit, // 英文
          style:{},
          styleEn:{}, // 英文样式
          align: 'high',
          rotation: 0,
          y: -15,
          offset: -(12 * newval[1].Unit.length),
        },
        labels: {
          formatter: function (ctx) {
            let val = ctx.value;
            return val;
          },
          align: 'center',
        },
        opposite: false,
        reversed: IsOrder,
        min: Number(newval[0].MinData),
        max: Number(newval[0].MaxData),
        tickWidth: 1,
      }

      //数据列
      let series = {
        data: [],
        type: 'scatter',
        name: `${this.chartInfo.ChartName}${IsOrder ? '(逆序)' : ''}`,
        nameCh: `${this.chartInfo.ChartName}${IsOrder ? '(逆序)' : ''}`,
        nameEn: `${this.chartInfo.ChartNameEn||this.chartInfo.ChartName}${IsOrder ? '(reverse)' : ''}`,
        color: ChartColor,
        lineWidth: 0
      }
      real_data.forEach(_ => {
        series.data.push([_.x,_.y])
      })
      
      this.options = {
        title: {
          text:''
        },
        series: [ series ],
        yAxis,
        xAxis: {
          ...scatterXAxis,
          title: {
            text:  `${newval[0].Unit}`,
            textCh:newval[0].Unit, // 中文
            // 中文不存在，无论英文有无都显示空
            textEn:newval[0].UnitEn||newval[0].Unit, // 英文
            style:{},
            styleEn:{}, // 英文样式
            // text:  null,
            align: 'high',
            rotation: 0,
            x: 0,
            offset: 20,
          },
        },
        tooltip
      }
      if(this.currentLang=='en') this.changeOptions()
    },

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

      //x轴
      let xAxis = {
        ...scatterXAxis,
        categories: this.barXData,
        tickWidth: 1,
        title: {
          text:  ``,
          align: 'high',
          rotation: 0,
          x: 0,
          offset: 20,
        },
      }

      const { max,min } = this.chartLimit;
      console.log(max,min)
      //y轴
      let yAxis = {
        ...basicYAxis,
        title: {
          text:  this.chartInfo.Unit,
          textCh: this.chartInfo.Unit,
          textEn: this.chartInfo.UnitEn,
          align: 'high',
          rotation: 0,
          y: -15,
          offset: 0,
        },
        labels: {
          formatter: function (ctx) {
            let val = ctx.value;
            return val;
          },
          align: 'center',
        },
        min: Number(min),
        max: Number(max),
        opposite: false,
        tickWidth: 1,
      }

      //数据列
      data.forEach(item => {
        let serie_item = {
          data: item.Value,
          type: 'column',
          yAxis: 0,
          name: item.Name || item.Date,
          nameCh: item.Name || item.Date,
          nameEn: item.Date,
          color: item.Color,
          chartType: 'linear'
        };
        seriesData.push(serie_item)
      })
      
      this.options = {
        title: {
          text:''
        },
        plotOptions: {
          column:{
            stacking: null,
          },
        },
        series: seriesData,
        yAxis: [ yAxis ],
        xAxis
      }
      this.currentLang=='en' && this.changeOptions();
    },

    /* 商品价格曲线设置 绘图逻辑同奇怪柱形图*/
    setCommodityChart() {
      //上下限都不通用
      this.leftIndex = -1;
      this.rightIndex = -1;
      this.rightTwoIndex = -1;

      let seriesData = [];
      const data = _.cloneDeep(this.commodityChartData);

      //x轴
      let xAxis = {
        ...scatterXAxis,
        categories: this.commodityXData.map(_ =>_.Name),
        tickWidth: 1,
        title: {
          text:  ``,
          align: 'high',
          rotation: 0,
          x: 0,
          offset: 20,
        },
      }

      const { max,min } = this.chartLimit;
      //y轴
      let yAxis = {
        ...basicYAxis,
        title: {
          text:  this.commodityEdbList[0].Unit,
          textCh:  this.commodityEdbList[0].Unit,
          textEn:  this.commodityEdbList[0].UnitEn||this.commodityEdbList[0].Unit,
          align: 'high',
          rotation: 0,
          y: -15,
          offset: 0,
        },
        labels: {
          formatter: function (ctx) {
            let val = ctx.value;
            return val;
          },
          align: 'center',
        },
        min: Number(min),
        max: Number(max),
        opposite: false,
        tickWidth: 1,
      }

      //数据列
      data.forEach(item => {
        //处理首或/尾全是无效数据的以null填充
        let filterData = this.filterInvalidData(item)
        // console.log(filterData)
      
        let serie_item = {
          data: filterData,
          type: 'spline',
          yAxis: 0,
          name: item.Name,
          nameCh: item.Name,
          nameEn: item.NameEn,
          color: item.Color,
          chartType: 'linear',
          lineWidth: 3,
          marker: {
            enabled: false
          }
        };
        seriesData.push(serie_item)
      })

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

            //合约显示
            let haveContract = obj_item.XEdbInfoIdList[index];
            
            if(haveContract) {
              // 利润曲线指标名
              let edb_name = chartInfo.Source === 5 
                ? (index === 0 ? obj_item.NameList[index] : `${chartInfo.ProfitName}(${obj_item.NameList[index]})`)
                : commodityEdbList.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||'无合约'
        },
        formatterCh: function() {
          let str = ''; 
          this.points.forEach(item => {
            let obj_item = data.find(_ => _.Name === item.series.name);
            let index = commodityXData.findIndex(_ => _.Name === this.x);

            //合约显示
            let haveContract = obj_item.XEdbInfoIdList[index];
            
            if(haveContract) {
              // 利润曲线指标名
              let edb_name = chartInfo.Source === 5
                ? (index === 0 ? obj_item.NameList[index] : `${chartInfo.ProfitName}(${obj_item.NameList[index]})`)
                : commodityEdbList.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||'无合约'
        },
        formatterEn: function() {
          let str = ''; 
          this.points.forEach(item => {
            let obj_item = data.find(_ => _.NameEn === item.series.name);
            let index = commodityXData.findIndex(_ => _.NameEn === this.x);

            //合约显示
            let haveContract = obj_item.XEdbInfoIdList[index];

            if(haveContract) {
              // 利润曲线指标名
              let edb_name = chartInfo.Source === 5
                ? (index === 0 ? obj_item.NameList[index] : `${chartInfo.ProfitNameEn}(${obj_item.NameList[index]})`)
                : commodityEdbList.find(_ => _.EdbInfoId === obj_item.XEdbInfoIdList[index]).EdbNameEn;
              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,
      }
      
      this.options = {
        title: {
          text:''
        },
        series: seriesData,
        yAxis: [ yAxis ],
        xAxis,
        tooltip
      }

      this.currentLang==='en' && this.changeCommodityOptions();
    },

    /* 处理无效数据为null */
    filterInvalidData(item) {
      //找出第一个有效数据和最后一个有效数据的index index1 index2
      //0到index1全填null index2到最后一个全为null

        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
          }
        })
        return arr;
    },

    /* 获取图表详情后赋值柱状图数据 */
    initBarData(data) {
      const { XEdbIdValue,YDataList,EdbInfoList,ChartInfo } = data;

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

      this.leftIndex = -1;
      this.rightIndex = -1;
      this.rightTwoIndex = -1;
      
      this.barXIdList = XEdbIdValue;
      this.barDateList = YDataList;
      this.barXData = xData;
      this.barEdbData = EdbInfoList;
      this.chartLimit = {
        min: Number(ChartInfo.LeftMin),
        max: Number(ChartInfo.LeftMax)
      }
    },

    /* 商品价格曲线获取详情赋值 */
    initCommodityData(data) {
      const { XDataList,YDataList,EdbInfoList,ChartInfo,DataResp } = data;

      this.commodityEdbList = EdbInfoList;
      this.commodityChartData = ChartInfo.Source===5?DataResp.YDataList:YDataList;
      this.commodityXData = ChartInfo.Source===5?DataResp.XDataList:XDataList;
      this.chartLimit = {
        min: Number(ChartInfo.LeftMin),
        max: Number(ChartInfo.LeftMax)
      }
      this.setCommodityChart()
    },

     /* 相关性图表初始化 source4 滚动相关性*/
    initRelevanceChartData(){
      this.leftIndex = -1;
      this.rightIndex = -1;
      this.rightTwoIndex = -1;
      // 处理X轴
      let xAxis={
        categories: this.relevanceChartData.XEdbIdValue,
        tickWidth: 1,
        title: {
          text: this.relevanceChartData.ChartInfo.Source===3 ?`期数（${this.relevanceChartData.CorrelationChartInfo.LeadUnit}）` : null,
          textCh:this.relevanceChartData.ChartInfo.Source===3 ? `期数（${this.relevanceChartData.CorrelationChartInfo.LeadUnit}）`:null,
          textEn:this.relevanceChartData.ChartInfo.Source===3 ? `stage（${this.relevanceUnitEnMap[this.relevanceChartData.CorrelationChartInfo.LeadUnit]}）`:null,
          align: 'high',
          rotation: 0,
          x: 0,
          y:10,
          offset: 20
        },
        tickInterval: 1,
        offset:0,
        tickmarkPlacement:'on'
      }

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

      //处理series
      let seriesData=[]
      this.relevanceChartData.YDataList.forEach(item=>{
        let serie_item = {
          data: item.Value,
          type: 'spline',
          yAxis: 0,
          name: item.Name,
          nameCh: item.Name,
          nameEn: item.NameEn,
          color: item.Color,
          chartType: 'linear',
          lineWidth: 3,
          marker: {
            enabled: false
          }
        };
        seriesData.push(serie_item)
      })
      
      const { LeadValue,LeadUnit } = this.relevanceChartData.CorrelationChartInfo;
      const { Source } = this.relevanceChartData.ChartInfo;
      let relevanceUnitEnMap = this.relevanceUnitEnMap;
      let tooltip = {
        formatter: function() {
          let str = `<p>相关性系数：${this.y.toFixed(4)}</p><br><p>领先${ Source===3 ?this.x+'期' : LeadValue+LeadUnit}</p>`
          return str
        },
        formatterCh: function() {
          let str = `<p>相关性系数：${this.y.toFixed(4)}</p><br><p>领先${ Source===3 ?this.x+'期' : LeadValue+LeadUnit}</p>`
          return str
        },
        formatterEn: function() {
          let str = `<p>Correlation coefficient：${this.y.toFixed(4)}</p><br><p>lead${ Source===3 ? this.x+'stage' : LeadValue+relevanceUnitEnMap[LeadUnit]}</p>`
          return str
        }
      }

      this.options = {
        isRelevanceChart: Source===3,
        title: {
          text:''
        },
        series: seriesData,
        yAxis: [yAxis] ,
        xAxis:xAxis,
        tooltip
      }
      console.log('处理结束相关性图表',this.options);
    },

    /* 截面散点图获取详情赋值 */
    initSectionScatterData({ DataResp }) {
      this.chartLimit = {
        min: Number(DataResp.YMinValue),
        max: Number(DataResp.YMaxValue),
        x_min: Number(DataResp.XMinValue),
        x_max: Number(DataResp.XMaxValue)
      }

      this.sectionScatterData = DataResp;
    },

    /* 截面散点图设置 sectionScatterData */
    setSectionScatterChart() {
      this.leftIndex = -1;
      this.rightIndex = -1;
      this.rightTwoIndex = -1;
      
      const { DataList,XName,XNameEn,XUnitName,XUnitNameEn,YName,YNameEn,YUnitName,YUnitNameEn } = this.sectionScatterData;
      const { min,max,x_min,x_max }  = this.chartLimit;

      //y轴
      let yAxis = {
        ...basicYAxis,
        title: {
          text: YName,
          textCh:YName,// 中文
          textEn:YNameEn||YName,
          style:{},
          styleEn:{},
          align: 'middle',
        },
        opposite: false,
        reversed: false,
        min: Number(min),
        max: Number(max),
        tickWidth: 1,
      }

      //x轴
      let xAxis = {
        ...scatterXAxis,
        title: {
          text: XName,
          textCh:XName,// 中文
          textEn:XNameEn || XName,
          style:{},
          styleEn:{},
          align: 'middle',
        },
        min: Number(x_min),
        max: Number(x_max),
      }

      //数据列
      let series = [];
      DataList.forEach(item => {
        //数据列
        let series_item = {
          data: [],
          type: 'scatter',
          name: item.Name,
          nameCh: item.Name,
          nameEn: item.NameEn||item.Name,
          color: item.Color,
          lineWidth: 0,
          chartType: 'linear',
          zIndex:1
        }
        item.EdbInfoList.forEach(_ => {
          series_item.data.push({
            x: _.XValue,
            y: _.YValue,
            dataLabels: {
              enabled: _.IsShow,
              allowOverlap: true,
              align: 'left',
              format: _.Name,
              formatCh: _.Name,
              formatEn: _.NameEn||_.Name
            }
          })
        })
        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,
            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
        },
        formatterCh: 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
          
        },
        formatterEn: function() {
          let series_obj = DataList.find(_ => _.NameEn === this.series.name);
          let ponit_obj = series_obj.EdbInfoList.find(_ => _.XValue ===this.x && _.YValue===this.y);

          let str=`<b>${ ponit_obj.NameEn }</b>`;
          str += `<br><span style="color:${this.color}">\u25CF</span>${ponit_obj.XNameEn}: ${this.x} ${ponit_obj.XDate}<br>`;
          str += `<span style="color:${this.color}">\u25CF</span>${ponit_obj.YNameEn}: ${this.y} ${ponit_obj.YDate}`;

          return str
        }
      }
      
      this.options = {
        title: {
          text:''
        },
        series,
        yAxis: [yAxis],
        xAxis,
        tooltip
      }
      this.currentLang=='en' && this.changeOptions()
    },


    /* 统计频率图 */
    setStatisticFrequency() {
      this.leftIndex = -1;
      this.rightIndex = -1;
      this.rightTwoIndex = -1;

      const { DataList,LeftMaxValue,LeftMinValue,RightMaxValue,RightMinValue } = this.statisticFrequencyData;
      
      let xAxis = {
        ...scatterXAxis,
        tickWidth: 1,
        title: {
          text:  ``,
          align: 'high',
          rotation: 0,
          x: 0,
          offset: 20,
        }
      }

      //y和系列
      let yAxis = [],series = [];
      DataList.forEach((item,index) => {
        let y_item = {
          ...basicYAxis,
          title: {
            text: item.Unit,
            textCh:item.Unit,// 中文
            textEn:item.UnitEn||item.Unit,
            align: 'high',
            rotation: 0,
            y: -15,
            offset: 0,
          },
          opposite: item.IsAxis===1?false:true,
          min: index===0? Number(LeftMinValue):Number(RightMinValue),
          max: index===0? Number(LeftMaxValue):Number(RightMaxValue),
          tickWidth: 1,
        }

        let series_item = {
          data: item.Value.map(_ =>[_.X,_.Y]),
          type: 'spline',
          yAxis: index,
          name: item.Name,
          nameCh: item.Name,
          nameEn: item.NameEn||item.Name,
          color: item.Color,
          lineWidth: 3,
          chartType: 'linear',
          zIndex:1
        }

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

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

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

      this.options = {
        title: {
          text:''
        },
        tooltip,
        series,
        yAxis,
        xAxis
      }
      this.currentLang=='en' && this.changeOptions()
    },

		/* 查询范围为1年内 x轴显示为月/日 否则默认年/月 */
		xLabelDealHandle() {
			const end =
				this.year_select === 5
					? this.select_date[1]
					: this.year_select === 6
					? new Date()
					: '';
			const year_differ = this.$moment(end).diff(
				this.$moment(this.select_date[0]),
				'years',
				true
			);
			// console.log(year_differ)
			if ([5, 6].includes(this.year_select) && year_differ <= 1) {
				defaultOpts.xAxis.labels = {
					formatter: function () {
						return Highcharts.dateFormat('%m/%d', this.value);
					},
				};
			} else {
				defaultOpts.xAxis.labels = {};
			}
		},

    /* 拼接动态的指标名称小标签 */
    concatDynamicTag({ IsAxis,IsOrder,EdbInfoType,LeadValue,LeadUnit },lang='ch') {
      // IsAxis左轴1 右轴0 2右2轴 
      //IsOrder正序false 逆序true 
      //EdbInfoType是否是领先指标
      // lang ch 中文 en 英文
      const axisLabelMap = lang=='ch'?{
        0: '右轴',
        2: '右2轴'
      }:{
        0: 'RHS',
        2: '2-RHS'
      }
      const orderLabelMap = lang=='ch'?{
        1: '逆序'
      }:{
        1: 'REV'
      }
      const edbInfoMap = lang=='ch'?{
        0: '领先'
      }:{
        0: 'Lead'
      }

      //英文领先单位转换
      const leadUnit = lang==='ch' ? LeadUnit : this.leadUnitEnMap[LeadUnit];

      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}` : '';

      return (axis_tag || order_tag || edb_tag) ? `(${axis_tag}${order_tag}${edb_tag})` : ''
    },

    /* 指标顺序调整  IsAxis: 0右轴 1左轴 2右2*/
    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);
    },

    /* 获取同侧极值 左右极值 */
    getSameSideExtreme(newval) {
      // // 左侧
      let leftArr = newval.filter(item => item.IsAxis === 1);
      let left_extreme_max = leftArr.length ? Math.max(...leftArr.map(item => Number(item.MaxData))) : undefined;
      let left_extreme_min = leftArr.length ? Math.min(...leftArr.map(item => Number(item.MinData))) : undefined;

      // // 右侧
      let rightArr = newval.filter(item => !item.IsAxis);
      let right_extreme_max = rightArr.length ? Math.max(...rightArr.map(item => Number(item.MaxData))) : undefined;
      let right_extreme_min = rightArr.length ? Math.min(...rightArr.map(item => Number(item.MinData))) : undefined;

      this.left_extreme = leftArr.length ? [left_extreme_max,left_extreme_min] : [];
      this.right_extreme = rightArr.length ? [right_extreme_max,right_extreme_min] : [];


    },

    /* 用于复制指标 */
    async copyCode({EdbInfoId, EdbInfoCategoryType}) {
      let params = {
        PageSize: 100000,
        CurrentIndex: 1,
        EdbInfoId: EdbInfoId,
      }
      const res = EdbInfoCategoryType === 1 
        ? await preDictEdbInterface.edbDataInfo(params)
        : await dataBaseInterface.targetList(params);
      if (res.Ret !== 200) return

      let arr = res.Data.Item.DataList || [];

      let str = '日期\t 值\n';
      arr.forEach((item) => (str += `${item.DataTime}\t${item.Value}\n`));
      this.$copyText(str).then(
        (res) => {
          this.$message.success('已成功复制!');
        },
        (err) => {
          this.$message.error('复制失败!');
        }
      );
    },

    /* 查看数据 跳转指标库展开具体指标 */
    viewTarget({ UniqueCode,EdbInfoId,EdbInfoCategoryType,ClassifyId }) {
      let path = EdbInfoCategoryType ? '/predictEdb' : '/database';
      let {href} = this.$router.resolve({path, query: {
        code: UniqueCode,
        id: EdbInfoId,
        classifyId:ClassifyId
      }});
			window.open(href,'_blank');
    },

    /* 领先指标 过滤负数 小数点*/
    filterCode(item) {
      item.LeadValue=item.LeadValue.replace(/[^\.\d]/g,'').replace('.','');
    },

    /* 线条粗细 过滤最小1 */
    filterWidth(item) {
      item.ChartWidth = Number(item.ChartWidth) >= 1 ? Number(item.ChartWidth) : 1;
    },

    /* 图标复制的 blob方法*/
    copyBlobItem(widthNum,heightNum,svg,genre){
      let bas64 = this.svgToBase64(svg)
      const dynamic_condition = {
        bigScreen:{
          x:1.22,
          zoomY:0.8,
          zoomX:0.8,
        },
        smallScreen:{
          x:1,
          zoomY:1,
          zoomX:1,
        }
      }
      const {x,zoomY,zoomX} =  dynamic_condition.smallScreen;
      // const {x,zoomY,zoomX} = document.body.clientWidth > 1500 && genre === '微信' ? dynamic_condition.bigScreen : dynamic_condition.smallScreen;
      const canvas = document.createElement("canvas");
      const ctx = canvas.getContext("2d");
      const img = new Image();
      canvas.width = widthNum / x;
      canvas.height = heightNum  / x;
      img.crossOrigin = "Anonymous";
      img.src = bas64;
      img.onload = () => {
        ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
        if(genre === '微信'){
        ctx.fillStyle="#fff";
        ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
        }
        ctx.scale(zoomX,zoomY)
        ctx.drawImage(img, 0, 0); // 将canvas转为blob
        if(window.ClipboardItem) {
          canvas.toBlob(async (blob) => {
            const data = [new ClipboardItem({ [blob.type]: blob })]; 
            await navigator.clipboard.write(data).then(
              () => {
               this.$message.success('复制成功！')
              },
              () => {
                this.$message.warning('复制失败,稍后再试')
              }
            );
          });
        }else {
          this.$message.warning('浏览器暂不支持')
        }
      };
    },

    /* 图标复制的 区分微信 office 来动态的计算*/
    dynamicWidthAndHeight(type, ChartType, ChartName, tableData) {
      //动态计算高度 宽度
      let heightNum = this.sameOptionType.includes(ChartType) ? 352 + parseInt((tableData - 1) / 2) * 20 : 352;
      let widthNum = this.sameOptionType.includes(ChartType) ? parseFloat(heightNum * (591 / 352)) : 591;
      widthNum = type === "微信" ? 1260 : widthNum;
      heightNum = type === "微信" ? 669 : heightNum;
      //动态 标题
      let count = parseInt(widthNum / 21);
      let reg = new RegExp("(.{" + count + "})", "g");
      let newTitle = ''
      if(this.currentLang == 'ch'){
        newTitle = _.cloneDeep(ChartName).replace(/\s/g, "").replace(reg, "$1<br/>");
      }else{
        newTitle = _.cloneDeep(ChartName);
      }
      //动态配置
      let dynamic_copyOptions = {
        legend: {
          labelFormatter: function () {
            let count = 0
            let reg = ''
            // let newName = this.name.replace(/-/g, "—").replace(/\s/g, "").replace(reg, "$1<br/>");
            let newName=''
            if(this.currentLang == 'ch'){
              count = widthNum > 1000 ? 510 / 14 : 15;
              reg = new RegExp("(.{" + parseInt(count) + "})", "g");
              newName = this.name.replace(/-/g, "—").replace(/\s/g, "").replace(/（/g, "(").replace(/）/g, ")").replace(reg, "$1<br/>");
            }else{
              // '<span style="color:#999">无英文名称</span>' 没有填写指标名称 显示为空
              if(this.name.indexOf('<span style="color:#999">无英文名称</span>')!=-1) this.name=''
              newName = this.name.replace(/（/g, "(").replace(/）/g, ")");
            }
            let finalName=  newName.substring(newName.length - 6, newName.length) === "<br/>)" ? newName.slice(0, newName.length - 6) + ")" : newName;
            return finalName;
          },
          itemWidth: widthNum > 1000 ? 530 : 235,
        },
        seasonLegend: {},
      };
      return {
        heightNum,
        widthNum,
        newTitle,
        dynamic_copyOptions,
      };
    },

    /* 控制y轴配置项是否显示 其他类型图|堆叠图第一个显示|组合图第一个堆叠的样式显示 */
    showYOptionsHandle(item,index) {
      let isShowOptions = true;
      // 图表类型不是堆叠或组合 y轴配置显示
      // 堆叠图类型第一个指标的y轴配置显示 其余不显示
      // 组合图类型 组合样式不是堆叠 显示
      //组合图类型 组合样式是堆叠 第一个堆叠的y轴配置显示 其余相同样式堆叠不显示
      if([3,4].includes(this.chartInfo.ChartType) && index !== 0) {
        isShowOptions = false
      } else if(this.chartInfo.ChartType ===6 
        && ['areaspline','column'].includes(item.ChartStyle) 
        && index !== this.tableData.findIndex(_ => _.ChartStyle === item.ChartStyle)) {
        isShowOptions = false
      }

      return isShowOptions;
    },

    /* 图表另存为  */
    saveChartOtherHandle() {
      this.isShowSaveOther = true;
    },

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

    /* 转base64 */
    svgToBase64(svg) {
      const base64img = `data:image/svg+xml;base64,${window.btoa(
        unescape(encodeURI(svg))
      )}`;
      // console.log(base64img)
      return base64img;
    },

    /* 改变上下限时重绘图 依赖于chartLimit的柱 商品价格 散点截面 */
    changeLimit() {
      const typeMap = {
        7: this.setBarChart,
        10: this.setSectionScatterChart
      }
      const sourceMap = {
        2: this.setCommodityChart,
        // 3:
      }
      if(this.chartInfo.Source === 1) {
        typeMap[this.chartInfo.ChartType]()
      }else {
        sourceMap[this.chartInfo.Source]();
      }
    }
	}
}