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


  // 组件名称
  name: barLineChart,

  // 前面板html模板
  viewTemplate() {
    return `
      <div data-gjs-type="${barLineChart}" class="${barLineChart}"></div>
    `
  },
  // 前面板html样式
  viewStyle() {
    return `
      <style>
        .${barLineChart} {
          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="M0 960h1024v64H0z" ></path><path d="M96 640h64v352H96zM352 384h64v608h-64zM608 544h64v448h-64zM864 128h64v864h-64z" ></path><path d="M896 192a96 96 0 1 1 96-96 96 96 0 0 1-96 96z m0-128a32 32 0 1 0 32 32 32 32 0 0 0-32-32zM640 608a96 96 0 1 1 96-96 96 96 0 0 1-96 96z m0-128a32 32 0 1 0 32 32 32 32 0 0 0-32-32zM384 448a96 96 0 1 1 96-96 96 96 0 0 1-96 96z m0-128a32 32 0 1 0 32 32 32 32 0 0 0-32-32zM128 704a96 96 0 1 1 96-96 96 96 0 0 1-96 96z m0-128a32 32 0 1 0 32 32 32 32 0 0 0-32-32z" ></path><path d="M137.536 553.28l192.128-192.096 45.248 45.28-192.128 192.096zM441.76 425.76l33.92-54.304 106.368 66.496-33.92 54.272zM650.304 434.24l181.408-294.528 54.496 33.6-181.44 294.528z" ></path></svg>
        <div class="gjs-block-label">柱线图</div>
      `,
    };
  },

  // 后面板显示属性配置
  spOptions() {
    return {
      label: '柱线图',
      icon: 'globe',
      docUrl: 'https://xuelangyun.yuque.com/docs/share/77e11be2-36e3-4cd9-be2a-cbe836ad17a2?# 《柱线图》',
      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: barLineChart,
      resizable: true,
      dmode: 'absolute',
      droppable: false,
      traits: [
        {
          name: 'gridPadding',
          label: '容器边距(左,上,右,下)',
          changeProp: 1
        }, {
          name: 'containLabel',
          label: '包含刻度标签',
          changeProp: 1,
          type: 'checkbox'
        }, {
          name: 'xAxisName',
          label: 'X轴名称',
          changeProp: 1
        }, {
          name: 'yAxisName',
          label: 'Y轴名称',
          changeProp: 1
        }, {
          name: 'axisNameFontsize',
          label: '轴名称字号',
          changeProp: 1,
          type: 'number',
          min: 9,
          step: 1
        }, {
          name: 'show',
          label: '双Y轴',
          changeProp: 1,
          type: 'checkbox'
        },{
          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: 'xAxisSplitLine',
          label: 'X轴分割线',
          changeProp: 1,
          type: 'checkbox'
        }, {
          name: 'yAxisSplitLine',
          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: 'axisSplitLineColor',
          label: '分割线颜色',
          changeProp: 1,
          type: 'color'
        }, {
          name: 'xAxisTick',
          label: 'X轴刻度线',
          changeProp: 1,
          type: 'checkbox'
        }, {
          name: 'yAxisTick',
          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: 'xLabelRotate',
          label: 'X轴标签旋转',
          changeProp: 1,
          type: 'number'
        }, {
          name: 'xAxisDataIndex',
          label: 'X轴数据索引',
          changeProp: 1,
          type: 'number',
          min: 0,
          step: 1
        },{
          name: 'barDataIndex',
          label: '柱形数据索引',
          changeProp: 1,
        }, {
          name: 'lineDataIndex',
          label: '线形数据索引',
          changeProp: 1,
        },{
          name: 'barYAxisIndex',
          label: '柱形图Y轴映射',
          changeProp: 1,
          type: 'number',
          min: 0,
          max: 1
        }, {
          name: 'borderRadius',
          label: '柱形圆角',
          changeProp: 1
        }, {
          name: 'barWidth',
          label: '柱宽',
          changeProp: 1,
          type: 'number'
        }, {
          name: 'barGap',
          label: '柱间距(%)',
          changeProp: 1,
          type: 'number'
        }, {
          name: 'gradient',
          label: '柱形渐变',
          changeProp: 1,
          type: 'select',
          options: [{ id: 'none', name: '无' }, { id: 'line::0-0-0-1', name: '↓' }, { id: 'line::0-1-0-0', name: '↑' }, { id: 'line::0-0-1-0', name: '→' }, { id: 'line::1-0-0-0', name: '←' }, { id: 'line::0-0-1-1', name: '↘' }, { id: 'line::1-0-0-1', name: '↙' }, { id: 'line::0-1-1-0', name: '↗' }, { id: 'line::1-1-0-0', name: '↖' }]
        }, {
          name: 'gradientColors',
          label: '渐变颜色',
          changeProp: 1,
        }, {
          name: 'smooth',
          label: '线平滑',
          changeProp: 1,
          type: 'checkbox'
        }, {
          name: 'lineWidth',
          label: '线宽',
          changeProp: 1,
          type: 'number'
        }, {
          name: 'lineOpacity',
          label: '线透明度',
          changeProp: 1,
          type: 'number',
          min: 0,
          max: 1,
          step: 0.1
        }, {
          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: 'areaFill',
          label: '区域填充',
          changeProp: 1,
          type: 'select',
          options: [{id: 'null', name: '无填充'}, {id: 'gradient', name: '渐变填充'}, {id: 'color', name: '纯色填充'}]
        }, {
          name: 'labelPositionBar',
          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: 'labelColorBar',
          label: '柱标签颜色',
          changeProp: 1,
          type: 'color',
        }, {
          name: 'labelPositionLine',
          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: 'labelColorLine',
          label: '线标签颜色',
          changeProp: 1,
          type: 'color',
        }, {
          name: 'labelDistance',
          label: '标签边距',
          changeProp: 1,
          type: 'number',
          min: 5,
        }, {
          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: 'stack',
          label: '数据堆叠',
          changeProp: 1,
          type: 'select',
          options: [{id: 'null', name: '无堆叠'}, {id: 'bar', name: '柱形堆叠'}, {id: 'line', name: '线形堆叠'}, {id: 'all', name: '全部堆叠'}]
        }, {
          name: 'zoomStart',
          label: '放大镜开始(%)',
          changeProp: 1,
          type: 'number'
        }, {
          name: 'zoomEnd',
          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: 'csv',
          label: '示例数据',
          changeProp: 1,
          type: 'csvDownload',
          preFileName: '柱线图',
          datas: [["name", "A", "B", "C"], ["one", 1, 4, 3], ["two", 2, 3, 1], ["three", 3, 1, 5], ["four", 4, 5, 9], ["five", 5, 2, 6]]
        }, {
          name: 'defaultData',
          changeProp: 1,
          type: 'hide'
        }
      ],
      defaultData:JSON.stringify([
        ["name", "A", "B", "C"], 
        ["one", 1, 4, 5], 
        ["two", 2, 3, 5], 
        ["three", 3, 1, 4], 
        ["four", 4, 5, 9], 
        ["five", 5, 2, 7]
      ]).replace(/\"/g, "\\\""),
      'xAxisName': null,
      'yAxisName': null,
      'axisNameFontsize': 12,
      'show': false,
      'barYAxisIndex':'0',
      'yAxisUnit': null,
      'axisColor': '#333333',
      'axisLineWidth': 1,
      'axisSplitLineColor': '#333333',
      'axisLabelFontsize': 12,
      'axisLabelFontFamily': 'sans-serif',
      'labelFontFamily': 'sans-serif',
      'xAxisSplitLine': false,
      'xAxisTick': true,
      'yAxisSplitLine': true,
      'yAxisTick': true,
      'yAxisSplitLineType': 'dashed',
      'xAxisDataIndex': 0,
      'barDataIndex': '1,2',
      'lineDataIndex': '3',
      'gridPadding': '10%,60,10%,60',
      'containLabel': true,
      'borderRadius': '0',
      'xLabelRotate': null,
      'barWidth': null,
      'barGap': '30',
      'smooth': false,
      'lineWidth': 1,
      'lineOpacity': 1,
      'symbol': 'emptyCircle',
      'symbolSize': 4,
      'areaFill': 'null',
      'gradient': 'none',
      'gradientColors': '#59B5FF|#2263BD::#FF9793|#E7504C::#AE60FA|#6D32C1::#EFCE49|#D79C12::#FFB058|#C56625::#4ACC88|#27A657::#2C989E|#27BCC9::#8A98FF|#2B36A8',
      'stack': 'null',
      'labelPositionBar': 'null',
      'labelPositionLine': 'null',
      'labelDistance': 5,
      'labelFontsize': 12,
      'labelColorBar': '#333333',
      'labelColorLine': '#333333',
      'zoomStart': -1,
      'zoomEnd': 100,
      '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 titleText = '{[ titleText ]}';
    const titleColor = '{[ titleColor ]}';
    const titlePosition = ('{[ titlePosition ]}').toString();
    const labelPositionBar = ('{[ labelPositionBar ]}').toString();
    const labelPositionLine = ('{[ labelPositionLine ]}').toString();
    const labelFontsize = Number('{[ labelFontsize ]}');
    const labelDistance = Number('{[ labelDistance ]}');
    const labelColorBar = '{[ labelColorBar ]}';
    const labelColorLine = '{[ labelColorLine ]}';
    const labelFontFamily = ('{[ labelFontFamily ]}').toString();
    const xAxisName = '{[ xAxisName ]}';
    let yAxisName = ('{[ yAxisName ]}').toString();
    const axisNameFontsize = Number('{[ axisNameFontsize ]}');
    const show = Boolean('{[ show ]}');
    let yAxisUnit = ('{[ yAxisUnit ]}').toString();
    const axisColor = '{[ axisColor ]}';
    const axisLineWidth = Number('{[ axisLineWidth ]}');
    const axisSplitLineColor = '{[ axisSplitLineColor ]}';
    const xAxisSplitLine = Boolean('{[ xAxisSplitLine ]}');
    const xAxisTick = Boolean('{[ xAxisTick ]}');
    const yAxisSplitLine = Boolean('{[ yAxisSplitLine ]}');
    const yAxisTick = Boolean('{[ yAxisTick ]}');
    const yAxisSplitLineType = ('{[ yAxisSplitLineType ]}').toString();
    const axisLabelFontsize = Number('{[ axisLabelFontsize ]}');
    const axisLabelFontFamily = ('{[ axisLabelFontFamily ]}').toString();
    let barDataIndex = '{[ barDataIndex ]}'.toString();
    let lineDataIndex = '{[ lineDataIndex ]}'.toString();
    const xAxisDataIndex = Boolean('{[ xAxisDataIndex ]}') ? Number('{[ xAxisDataIndex ]}') : 0;
    const barYAxisIndex = Boolean('{[ barYAxisIndex ]}') ? Number('{[ barYAxisIndex ]}') : 0;
    const lineOpacity = Boolean('{[ lineOpacity ]}') ? Number('{[ lineOpacity ]}') : 0;
    let gridPadding = '{[ gridPadding ]}';
    let borderRadius = '{[ borderRadius ]}';
    const xLabelRotate = '{[ xLabelRotate ]}';
    const barWidth = '{[ barWidth ]}';
    const barGap = ('{[ barGap ]}').toString() + '%';
    const smooth = Boolean('{[ smooth ]}');
    const lineWidth = Number('{[ lineWidth ]}');
    const symbol = ('{[ symbol ]}').toString();
    const symbolSize = Number('{[ symbolSize ]}');
    const areaFill = ('{[ areaFill ]}').toString();
    const gradient = ('{[ gradient ]}').toString();
    let gradientColors = '{[ gradientColors ]}';
    const containLabel = Boolean('{[ containLabel ]}');
    const stack = ('{[ stack ]}').toString();
    const zoomStart = Number('{[ zoomStart ]}');
    const zoomEnd = Number('{[ zoomEnd ]}');
    const legendMap = ('{[ legendMap ]}').toString();
    const clickEvent = ('{[ clickEvent ]}').toString();
    const defaultData = JSON.parse('{[ defaultData ]}'.replace(/\\\"/g, "\""));

    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 (borderRadius.indexOf(',') > -1) {
      borderRadius = borderRadius.split(',').map(item => parseInt(item.trim()))
    } else if (Boolean(borderRadius)) {
      borderRadius = Number(borderRadius)
    }

    barDataIndex = barDataIndex.split(',').map(item => {
      const itemTrim = item.trim()
      return parseInt(itemTrim, 10)
    })

    lineDataIndex = lineDataIndex.split(',').map(item => {
      const itemTrim = item.trim()
      return parseInt(itemTrim, 10)
    })

    if (yAxisName.indexOf(',') > -1) {
      yAxisName = yAxisName.split(',').map(item => item.trim())
    } else if (Boolean(yAxisName)) {
      yAxisName = [yAxisName]
    }

    if (gradientColors.indexOf('::') > 0) {
      gradientColors = gradientColors.split('::').map(function(item) {
        if (item.indexOf('|') > 0) {
          const itemColor = item.split('|');
          const len = itemColor.length - 1;
          return itemColor.map(function(stepColor, index) {
            return {
              offset: index / len,
              color: stepColor.trim()
            }
          })
        }
      });
    } else if (gradientColors.indexOf('|') > 0) {
      const itemColor = gradientColors.split('|');
      const len = itemColor.length - 1;
      const _colors = itemColor.map(function(stepColor, index) {
        return {
          offset: index / len,
          color: stepColor.trim()
        }
      });
      gradientColors = [_colors];
    } else {
      gradientColors = null;
    }

    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 (legendIcon != 'none') {
      legend.icon = legendIcon;
    }
    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 labelBarShow = labelPositionBar != 'null'
    const labelLineShow = labelPositionLine != 'null'
    const serieBar = {
      type: 'bar',
      yAxisIndex: barYAxisIndex,
      itemStyle: {
        barBorderRadius: borderRadius
      },
      label: {
        show: labelBarShow,
        color: labelColorBar,
        distance: labelDistance,
        fontSize: labelFontsize,
        fontFamily: labelFontFamily,
      },
      barWidth: barWidth,
      barGap: barGap,
      encode: {
        x: xAxisDataIndex
      }
    };
    if (labelBarShow) {
      serieBar.label.position = labelPositionBar
    }
    const serieLine = {
      type: 'line',
      symbol: symbol,
      symbolSize: symbolSize,
      yAxisIndex: barYAxisIndex === 0 && show ? 1 : 0,
      lineStyle: {
        width: lineWidth,
        opacity: lineOpacity
      },
      label: {
        show: labelLineShow,
        color: labelColorLine,
        distance: labelDistance,
        fontSize: labelFontsize,
        fontFamily: labelFontFamily,
      },
      encode: {
        x: xAxisDataIndex
      }
    };
    if (labelLineShow) {
      serieLine.label.position = labelPositionLine
    }
    if (smooth) {
      serieLine.smooth = smooth;
    }

    const xAxis = {
      type: 'category',
      axisTick: {
        show: xAxisTick,
        lineStyle: {
          width: axisLineWidth,
        }
      },
      axisLine: {
        lineStyle: {
          width: axisLineWidth,
          color: axisColor
        }
      },
      axisLabel: {
        color: fontColor,
        fontFamily: axisLabelFontFamily,
        fontSize: axisLabelFontsize || fontSize,
        rotate: xLabelRotate
      },
      splitLine: {
        show: xAxisSplitLine,
        lineStyle: {
          color: axisSplitLineColor,
          opacity: 0.4
        }
      }
    };
    if (Boolean(xAxisName)) {
      xAxis.name = xAxisName;
      xAxis.nameTextStyle = {
        color: fontColor,
        fontSize: axisNameFontsize || fontSize
      };
    }

    const yAxis_0 = {
      type: 'value',
      axisTick: {
        show: yAxisTick,
        lineStyle: {
          width: axisLineWidth,
        }
      },
      axisLine: {
        lineStyle: {
          width: axisLineWidth,
          color: axisColor
        }
      },
      axisLabel: {
        fontFamily: axisLabelFontFamily,
        fontSize: axisLabelFontsize || fontSize,
        color: fontColor
      },
      splitLine: {
        show: yAxisSplitLine,
        lineStyle: {
          color: axisSplitLineColor,
          type: yAxisSplitLineType
        }
      }
    };
    const yAxis_1 = {
      type: 'value',
      axisTick: {
        show: yAxisTick,
        lineStyle: {
          width: axisLineWidth,
        }
      },
      axisLine: {
        lineStyle: {
          width: axisLineWidth,
          color: axisColor
        }
      },
      axisLabel: {
        fontFamily: axisLabelFontFamily,
        fontSize: axisLabelFontsize || fontSize,
        color: fontColor
      },
      splitLine: {
        show: yAxisSplitLine,
        lineStyle: {
          color: axisSplitLineColor,
          type: yAxisSplitLineType
        }
      },
      show: show
    };
    if (Boolean(yAxisName)) {
      yAxis_0.name = yAxisName[0];
      if (yAxisName.length > 1) {
        yAxis_1.name = yAxisName[1];
      } else {
        yAxis_1.name = yAxisName[0];
      }
      yAxis_0.nameTextStyle = {
        color: fontColor,
        fontSize: axisNameFontsize || fontSize
      }
      yAxis_1.nameTextStyle = {
        color: fontColor,
        fontSize: axisNameFontsize || fontSize
      }
    }
    if (Boolean(yAxisUnit)) {
      if(yAxisUnit.indexOf(',')>-1){
        yAxisUnit = yAxisUnit.split(',').map(function(item) { return item.trim() })
      } else {
        yAxisUnit = [yAxisUnit, yAxisUnit];
      }
      yAxis_0.axisLabel.formatter = '{value}' + yAxisUnit[0];
      yAxis_1.axisLabel.formatter = '{value}' + yAxisUnit[1];
    }

    const tooltip = {
      trigger: 'axis',
      // axisPointer: {
      //   type: 'shadow'
      // }
      type: 'line',
      lineStyle: {
        color: axisColor,
        opacity: 0.6
      },
      textStyle: {
        fontSize: fontSize
      }
    };
    if (_legendMap) {
      tooltip.formatter = function (params) {
        if (params.length) {
          const xAxisName = params[0].name;
          const list = params.map(function (item, index) {
            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:" + item.color + "'></span>" + seriesName + ": " + item.data[index+1]
          })
          return xAxisName + list.join(' ')
        }
      }
    }

    const dataZoom = [
      {
        show: false,
        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 eventName = `call-` + self.getAttribute('id');
    const myChart = window.echarts.init(this);

    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();
      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 _stack = 'stack';
      const series = [];
      const _dataColumnLen = barDataIndex.length;
      barDataIndex.forEach(function(dem, i) {
        const serieBarFinal = JSON.parse(JSON.stringify(serieBar));
        if (stack == 'bar' || stack == 'all') serieBarFinal.stack = _stack;
        serieBarFinal.itemStyle.color = colorMap[i % colorMap.length];
        if (gradient !== 'none' && gradientColors) {
          const _gradient = gradient.split('::');
          const _type = _gradient[0];
          const _line = _gradient[1].split('-');
          const _colorStopsLen = gradientColors.length;
          serieBarFinal.itemStyle.color = {
            type: _type,
            x:_line[0], y:_line[1], x2:_line[2], y2:_line[3],
            colorStops: gradientColors[i < _colorStopsLen ? i : i % _colorStopsLen]
          };
        }
        serieBarFinal.encode.y = dem;
        serieBarFinal.encode.seriesName = dem;
        const item = Object.assign({}, { zlevel: _dataColumnLen - i }, serieBarFinal);
        series.push(item);
      });
      lineDataIndex.forEach(function(dem, i) {
        const serieLineFinal = JSON.parse(JSON.stringify(serieLine));
        const _i = (barDataIndex.length + i + 1) % colorMap.length;
        if (areaFill === '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 (areaFill === 'color') {
          const currColor = transferColorToRgba(colorMap[_i], 0.3)
          serieLineFinal.areaStyle = {
            color: currColor,
            opacity: 0.8
          }
        }
        serieLineFinal.encode.y = dem;
        serieLineFinal.encode.seriesName = dem;
        if (stack == 'line' || stack == 'all') serieLineFinal.stack = _stack;
        const item = Object.assign({}, { zlevel: _dataColumnLen + i + 1, itemStyle: { color: colorMap[_i] } }, serieLineFinal);
        series.push(item);
      });
      const option = {
        title: title,
        tooltip: tooltip,
        legend: legend,
        grid: grid,
        xAxis: xAxis,
        yAxis: [yAxis_0, yAxis_1],
        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 (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(defaultData);

    window.addEventListener('resize', function () {
      myChart.resize();
    }, false)
    let hasTransfer = false;
    // 有 dashboardHost 说明是运行模式
    if (window.spSocket) {
      window.spSocket.subscribe({
        eventName: eventName,
        callback: function (_data) {
          let _in1Str = _data.data.in1;
          if (_in1Str) {
            const source = JSON.parse(_in1Str);

            if (!hasTransfer) {
              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:barYAxisIndex
    change:axisSplitLineColor
    change:axisNameFontsize
    change:areaFill
    change:barDataIndex
    change:lineDataIndex
    change:xAxisDataIndex
    change:xAxisTick
    change:yAxisTick
    change:xAxisName
    change:yAxisName
    change:show
    change:yAxisUnit
    change:axisColor
    change:axisLineWidth
    change:axisLabelFontFamily
    change:labelFontFamily
    change:xAxisSplitLine
    change:yAxisSplitLine
    change:gridPadding
    change:containLabel
    change:labelPositionBar
    change:labelPositionLine
    change:labelDistance
    change:labelFontsize
    change:labelFormatter
    change:labelColorBar
    change:labelColorLine
    change:borderRadius
    change:xLabelRotate
    change:barWidth
    change:barGap
    change:smooth
    change:lineWidth
    change:lineOpacity
    change:symbol
    change:symbolSize
    change:yAxisSplitLineType
    change:stack
    change:axisLabelFontsize
    change:gradient
    change:gradientColors
    change:zoomStart
    change:zoomEnd
    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)));
  }
}
