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

export default {

  // 组件名称
  name: rectStackBarChart,

  // 前面板html模板
  viewTemplate() {
    return `
      <div data-gjs-type="${rectStackBarChart}" class="${rectStackBarChart}"></div>
    `
  },
  // 前面板html样式
  viewStyle() {
    return `
      <style>
        .${rectStackBarChart} {
          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" xmlns="http://www.w3.org/2000/svg" ><path d="M547.84 128h235.52v619.52h-235.52zM256 419.84h235.52v327.68H256z"></path><path d="M547.84 353.28h235.52v394.24h-235.52zM256 552.96h235.52v199.68H256z" ></path><path d="M547.84 128h235.52v619.52h-235.52zM256 419.84h235.52v327.68H256z" fill="#bcc9d4" ></path><path d="M547.84 353.28h235.52v394.24h-235.52zM256 552.96h235.52v199.68H256z"></path><path d="M73.216 828.416h870.4v58.88h-870.4z" fill="#1890ff"></path></svg>
        <div class="gjs-block-label">方块堆叠<br>柱图</div>
      `,
    };
  },

  // 后面板显示属性配置
  spOptions() {
    return {
      label: '方块堆叠柱图',
      icon: 'globe',
      inPorts: [{
        uuid: 'in1',
        subType: 'json',
        description: {
          zh_CN: '输入1'
        }
      }],
      outPorts: [{
        uuid: 'out1',
        subType: 'json',
        description: {
          zh_CN: '输出1'
        }
      }]
    }
  },

  // 组件属性
  componentOptions() {
    return {
      name: rectStackBarChart,
      resizable: true,
      dmode: 'absolute',
      droppable: false,
      traits: [
        {
          name: 'gridPadding',
          label: '容器边距(左,上,右,下)',
          changeProp: 1
        }, {
          name: 'containLabel',
          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',
        }, {
          name: 'labelFontsize',
          label: '标签字号',
          changeProp: 1,
          type: 'number',
          min: 9,
        }, {
          name: 'labelFontFamily',
          label: '标签字体',
          changeProp: 1,
          type: 'select',
          options: [
            { id: 'sans-serif', name: '默认' },
            { id: '庞门正道', name: '庞门正道' },
            { id: 'DS-Digital', name: 'DS-Digital' }
          ]
        }, {
          name: 'labelColor',
          label: '标签颜色',
          changeProp: 1,
          type: 'color',
        }, {
          name: 'labelUnit',
          label: '标签单位',
          changeProp: 1,
        }, {
          name: 'barWidth',
          label: '柱宽',
          changeProp: 1,
          type: "number"
        }, {
          name: 'symbolType',
          label: '图形类型',
          changeProp: 1,
          type: "select",
          options: [
            {id: 'customer', 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: 'symbol',
          label: '自定义图形',
          changeProp: 1,
          type: "imageSelector"
        }, {
          name: 'symbolSize',
          label: '图形大小',
          changeProp: 1
        }, {
          name: 'symbolRotate',
          label: '图形角度',
          changeProp: 1,
          type: 'number'
        }, {
          name: 'symbolRepeat',
          label: '图形重复',
          changeProp: 1,
          type: 'checkbox'
        }, {
          name: 'symbolClip',
          label: '图形剪裁',
          changeProp: 1,
          type: 'checkbox'
        }, {
          name: 'symbolMargin',
          label: '图形间隔',
          changeProp: 1,
          type: 'number'
        }, {
          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: 'xAxisType',
          label: 'X轴类型',
          changeProp: 1,
          type: 'select',
          options: [{id: 'category', name: '类目轴'}, {id: 'value', name: '数值轴'}, {id: 'time', name: '时间轴'}]
        }, {
          name: 'yAxisType',
          label: 'Y轴类型',
          changeProp: 1,
          type: 'select',
          options: [{id: 'category', name: '类目轴'}, {id: 'value', name: '数值轴'}, {id: 'time', name: '时间轴'}]
        }, {
          name: 'xAxisName',
          label: 'x轴名称',
          changeProp: 1
        }, {
          name: 'xAxisNameLocation',
          label: 'x轴名称位置',
          changeProp: 1,
          type: 'select',
          options: [{id: 'start', name: '开始'}, {id: 'center', name: '中间'}, {id: 'end', name: '末尾'}]
        }, {
          name: 'yAxisName',
          label: 'y轴名称',
          changeProp: 1
        }, {
          name: 'yAxisNameLocation',
          label: 'y轴名称位置',
          changeProp: 1,
          type: 'select',
          options: [{id: 'start', name: '开始'}, {id: 'middle', name: '中间'}, {id: 'end', name: '末尾'}]
        }, {
          name: 'axisNameFontSize',
          label: '轴名称字号',
          changeProp: 1,
          type: 'number',
          min: 10,
          step: 1
        }, {
          name: 'xAxisLine',
          label: 'X轴轴线',
          changeProp: 1,
          type: 'checkbox'
        }, {
          name: 'yAxisLine',
          label: 'Y轴轴线',
          changeProp: 1,
          type: 'checkbox'
        }, {
          name: 'axisColor',
          label: '坐标轴颜色',
          changeProp: 1,
          type: 'color'
        }, {
          name: 'axisLineWidth',
          label: '坐标轴线宽',
          changeProp: 1,
          type: 'number',
          min: 1,
          step: 1
        }, {
          name: 'xAxisTick',
          label: 'X轴刻度线',
          changeProp: 1,
          type: 'checkbox'
        }, {
          name: 'yAxisTick',
          label: 'Y轴刻度线',
          changeProp: 1,
          type: 'checkbox'
        }, {
          name: 'axisTickLength',
          label: '刻度线长度',
          changeProp: 1,
          type: 'number',
          min: 1,
          step: 1
        }, {
          name: 'xAxisLabel',
          label: 'X轴刻度值',
          changeProp: 1,
          type: 'checkbox'
        }, {
          name: 'yAxisLabel',
          label: 'Y轴刻度值',
          changeProp: 1,
          type: 'checkbox'
        }, {
          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: 'yAxisLabelAlign',
          label: 'y轴刻度值对齐',
          changeProp: 1,
          type: 'select',
          options: [{id: 'right', name: '右对齐'}, {id: 'left', name: '左对齐'}, {id: 'center', name: '居中对齐'}]
        }, {
          name: 'xAxisSplitLine',
          label: 'X轴分割线',
          changeProp: 1,
          type: 'checkbox'
        }, {
          name: 'yAxisSplitLine',
          label: 'Y轴分割线',
          changeProp: 1,
          type: 'checkbox'
        }, {
          name: 'axisSplitLineColor',
          label: '分割线颜色',
          changeProp: 1,
          type: 'color'
        }, {
          name: 'yAxisInverse',
          label: 'Y轴反向',
          changeProp: 1,
          type: 'checkbox'
        }, {
          name: 'axisSplitLineType',
          label: '分割线类型',
          changeProp: 1,
          type: 'select',
          options: [{ id: 'solid', name: '实线' },{id:'dashed', name:'虚线'},{id:'dotted', name:'点线'}]
        }, {
          name: 'yAxisOffset',
          label: 'Y轴偏移',
          changeProp: 1,
          type: 'number'
        }, {
          name: 'pointerType',
          label: 'Tooltip指示器类型',
          changeProp: 1,
          type: 'select',
          options: [{id: 'line', name: '直线'}, {id: 'shadow', name: '阴影'}, {id: 'cross', name: ' 十字准星'}, {id: 'none', name: '无'}]
        }, {
          name: 'pointerColor',
          label: '指示器颜色',
          changeProp: 1,
          type: 'color'
        }, {
          name: 'showBarBg',
          label: '柱形背景',
          changeProp: 1,
          type: 'checkbox'
        }, {
          name: 'barBgColor',
          label: '柱形背景颜色',
          changeProp: 1,
          type: 'color'
        }, {
          name: 'csv',
          label: '示例数据',
          changeProp: 1,
          type: 'csvDownload',
          preFileName: '方块堆叠柱图',
          datas: [["name", "DEMO"], ["one", 1], ["two", 2], ["three", 3], ["four", 4], ["five", 5]]
        }, 
        {
          name: 'initLoader',
          label: '初始Loading',
          changeProp: 1,
          type: 'checkbox'
        },
        {
          name: 'defaultData',
          changeProp: 1,
          type: 'hide'
        }
      ],
      defaultData:JSON.stringify([["name", "DEMO"], ["one", 1], ["two", 2], ["three", 3], ["four", 4], ["five", 5]]).replace(/\"/g, "\\\""),
      'gridPadding': '10%,60,10%,60',
      'containLabel': true,
      'xAxisType': 'category',
      'yAxisType': 'value',
      'xAxisName': null,
      'xAxisNameLocation': 'end',
      'yAxisName': null,
      'yAxisNameLocation': 'end',
      'xAxisLine': true,
      'xAxisSplitLine': false,
      'xAxisTick': true,
      'xAxisLabel': true,
      'yAxisLine': true,
      'yAxisSplitLine': true,
      'yAxisTick': true,
      'yAxisLabel': true,
      'yAxisInverse': false,
      'yAxisOffset': 0,
      'yAxisLabelAlign': 'right',
      'axisColor': '#333333',
      'axisSplitLineColor': '#333333',
      'axisSplitLineType': 'solid',
      'axisLabelFontsize': 12,
      'axisLabelFontFamily': 'sans-serif',
      'labelPosition': 'null',
      'labelDistance': 5,
      'labelFontFamily': "sans-serif",
      'labelFontsize': 12,
      'labelColor': '#333333',
      'barWidth': null,
      'symbolType': 'rect',
      'symbol': '/oss_public/studio/shanglu/dashboard/assets/1585114968662_bar-primary.png',
      'symbolSize': '20%, 10%',
      'symbolRotate': 0,
      'symbolRepeat': true,
      'symbolMargin': 2,
      'zoomStart': -1,
      'zoomEnd': 100,
      'axisType': false,
      'pointerType': 'line',
      'pointerColor': 'rgba(255,255,255,1)',
      'clickEvent': 'null',
      'axisNameFontSize': 12,
      'axisLineWidth': 1,
      'axisTickLength': 5,
      'showBarBg': true,
      'barBgColor': '#ccc',
      'symbolClip': true,
      'labelUnit': '',
      'initLoader': false,
    }
  },

  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 legendItemGap = Number('{[ legendItemGap ]}');
    const legendItemWidth = Number('{[ legendItemWidth ]}');
    const legendItemHeight = Number('{[ legendItemHeight ]}');
    const legendFontSize = Number('{[ legendFontSize ]}');
    const legendFontFamily = ('{[ legendFontFamily ]}').toString();
    const labelPosition = ('{[ labelPosition ]}').toString();
    const labelFontFamily = ('{[ labelFontFamily ]}').toString();
    const labelFontsize = Number('{[ labelFontsize ]}');
    const labelDistance = Boolean('{[ labelDistance ]}') ? Number('{[ labelDistance ]}') : 0;
    const labelColor = '{[ labelColor ]}';
    const titleText = '{[ titleText ]}';
    const titleColor = '{[ titleColor ]}';
    const titlePosition = ('{[ titlePosition ]}').toString();
    const xAxisType = '{[ xAxisType ]}';
    const yAxisType = '{[ yAxisType ]}';
    const xAxisName = '{[ xAxisName ]}';
    const xAxisNameLocation = '{[ xAxisNameLocation ]}';
    const yAxisName = '{[ yAxisName ]}';
    const yAxisNameLocation = '{[ yAxisNameLocation ]}';
    const axisColor = '{[ axisColor ]}';
    const xAxisLine = Boolean('{[ xAxisLine ]}');
    const xAxisSplitLine = Boolean('{[ xAxisSplitLine ]}');
    const xAxisTick = Boolean('{[ xAxisTick ]}');
    const xAxisLabel = Boolean('{[ xAxisLabel ]}');
    const yAxisLine = Boolean('{[ yAxisLine ]}');
    const yAxisSplitLine = Boolean('{[ yAxisSplitLine ]}');
    const yAxisTick = Boolean('{[ yAxisTick ]}');
    const yAxisLabel = Boolean('{[ yAxisLabel ]}');
    const yAxisInverse = Boolean('{[ yAxisInverse ]}');
    const yAxisOffset = Boolean('{[ yAxisOffset ]}') ? parseInt('{[ yAxisOffset ]}') : 0;
    const yAxisLabelAlign = '{[ yAxisLabelAlign ]}';
    const axisSplitLineColor = '{[ axisSplitLineColor ]}';
    const axisSplitLineType = ('{[ axisSplitLineType ]}').toString();
    const axisLabelFontsize = Number('{[ axisLabelFontsize ]}');
    const axisLabelFontFamily = ('{[ axisLabelFontFamily ]}').toString();
    let gridPadding = '{[ gridPadding ]}';
    const symbolType = '{[ symbolType ]}';
    const symbolSize = '{[ symbolSize ]}';
    const symbol = '{[ symbol ]}';
    const barWidth = '{[ barWidth ]}';
    const symbolRotate = '{[ symbolRotate ]}';
    const symbolRepeat = Boolean('{[ symbolRepeat ]}');
    const symbolMargin = Boolean('{[ symbolMargin ]}') ? parseInt('{[ symbolMargin ]}') : 0;
    const axisNameFontSize = Boolean('{[ axisNameFontSize ]}') ? parseInt('{[ axisNameFontSize ]}') : 0;
    const axisLineWidth = Boolean('{[ axisLineWidth ]}') ? parseInt('{[ axisLineWidth ]}') : 0;
    const axisTickLength = Boolean('{[ axisTickLength ]}') ? parseInt('{[ axisTickLength ]}') : 0;
    const containLabel = Boolean('{[ containLabel ]}');
    const legendMap = ('{[ legendMap ]}').toString();
    const pointerType = ('{[ pointerType ]}').toString();
    const pointerColor = '{[ pointerColor ]}'
    const clickEvent = ('{[ clickEvent ]}').toString();
    const showBarBg = Boolean('{[ showBarBg ]}');
    const barBgColor = Boolean('{[ barBgColor ]}') ? ('{[ barBgColor ]}').toString() : '#ccc';
    const symbolClip = Boolean('{[ symbolClip ]}');
    const defaultData = JSON.parse('{[ defaultData ]}'.replace(/\\\"/g, "\""));
    const defaultDataFormat = [];
    const labelUnit = ('{[ labelUnit ]}').toString();
    const initLoader = Boolean('{[ initLoader ]}');

    defaultData.forEach((el,i) => {
      let newEl = [];
      if(i === 0) {
        newEl = el;
      } else {
        el.forEach((element, index) => {
          let newElement = element;
          if(index !== 0 && Number(element) !== NaN) {
            newElement = Number(element)
          }
          newEl.push(newElement);
        })
      }
      defaultDataFormat.push(newEl);
    })

    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]
    }

    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',
      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;
    }

    let _legendMap;
    if (legendMap.indexOf(':') > 0) {
      _legendMap = {};
      let _legendArr;
      if (legendMap.indexOf(',') > 0) {
        _legendArr = legendMap.split(',');
      } else {
        _legendArr = [legendMap]
      }
      _legendArr.forEach(function (item) {
        if (item.indexOf(':') > 0) {
          const _item = item.trim().split(':').map(v => v.trim());
          _legendMap[_item[0].toString().toLocaleLowerCase()] = _item[1];
        }
      });
      legend.formatter = function (name) {
        return _legendMap[name.toString().toLocaleLowerCase()] || name
      }
    } else {
      legend.formatter = null
    }

    const labelShow = labelPosition != 'null'
    const serieTemp = {
      type: 'pictorialBar',
      label: {
        show: labelShow,
        color: labelColor,
        distance: labelDistance,
        fontSize: labelFontsize,
        fontFamily: labelFontFamily
      },
      barWidth: barWidth,
      symbol: symbolType === 'customer' ? "image://" + symbol : symbolType,
      symbolSize: symbolSize.split(','),
      symbolRotate: symbolRotate,
      symbolRepeat: symbolRepeat,
      symbolMargin: symbolMargin,
      symbolClip: symbolClip,
      silent: true,
      legendHoverLink: false,
      z: 10,
    };
    if (labelShow) {
      serieTemp.label.position = labelPosition
    }

    const xAxis = {
      type: xAxisType,
      name: xAxisName,
      nameLocation: xAxisNameLocation,
      axisLine: {
        show: xAxisLine,
        lineStyle: {
          width: axisLineWidth,
          color: axisColor
        }
      },
      axisTick: {
        show: xAxisTick,
        length: axisTickLength,
        lineStyle: {
          width: axisLineWidth
        }
      },
      axisLabel: {
        show: xAxisLabel,
        fontFamily: axisLabelFontFamily,
        fontSize: axisLabelFontsize || fontSize,
        color: fontColor
      },
      splitLine: {
        show: xAxisSplitLine,
        lineStyle: {
          color: axisSplitLineColor,
          type: axisSplitLineType
        }
      }
    };
    if (Boolean(xAxisName)) {
      xAxis.nameTextStyle = {
        fontSize: axisNameFontSize || fontSize,
        color: fontColor
      }
    }
    const yAxis = {
      type: yAxisType,
      name: yAxisName,
      nameLocation: yAxisNameLocation,
      inverse: yAxisInverse,
      offset: yAxisOffset,
      axisLine: {
        show: yAxisLine,
        lineStyle: {
          width: axisLineWidth,
          color: axisColor
        }
      },
      axisTick: {
        show: yAxisTick,
        length: axisTickLength,
        lineStyle: {
          width: axisLineWidth
        }
      },
      axisLabel: {
        show: yAxisLabel,
        align: yAxisLabelAlign,
        fontFamily: axisLabelFontFamily,
        fontSize: axisLabelFontsize || fontSize,
        color: fontColor
      },
      splitLine: {
        show: yAxisSplitLine,
        lineStyle: {
          color: axisSplitLineColor,
          type: axisSplitLineType
        }
      }
    };
    if (Boolean(yAxisName)) {
      yAxis.nameTextStyle = {
        fontSize: axisNameFontSize || fontSize,
        color: fontColor
      }
    }

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

    const self = this;
    const eventName = `call-` + self.getAttribute('id');
    //const defaultSource = [["name", "DEMO", "DEMO2"], ["one", 3, 7], ["two", 10, 3], ["three", 3, 4], ["four", 4, 5], ["five", 5, 6]]
    const myChart = window.echarts.init(this);

    function getStackData(source) {
      source.map(function (item, index) {
        if (index !== 0) {
          item.map(function(val, index) {
            if (index > 0 && index < item.length) {
              for (let j = index + 1; j < item.length; j++) {
                item[index] += item[j];
              }
            }
          });
        }
      });
    }

    function getTooltipFormatter(source) {
      Object.assign(tooltip, {
        formatter: function(params) {
          let tooltip = "<p>" + params[0].name + "</p>";
          params.map(function(val, index) {
            const { marker, dataIndex, seriesName } = val;
            if(seriesName === "_background") return '';
            const seriesNameFormat = _legendMap ? _legendMap[seriesName.toString().toLocaleLowerCase()] || seriesName : seriesName;
            tooltip += "<p>" + marker + seriesNameFormat + ": " + source[dataIndex + 1][index + 1] + "</p>";
          });
          return tooltip;
        }
      });
    }

    const bgSerie = {
      type: 'pictorialBar',
      name: '_background',
      symbol: symbolType === 'customer' ? "image://" + symbol : symbolType,
      symbolSize: symbolSize.split(','),
      symbolRotate: symbolRotate,
      symbolRepeat: 'fixed',
      symbolMargin: symbolMargin,
      silent: true,
      legendHoverLink: false,
      animationDuration: 0,
      barGap: '-100%',
      itemStyle: {
        color: barBgColor
      }
    }

    function initChart(source) {
      myChart.clear();
      let series = source[0].slice(1).map(function (item, index) {
        return serieTemp
      });

      const orginSource = JSON.parse(JSON.stringify(source));
      getTooltipFormatter(orginSource);
      series.forEach(serie => {
        serie.label.formatter = function(params) {
          const { dataIndex, seriesIndex, value } = params;
          let label = orginSource[dataIndex+1][seriesIndex+1];
          return `${label}${labelUnit}`
        }
      })

      if(showBarBg) {
        series.push(bgSerie);
      }

      legend.data = source[0].slice(1); // 解决设置背景时，legend显示背景的图例

      getStackData(source);
      const option = {
        title: title,
        tooltip: tooltip,
        legend: legend,
        grid: grid,
        xAxis: xAxis,
        yAxis: yAxis,
        dataset: {
          source: source
        },
        series: series
      };
      if (Boolean(colors)) option.color = colors;

      myChart.setOption(option);
      myChart.resize();

      myChart.on('legendselectchanged', function(params) {
        const { selected } = params;
        let data = JSON.parse(JSON.stringify(orginSource));
        source[0].map(function(value, index) {
          if (index !== 0 && !selected[value]) {
            data.map(function(val) {
              val.splice(index, 1);
            });
          }
        });
        const tooltipData = JSON.parse(JSON.stringify(data));
        getTooltipFormatter(tooltipData);
        getStackData(data);
        myChart.setOption({
          dataset: {
            source: data
          },
          tooltip,
          series: data[0].slice(1).map(function () { return serieTemp })
        });
      });

      if (window.prevEventType && window.prevEventType[eventName]) {
        myChart.off(window.prevEventType[eventName]);
      }
      if (clickEvent != 'null') {
        myChart.on(clickEvent, function (params) {
          var _data = params.data;
          if (window.spSocket && clickEvent != 'null') {
            window.spSocket.send({
              eventName: eventName,
              data: {
                success: true,
                out1: JSON.stringify(_data)
              }
            });
          }
        });
        if (!window.prevEventType) {
          window.prevEventType = {};
        }
        window.prevEventType[eventName] = clickEvent;
      }
    }

    initChart(defaultDataFormat);

    const loader = $('<div class="loader"><span class="dot"></span><span class="dot"></span><span class="dot"></span><span class="dot"></span><span class="dot"></span></div>')

    window.addEventListener('resize', function () {
      myChart.resize();
    }, false)
    let hasTransfer = false;
    // 有 dashboardHost 说明是运行模式
    if (window.spSocket) {
      if(initLoader){
        $(self).append(loader);
      }

      window.spSocket.subscribe({
        eventName: eventName,
        callback: function (_data) {
          let _in1Str = _data.data.in1;
          if (_in1Str) {
            const source = JSON.parse(_in1Str);
            $(self).children('.loader').remove();
            if (!hasTransfer) {
              initChart(source);
              hasTransfer = true
            } else {
              myChart.setOption({
                dataset: {
                  source: source
                },
                series: source[0].slice(1).map(function () { return serieTemp })
              })
            }
          }
        }
      });
    }

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

  onViewInit() {
    this.updateScript();
    const evn = echartsBasicListen + `
    change:showBarBg
    change:labelUnit
    change:initLoader
    change:symbolClip
    change:barBgColor
    change:defaultData
    change:xAxisType
    change:yAxisType
    change:xAxisName
    change:xAxisNameLocation
    change:yAxisName
    change:yAxisNameLocation
    change:axisColor
    change:xAxisLine
    change:xAxisSplitLine
    change:xAxisTick
    change:xAxisLabel
    change:yAxisLine
    change:yAxisSplitLine
    change:yAxisTick
    change:yAxisLabel
    change:yAxisInverse
    change:yAxisLabelAlign
    change:axisSplitLineColor
    change:axisSplitLineType
    change:axisLabelFontFamily
    change:axisLabelFontsize
    change:yAxisOffset
    change:gridPadding
    change:containLabel
    change:labelPosition
    change:labelDistance
    change:labelFontsize
    change:labelFontFamily
    change:labelFormatter
    change:labelColor
    change:symbolType
    change:symbol
    change:symbolSize
    change:symbolRotate
    change:symbolRepeat
    change:symbolMargin
    change:pointerType
    change:pointerColor
    change:clickEvent
    change:axisTickLength
    change:axisLineWidth
    change:axisNameFontSize
    `;
    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)));
  }
}