import { lineChart, CATEGORIES } from '../../configuration/constants'
import { echartsBasicListen } from '../../feature/traits/common'
import { throttle } from '../../utils'

export default {

  // 组件名称
  name: lineChart,

  // 前面板html模板
  viewTemplate() {
    return `
      <div data-gjs-type="${lineChart}" class="${lineChart}"></div>
    `
  },
  // 前面板html样式
  viewStyle() {
    return `
      <style>
        .${lineChart} {
          position: absolute;
          border-radius: 5px;
          border-style: solid;
          border-width: 1px;
          border-color: transparent;
          padding: 10px;
          width: 600px;
          height: 400px;
        }
      </style>
    `
  },

  // 编辑器右侧块管理器中显示属性配置
  blockOptions() {
    return {
      category: CATEGORIES.ECHARTS,
      label: `
      <svg  class="gjs-block-svg" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" ><path d="M408.533 425.173l256.64 213.76 333.44-455.68-34.56-25.173-306.56 418.987-255.36-212.907-248.32 315.947 33.707 26.453 221.013-281.387z" p-id="36183"></path><path d="M42.667 896V85.333H0v853.334h1024V896H42.667z" ></path></svg>
        <div class="gjs-block-label">线形图</div>
      `,
    };
  },

  // 后面板显示属性配置
  spOptions() {
    return {
      label: '线形图',
      icon: 'globe',
      docUrl: 'https://www.yuque.com/docs/share/062e7a46-b543-470c-bbcc-2f4e0466de79#',
      author: '秋水',
      email: 'qiushui.smy@xuelangyun.com',
      inPorts: [{
        uuid: 'in1',
        subType: 'json',
        description: {
          zh_CN: '输入1'
        }
      }],
      outPorts: [{
        uuid: 'out1',
        subType: 'json',
        description: {
          zh_CN: '输出1'
        }
      }]
    }
  },

  // 组件属性
  componentOptions() {
    return {
      name: lineChart,
      resizable: true,
      dmode: 'absolute',
      droppable: false,
      traits: [
        {
          name: 'xAxisName',
          label: 'x轴名称',
          changeProp: 1
        }, {
          name: 'yAxisName',
          label: 'Y轴名称',
          changeProp: 1
        }, {
          name: 'xAxisType',
          label: 'X轴类型',
          changeProp: 1,
          type: 'select',
          options: [{name: "类目轴", id: "category"}, {name: "数据轴", id: "value"}]
        }, {
          name: 'yAxisType',
          label: 'Y轴类型',
          changeProp: 1,
          type: 'select',
          options: [{name: "类目轴", id: "category"}, {name: "数据轴", id: "value"}]
        }, {
          name: 'axisNameFontsize',
          label: '轴名称字号',
          changeProp: 1,
          type: 'number',
          min: 9,
          step: 1
        }, {
          name: 'yAxisUnit',
          label: 'Y轴单位',
          changeProp: 1
        }, {
          name: 'axisColor',
          label: '坐标轴颜色',
          changeProp: 1,
          type: 'color'
        }, {
          name: 'axisLineWidth',
          label: '坐标轴线宽',
          changeProp: 1,
          type: 'number',
          min: 1,
          step: 1
        }, {
          name: 'axisLabelFontsize',
          label: '刻度值字号',
          changeProp: 1,
          type: 'number',
          min: 9,
          step: 1
        }, {
          name: 'axisLabelFontFamily',
          label: '刻度值字体',
          changeProp: 1,
          type: 'select',
          options: [
            { id: 'sans-serif', name: '默认' },
            { id: '庞门正道', name: '庞门正道' },
            { id: 'DS-Digital', name: 'DS-Digital' }
          ]
        }, {
          name: 'xAxisSplitLine',
          label: 'X轴分割线',
          changeProp: 1,
          type: 'checkbox'
        }, {
          name: 'xAxisTick',
          label: 'X轴刻度线',
          changeProp: 1,
          type: 'checkbox'
        }, {
          name: 'yAxisSplitLine',
          label: 'Y轴分割线',
          changeProp: 1,
          type: 'checkbox'
        }, {
          name: 'yAxisTick',
          label: 'Y轴刻度线',
          changeProp: 1,
          type: 'checkbox'
        }, {
          name: 'yAxisSplitLineType',
          label: 'Y轴分割线类型',
          type: 'select',
          changeProp: 1,
          options: [{ id: 'solid', name: '实线' }, { id: 'dashed', name: '虚线' }, { id: 'dotted', name: '点线' }]
        }, {
          name: 'gridPadding',
          label: '容器边距(左,上,右,下)',
          changeProp: 1
        }, {
          name: 'containLabel',
          label: '包含刻度标签',
          changeProp: 1,
          type: 'checkbox'
        }, {
          name: 'xLabelRotate',
          label: 'X轴标签旋转',
          changeProp: 1,
          type: 'number'
        }, {
          name: 'xLabelMap',
          label: 'X轴标签映射',
          changeProp: 1,
        }, {
          name: 'xDimension',
          label: 'X轴数据维度',
          changeProp: 1,
          type: 'number',
          min: 0,
          step: 1
        }, {
          name: 'yDimension',
          label: 'Y轴数据维度',
          changeProp: 1,
        }, {
          name: 'smooth',
          label: '平滑',
          changeProp: 1,
          type: 'checkbox'
        }, {
          name: 'connectNulls',
          label: '连接空数据',
          changeProp: 1,
          type: 'checkbox'
        }, {
          name: 'lineWidth',
          label: '线宽',
          changeProp: 1,
          type: 'number'
        }, {
          name: 'area',
          label: '区域填充',
          changeProp: 1,
          type: 'select',
          options: [{ id: 'null', name: '无填充' }, { id: 'gradient', name: '渐变填充' }, { id: 'color', name: '纯色填充' }]
        }, {
          name: 'symbol',
          label: '节点',
          type: 'select',
          changeProp: 1,
          options: [{ id: 'emptyCircle', name: '空心圆' }, { id: 'circle', name: '圆形' }, { id: 'rect', name: '矩形' }, { id: 'roundRect', name: '圆角矩形' }, { id: 'triangle', name: '三角形' }, { id: 'diamond', name: '菱形' }, { id: 'pin', name: '大头针' }, { id: 'arrow', name: '箭头' }, { id: 'none', name: '无' }]
        }, {
          name: 'symbolSize',
          label: '节点大小(px)',
          changeProp: 1,
          type: 'number',
          min: 1,
          step: 1
        }, {
          name: 'shadowColor',
          label: '阴影颜色',
          changeProp: 1,
        }, {
          name: 'shadowBlur',
          label: '阴影模糊',
          changeProp: 1,
          type: 'number',
          step: 1,
        }, {
          name: 'shadowOffsetX',
          label: '阴影水平偏移',
          changeProp: 1,
          type: 'number',
          step: 1
        }, {
          name: 'shadowOffsetY',
          label: '阴影垂直偏移',
          changeProp: 1,
          type: 'number',
          step: 1
        }, {
          name: 'stack',
          label: '数据堆叠',
          changeProp: 1,
          type: 'checkbox'
        }, {
          name: 'labelPosition',
          label: '标签',
          type: 'select',
          changeProp: 1,
          options: [{ id: 'null', name: '无标签' }, { id: 'top', name: '上' }, { id: 'left', name: '左' }, { id: 'right', name: '右' }, { id: 'bottom', name: '下' }, { id: 'inside', name: '内部' }, { id: 'insideLeft', name: '内部左侧' }, { id: 'insideRight', name: '内部右侧' }, { id: 'insideTop', name: '内部上侧' }, { id: 'insideBottom', name: '内部下侧' }, { id: 'insideRight', name: '内部右侧' }, { id: 'insideRight', name: '内部右侧' }]
        }, {
          name: 'labelDistance',
          label: '标签边距',
          changeProp: 1,
          type: 'number',
          min: 5,
        }, {
          name: 'labelFontsize',
          label: '标签字号',
          changeProp: 1,
          type: 'number',
          min: 9,
        }, {
          name: 'labelColor',
          label: '标签颜色',
          changeProp: 1,
          type: 'color',
        }, {
          name: 'tooltipFontsize',
          label: '提示框字号',
          changeProp: 1,
          type: 'number',
          min: 9,
        }, {
          name: 'showDataZoom',
          label: '显示放大镜',
          changeProp: 1,
          type: 'checkbox'
        }, {
          name: 'zoomStart',
          label: '放大镜开始(%)',
          changeProp: 1,
          type: 'number'
        }, {
          name: 'zoomEnd',
          label: '放大镜结束(%)',
          changeProp: 1,
          type: 'number'
        }, {
          name: 'hiddenDimension',
          label: '非渲染数据维度',
          changeProp: 1,
        }, {
          name: 'inLoader',
          label: '包含Loading',
          changeProp: 1,
          type: 'checkbox'
        }, {
          name: 'setAllOption',
          label: '全量更新',
          changeProp: 1,
          type: 'checkbox'
        }, {
          name: 'clickEvent',
          label: '鼠标事件',
          changeProp: 1,
          type: 'select',
          options: [{ id: 'null', name: '无' }, { id: 'click', name: '单击' }, { id: 'dblclick', name: '双击' }, { id: 'mousedown', name: '按下' }, { id: 'mouseup', name: '松开' }, { id: 'mouseover', name: '滑过' }, { id: 'mouseout', name: '滑出' }]
        }, {
          name: 'csv',
          label: '示例数据',
          changeProp: 1,
          type: 'csvDownload',
          preFileName: '线形图',
          datas: [["name", "DEMO-1", "DEMO-2"], ["one", 1, 2], ["two", 2, 5], ["three", 3, 4], ["four", 4, 1], ["five", 5, 7]]
        }, {
          name: 'defaultData',
          changeProp: 1,
          type: 'hide'
        }
      ],
      defaultData:JSON.stringify([
        ["name", "DEMO-1", "DEMO-2", "DEMO-3"], 
        ["one", 1, 2, 3], 
        ["two", 2, 5, 1], 
        ["three", -3, 4, 1], 
        ["four", 4, 1, 6], 
        ["five", 5, 7, 1]
      ]).replace(/\"/g, "\\\""),
      'xAxisName': null,
      'yAxisName': null,
      'xAxisType': 'category',
      'yAxisType': 'value',
      'axisColor': '#333333',
      'axisLineWidth': 1,
      'yAxisUnit': null,
      'axisNameFontsize': 12,
      'xAxisSplitLine': false,
      'xAxisTick': true,
      'yAxisSplitLine': true,
      'yAxisTick': true,
      'axisLabelFontsize': 12,
      'axisLabelFontFamily': 'sans-serif',
      'yAxisSplitLineType': 'dashed',
      'gridPadding': '10%,60,10%,60',
      'containLabel': true,
      'labelPosition': 'null',
      'labelDistance': 5,
      'labelFontsize': 12,
      'labelColor': '#333333',
      'tooltipFontsize':12,
      'xLabelRotate': null,
      'xLabelMap': null,
      'xDimension': 0,
      'yDimension': '1',
      'smooth': false,
      'setAllOption': false,
      'connectNulls': false,
      'lineWidth': 1,
      'area': 'null',
      'symbol': 'emptyCircle',
      'symbolSize': 4,
      'shadowBlur': 0,
      'shadowOffsetX': 0,
      'shadowOffsetY': 0,
      'stack': false,
      'showDataZoom': false,
      'zoomStart': -1,
      'zoomEnd': 100,
      'inLoader': false,
      'hiddenDimension': null,
      'clickEvent': 'null',
    }
  },

  onModelScript() {
    const dataSource = '{[ dataSource ]}';
    const bgColor = '{[ bgColor ]}';
    const borderColor = '{[ borderColor ]}';
    const fontColor = '{[ fontColor ]}';
    const fontSize = Number('{[ fontSize ]}');
    let colors = '{[ colors ]}';
    let legendPosition = ('{[ legendPosition ]}').toString();
    const legendOrient = ('{[ legendOrient ]}').toString();
    const legendIcon = ('{[ legendIcon ]}').toString();
    const legendItemGap = Number('{[ legendItemGap ]}');
    const legendItemWidth = Number('{[ legendItemWidth ]}');
    const legendItemHeight = Number('{[ legendItemHeight ]}');
    const legendFontSize = Number('{[ legendFontSize ]}');
    const legendFontFamily = ('{[ legendFontFamily ]}').toString();
    const labelPosition = ('{[ labelPosition ]}').toString();
    const labelFontsize = Number('{[ labelFontsize ]}');
    const labelDistance = Number('{[ labelDistance ]}');
    const labelColor = '{[ labelColor ]}';
    const tooltipFontsize = Number('{[ tooltipFontsize ]}');
    const titleText = '{[ titleText ]}';
    const titleColor = '{[ titleColor ]}';
    const titlePosition = ('{[ titlePosition ]}').toString();
    const xAxisName = '{[ xAxisName ]}';
    const yAxisName = '{[ yAxisName ]}';
    const xAxisType = ('{[ xAxisType ]}').toString();
    const yAxisType = ('{[ yAxisType ]}').toString();
    const axisNameFontsize = Number('{[ axisNameFontsize ]}');
    const yAxisUnit = ('{[ yAxisUnit ]}').toString();
    const axisColor = '{[ axisColor ]}';
    const axisLineWidth = Number('{[ axisLineWidth ]}');
    const xAxisSplitLine = Boolean('{[ xAxisSplitLine ]}');
    const xDimension = Boolean('{[ xDimension ]}') ? Number('{[ xDimension ]}') : 0;
    let yDimension = ('{[ yDimension ]}').toString();
    const xAxisTick = Boolean('{[ xAxisTick ]}');
    const yAxisTick = Boolean('{[ yAxisTick ]}');
    const yAxisSplitLine = Boolean('{[ yAxisSplitLine ]}');
    const yAxisSplitLineType = ('{[ yAxisSplitLineType ]}').toString();
    const axisLabelFontsize = Number('{[ axisLabelFontsize ]}');
    const axisLabelFontFamily = ('{[ axisLabelFontFamily ]}').toString();
    let gridPadding = '{[ gridPadding ]}';
    const xLabelRotate = '{[ xLabelRotate ]}';
    const smooth = Boolean('{[ smooth ]}');
    const setAllOption = Boolean('{[ setAllOption ]}');
    const connectNulls = Boolean('{[ connectNulls ]}');
    const area = ('{[ area ]}').toString();
    const lineWidth = Number('{[ lineWidth ]}');
    const symbol = ('{[ symbol ]}').toString();
    const symbolSize = Number('{[ symbolSize ]}');
    let shadowColor = '{[ shadowColor ]}';
    const shadowOffsetX = Boolean('{[ shadowOffsetX ]}') ? Number('{[ shadowOffsetX ]}') : 0;
    const shadowOffsetY = Boolean('{[ shadowOffsetY ]}') ? Number('{[ shadowOffsetY ]}') : 0;
    const shadowBlur = Boolean('{[ shadowBlur ]}') ? Number('{[ shadowBlur ]}') : 0;
    const stack = Boolean('{[ stack ]}') ? '总量' : null;
    const showDataZoom = Boolean('{[ showDataZoom ]}');
    const zoomStart = Number('{[ zoomStart ]}');
    const zoomEnd = Number('{[ zoomEnd ]}');
    let legendMap = ('{[ legendMap ]}').toString();
    const xLabelMap = ('{[ xLabelMap ]}').toString();
    const clickEvent = ('{[ clickEvent ]}').toString();
    const inLoader = Boolean('{[ inLoader ]}');
    const containLabel = Boolean('{[ containLabel ]}');
    let hiddenDimension = '{[ hiddenDimension ]}';
    const defaultData = JSON.parse('{[ defaultData ]}'.replace(/\\\"/g, "\""));
    
    let extraData = null;
    let extraIndex = -1;

    if (isNaN(Number(hiddenDimension))) {
      hiddenDimension = hiddenDimension.toString();
    } else {
      hiddenDimension = parseInt(hiddenDimension);
    }

    if (yDimension.indexOf(',') > 0) {
      yDimension = yDimension.split(',').map(item => {
        return isNaN(Number(item)) ? item.trim() : Number(item)
      });
    } else {
      yDimension = isNaN(Number(yDimension)) ? [yDimension] : [Number(yDimension)];
    }

    Boolean(bgColor) ? $(this).css({ backgroundColor: bgColor }) : $(this).css({ backgroundColor: 'transparent' });
    Boolean(borderColor) ? $(this).css({ borderColor: borderColor }) : $(this).css({ borderColor: 'transparent' });
    if (colors.indexOf(',') > -1) {
      colors = colors.split(',').map(item => item.trim())
    } else if (Boolean(colors)) {
      colors = [colors]
    }
    if (shadowColor.indexOf(';') > -1) {
      shadowColor = shadowColor.split(',').map(item => item.trim())
    } else if (Boolean(shadowColor)) {
      shadowColor = [shadowColor]
    }

    const grid = {
      containLabel: containLabel
    };
    if (gridPadding.indexOf(',') > -1) {
      gridPadding = gridPadding.split(',').map(item => item.trim());
      grid.left = gridPadding[0];
      grid.top = gridPadding[1];
      grid.right = gridPadding[2] || gridPadding[0];
      grid.bottom = gridPadding[3] || gridPadding[1];
    } else if (Boolean(gridPadding)) {
      grid.left = gridPadding;
      grid.top = gridPadding;
      grid.right = gridPadding;
      grid.bottom = gridPadding;
    }

    const titlePositionArr = titlePosition.split(',');
    const title = {
      text: titleText,
      left: titlePositionArr[0],
      top: titlePosition.indexOf(',') > 0 ? titlePositionArr[1] : titlePositionArr[0],
      textStyle: {
        fontSize: fontSize ? fontSize + 4 : 16,
        color: titleColor || fontColor
      }
    };

    const legendShow = legendOrient != 'null';
    const legend = {
      show: legendShow,
      type: 'scroll',
      icon: legendIcon,
      itemGap: legendItemGap,
      itemWidth: legendItemWidth,
      itemHeight: legendItemHeight,
      textStyle: {
        fontFamily: legendFontFamily,
        fontSize: legendFontSize || fontSize,
        color: fontColor,
      }
    };
    if (Boolean(legendPosition)) {
      legendPosition.split(',').forEach((item, i) => {
        if (item.indexOf(':') > 0) {
          const key = item.split(':')[0].trim();
          const value = item.split(':')[1].trim();
          legend[`${key}`] = value;
        } else {
          legend[`${i ? 'top' : 'left'}`] = item.trim();
        }
      });
    }
    if (legendShow) {
      legend.orient = legendOrient;
    } else {
      legend.show = false;
    }
    if (legendMap.indexOf(',') > 0) {
      legendMap = legendMap.split(',').map(function(leg) {
        return leg.trim();
      })
      legendMap.unshift('x');
    } else if (Boolean(legendMap)) {
      legendMap = ['x', legendMap];
    }

    const labelShow = labelPosition != 'null'

    const serieTemp = {
      type: 'line',
      symbol: symbol,
      symbolSize: symbolSize,
      stack: stack,
      lineStyle: {
        width: lineWidth,
        shadowOffsetX: shadowOffsetX,
        shadowOffsetY: shadowOffsetY,
        shadowBlur: shadowBlur
      },
      label: {
        show: labelShow,
        color: labelColor,
        distance: labelDistance,
        fontSize: labelFontsize || fontSize,
      },
      encode: {
        x: xDimension,
      }
    };

    if (smooth) {
      serieTemp.smooth = smooth;
    }
    if (connectNulls) {
      serieTemp.connectNulls = connectNulls;
    }
    if (labelShow) {
      serieTemp.label.position = labelPosition
    }

    const xAxis = {
      type: xAxisType,
      name: xAxisName,
      boundaryGap: false,
      scale: xAxisType == 'value',
      nameTextStyle: {
        fontSize: axisNameFontsize
      },
      axisTick: {
        show: xAxisTick,
        lineStyle: {
          width: axisLineWidth,
        }
      },
      axisLine: {
        lineStyle: {
          width: axisLineWidth,
          color: axisColor
        }
      },
      axisLabel: {
        color: fontColor,
        fontFamily: axisLabelFontFamily,
        fontSize: axisLabelFontsize || fontSize,
        rotate: xLabelRotate,
        verticalAlign: 'top'
      },
      splitLine: {
        show: xAxisSplitLine,
        lineStyle: {
          color: axisColor,
          opacity: 0.4
        }
      }
    };
    const yAxis = {
      type: yAxisType,
      name: yAxisName,
      axisTick: {
        show: yAxisTick,
        lineStyle: {
          width: axisLineWidth,
        }
      },
      nameTextStyle: {
        fontSize: axisNameFontsize || fontSize
      },
      axisLine: {
        lineStyle: {
          width: axisLineWidth,
          color: axisColor
        }
      },
      axisLabel: {
        fontFamily: axisLabelFontFamily,
        fontSize: axisLabelFontsize || fontSize,
        color: fontColor,
        align: 'right'
      },
      splitLine: {
        show: yAxisSplitLine,
        lineStyle: {
          color: axisColor,
          opacity: 0.4,
          type: yAxisSplitLineType
        }
      }
    };
    yAxis.axisLabel.formatter = '{value}' + yAxisUnit;

    let _xLabelMap;
    if (xLabelMap.indexOf(':') > 0) {
      _xLabelMap = {};
      let _xLabelArr;
      if (xLabelMap.indexOf(',') > 0) {
        _xLabelArr = xLabelMap.split(',');
      } else {
        _xLabelArr = [xLabelMap]
      }
      _xLabelArr.forEach(function (item) {
        if (item.indexOf(':') > 0) {
          const _item = item.trim().split(':').map(v => v.trim());
          _xLabelMap[_item[0].toString().toLocaleLowerCase()] = _item[1];
        }
      });
      xAxis.axisLabel.formatter = function (name) {
        return _xLabelMap[name.toString().toLocaleLowerCase()] || name
      }
    } else {
      xAxis.axisLabel.formatter = null
    }

    const tooltip = {
      trigger: 'axis',
      textStyle:{
        fontSize:tooltipFontsize || fontSize
      },
      axisPointer: {
        type: 'line',
        lineStyle: {
          color: axisColor,
          opacity: 0.6
        }
      }
    };
    if (_xLabelMap) {
      tooltip.formatter = function (params) {
        if (params.length) {
          const xAxisName = _xLabelMap ? _xLabelMap[params[0].name.toString().toLocaleLowerCase()] || params[0].name : params[0].name;
          const list = params.map(function (item, index) {
            return "<br /><span style='display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:" + item.color + "'></span>" + item.seriesName + ": " + item.data[index+1]
          })
          return xAxisName + list.join(' ')
        }
      }
    }

    const dataZoom = [
      {
        show: showDataZoom,
        // borderColor: fontColor,
        start: zoomStart,
        end: zoomEnd
      }, {
        type: 'inside',
        start: zoomStart,
        end: zoomEnd
      }
    ];
    if (zoomStart < 0 || zoomEnd < 100) {
      dataZoom[1].disabled = true
    } else {
      dataZoom[1].disabled = false
    }

    const self = this;
    const _id = self.getAttribute('id');
    const eventName = `call-${_id}`;
    const myChart = window.echarts.init(self);
    inLoader ? $(self).attr('loader', 'in') : $(self).removeAttr('loader');

    function transferColorToRgba(color, alpha = 1) {
      if (typeof color !== 'string' && !(color instanceof String)) return console.error("请输入16进制字符串形式的颜色值");
      color = color.charAt(0) === '#' ? color.substring(1) : color;
      if (color.length !== 6 && color.length !== 3) return console.error("请输入正确的颜色值")
      if (color.length === 3) {
        color = color.replace(/(\w)(\w)(\w)/, '$1$1$2$2$3$3')
      }
      var reg = /\w{2}/g;
      var colors = color.match(reg);
      for (var i = 0; i < colors.length; i++) {
        colors[i] = parseInt(colors[i], 16).toString();
      }
      return 'rgba(' + colors.join() + ',' + alpha + ')';
    }
    function initChart(source) {
      myChart.clear();
      const series = yDimension.map(function (item, index) {
        const serieLineFinal = JSON.parse(JSON.stringify(serieTemp));
        let colorMap = ['#c23531','#2f4554', '#61a0a8', '#d48265', '#91c7ae','#749f83',  '#ca8622', '#bda29a','#6e7074', '#546570', '#c4ccd3'];
        if (Boolean(colors)) {
          colorMap.splice(0, colors.length);
          colorMap = colors.concat(colorMap);
        }
        const _i = index % colorMap.length;
        if (Boolean(shadowColor)) {
          const s_i = index % shadowColor.length;
          serieLineFinal.lineStyle.shadowColor = shadowColor[s_i];
        }
        if (area === 'gradient') {
          const startColor = transferColorToRgba(colorMap[_i], 0.5)
          const endColor = transferColorToRgba(colorMap[_i], 0)
          serieLineFinal.areaStyle = {
            color: {type: 'line', x: 0, y: 0, x2: 0, y2: 1, colorStops: [{
              offset: 0,
              color: startColor
            }, {
              offset: 1,
              color: endColor
            }]}
          }
        } else if (area === 'color') {
          const currColor = transferColorToRgba(colorMap[_i], 0.3)
          serieLineFinal.areaStyle = {
            color: currColor,
            opacity: 0.8
          }
        }
        serieLineFinal.itemStyle = {color: colorMap[_i]};
        serieLineFinal.encode.y = item;
        serieLineFinal.encode.seriesName = item;
        serieLineFinal.encode.tooltip = item;
        return serieLineFinal
      });

      const option = {
        title: title,
        tooltip: tooltip,
        legend: legend,
        grid: grid,
        xAxis: xAxis,
        yAxis: yAxis,
        dataset: {
          source: source
        },
        dataZoom: dataZoom,
        series: series
      };
      myChart.setOption(option);
      myChart.resize();

      if (window.prevEventType && window.prevEventType[eventName]) {
        myChart.off(window.prevEventType[eventName]);
      }
      if (clickEvent != 'null') {
        myChart.on(clickEvent, function (params) {
          var _data = params.data;
          if (extraIndex > -1 && extraData && extraData.length) {
            _data.splice(extraIndex, 0, extraData[params.dataIndex + 1]);
          }
          if (window.spSocket && clickEvent != 'null') {
            inLoader && window.loader && window.loader.add(_id);
            window.spSocket.send({
              eventName: eventName,
              data: {
                success: true,
                out1: JSON.stringify(_data)
              }
            });
          }
        });
        if (!window.prevEventType) {
          window.prevEventType = {};
        }
        window.prevEventType[eventName] = clickEvent;
      }
    }

    initChart(defaultData);

    window.addEventListener('resize', function () {
      myChart.resize();
    }, false)
    let hasTransfer = false;
    // 有 dashboardHost 说明是运行模式
    if (window.spSocket) {
      inLoader && window.loader && $(self).append($(window.loader.ele));
      window.spSocket.subscribe({
        eventName: eventName,
        callback: function (_data) {
          let _in1Str = _data.data.in1;
          if (_in1Str) {
            const data = JSON.parse(_in1Str);
            let source = data;
            if (hiddenDimension) {
              extraIndex = isNaN(hiddenDimension) ? data[0].indexOf(hiddenDimension) : hiddenDimension;
              if (extraIndex > -1) {
                extraData = [];
                source = data.map(function(row) {
                  extraData.push(row[extraIndex]);
                  row.splice(extraIndex, 1);
                  return row;
                });
              }
            }
            inLoader && window.loader && window.loader.remove(_id);
            if (!hasTransfer || setAllOption) {
              initChart(source);
              hasTransfer = true
            } else {
              myChart.setOption({
                dataset: {
                  source: source
                }
              })
            }
          }
        }
      });
    }

    Boolean(dataSource) && $.get(dataSource, function (ds) {
      myChart.hideLoading();
      initChart(JSON.parse(ds))
    });
  },

  onViewInit() {
    this.updateScript();
    const evn = echartsBasicListen + `
    change:defaultData
    change:xAxisTick
    change:yAxisTick
    change:yAxisSplitLineType
    change:yAxisUnit
    change:xAxisName
    change:xAxisType
    change:yAxisName
    change:xDimension
    change:yDimension
    change:yAxisType
    change:axisNameFontsize
    change:axisLabelFontFamily
    change:axisColor
    change:axisLineWidth
    change:xAxisSplitLine
    change:yAxisSplitLine
    change:axisLabelFontsize
    change:gridPadding
    change:containLabel
    change:labelPosition
    change:labelDistance
    change:labelFontsize
    change:labelFormatter
    change:labelColor
    change:tooltipFontsize
    change:xLabelRotate
    change:smooth
    change:connectNulls
    change:lineWidth
    change:area
    change:symbol
    change:symbolSize
    change:shadowOffsetX
    change:shadowOffsetY
    change:shadowBlur
    change:shadowColor
    change:stack
    change:showDataZoom
    change:zoomStart
    change:zoomEnd
    change:xLabelMap
    change:inLoader
    change:hiddenDimension
    change:setAllOption
    change:clickEvent`;
    this.listenTo(this.model, evn, this.updateScript);
    this.listenTo(this.model, evn, this.em.handleUpdates.bind(this.em));
    this.listenTo(this.em, 'update:component:style:height update:component:style:width', throttle.bind(this, this.updateScript.bind(this)));
  }
}
