'use strict';

function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var echarts = _interopDefault(require('echarts/lib/echarts'));
require('echarts/lib/component/tooltip');
require('echarts/lib/component/legend');
require('echarts/lib/component/title');
require('echarts/lib/chart/scatter');

var SIGN = '@_@';
var getLabelName = function getLabelName(item) {
  return item.split(SIGN)[0];
}; // TODO: delete
var tipPointStyle = [// TODO: delete
'display: inline-block;', 'width: 10px;', 'height: 10px;', 'border-radius: 50%;', 'margin-right:2px;'].join('');

echarts.registerTheme('ve-chart', {
  color: ['#19d4ae', '#5ab1ef', '#fa6e86', '#ffb980', '#0067a6', '#c4b4e4', '#d87a80', '#9cbbff', '#d9d0c7', '#87a997', '#d49ea2', '#5b4947', '#7ba3a8'],
  categoryAxis: {
    axisLine: { show: false },
    axisTick: { show: false },
    splitLine: { show: false }
  },
  valueAxis: {
    axisLine: { show: false }
  },
  line: {
    smooth: true
  },
  grid: {
    left: 60,
    right: 60,
    top: 60,
    bottom: 60
  }
});

var numberFormat = function numberFormat(val) {
  var digits = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;

  if (isNaN(+val)) return val;

  var symbolMap = [{ value: 1E18, symbol: 'E' }, { value: 1E15, symbol: 'P' }, { value: 1E12, symbol: 'T' }, { value: 1E9, symbol: 'B' }, { value: 1E6, symbol: 'M' }, { value: 1E3, symbol: 'k' }];

  for (var i = 0; i < symbolMap.length; i++) {
    if (Math.abs(val) >= symbolMap[i].value) {
      return (val / symbolMap[i].value).toFixed(digits) + symbolMap[i].symbol;
    }
  }

  return val.toString();
};

var formatTausends = function formatTausends(num) {
  return String(num).replace(/^(\s+|-)?\d+(?=.?\d*($|\s))/g, function (m) {
    return m.replace(/(?=(?!\b)(\d{3})+$)/g, ',');
  });
};

var getFormated = function getFormated(val, type) {
  switch (type) {
    case 'KMB':
      return numberFormat(val);
    case 'percent':
      return (val * 100).toFixed(2) + '%';
    case 'normal':
      return formatTausends(val);
    default:
      return val;
  }
};

var getLineKB = function getLineKB(s, v) {
  var result = [];
  result[0] = (s[1] - s[0]) / (v[1] - v[0]);
  result[1] = s[0] - result[0] * v[0];
  return result;
};

var scatterRange = [10, 80];
var dataHandler = {
  getScatterLegend: function getScatterLegend(data, dataType, axisNames) {
    var formatter = getLabelName;
    var legendData = [];

    data.forEach(function (items) {
      if (legendData.indexOf(items.name) === -1) legendData.push(items.name);
    });

    return { data: legendData, formatter: formatter };
  },
  getScatterTooltip: function getScatterTooltip(dataNames, dataType) {
    return {
      formatter: function formatter(item) {
        var tpl = [];
        tpl.push('<span style="background-color:' + item.color + ';' + tipPointStyle + '"></span>');
        tpl.push(item.seriesName + '<br>');
        dataNames.forEach(function (name, index) {
          tpl.push(name + ' : ' + getFormated(item.data[index], dataType[index]) + '<br>');
        });
        return tpl.join('');
      }
    };
  },
  getScatterAxis: function getScatterAxis() {
    var type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'normal';
    var axisName = arguments[1];

    return {
      splitLine: { lineStyle: { type: 'dashed' } },
      scale: true,
      axisTick: { show: false },
      name: axisName,
      axisLabel: {
        formatter: function formatter(val) {
          return getFormated(val, type);
        }
      }
    };
  },
  getScatterSeries: function getScatterSeries(data, dataType, axisNames) {
    data = JSON.parse(JSON.stringify(data));
    var type = 'scatter';
    var itemStyle = {
      normal: {
        shadowBlur: 10,
        shadowColor: 'rgba(25, 100, 150, 0.5)',
        shadowOffsetY: 5
      }
    };
    var dataTypeObj = {};

    axisNames.forEach(function (name, index) {
      dataTypeObj[name] = dataType[index];
    });

    var valueRange = [data[0][axisNames[2]], data[0][axisNames[2]]];
    var dataTemp = {};

    data.forEach(function (items) {
      var name = items.name;

      delete items.name;
      if (!dataTemp[name]) {
        dataTemp[name] = [items];
      } else {
        dataTemp[name].push(items);
      }
      if (items[axisNames[2]] < valueRange[0]) valueRange[0] = items[axisNames[2]];
      if (items[axisNames[2]] > valueRange[1]) valueRange[1] = items[axisNames[2]];
    });

    var lineKB = getLineKB(scatterRange, valueRange);
    var series = Object.keys(dataTemp).map(function (name, index) {
      var result = [];

      dataTemp[name].forEach(function (val, index) {
        result[index] = [];
        axisNames.forEach(function (name) {
          result[index].push(val[name]);
        });
      });

      return {
        type: type,
        itemStyle: itemStyle,
        name: name,
        data: result,
        symbolSize: function symbolSize(data) {
          return data[2] * lineKB[0] + lineKB[1];
        }
      };
    });
    return series;
  }
};
/**
 * 气泡图
 * settings = {
 *   dataType: ['normal','normal',KMB'], 坐标轴类型 支持KMB, percent, normal
 *   axisNames: ['d1', 'd2', 'd3'], 显示在X轴，Y轴，气泡上的数据名称
 * }
 * data = [
 *   { d1: 1000, d2: 2000, d3: 3000, name: '1991' },
 *   { d1: 2000, d2: 3000, d3: 4000, name: '1991' },
 *   { d1: 3000, d2: 5000, d3: 8000, name: '1991' },
 *   { d1: 300, d2: 400, d3: 500, name: '1992' },
 *   { d1: 330, d2: 500, d3: 200, name: '1992' },
 *   { d1: 30, d2: 40, d3: 50, name: '1992' },
 *   { d1: 100, d2: 200, d3: 30, name: '1993' },
 *   { d1: 150, d2: 250, d3: 60, name: '1993' },
 *   { d1: 200, d2: 200, d3: 30, name: '1993' }
 * ]
 * @param {Object} data 原始数据
 * @param {Object} settings 配置项
 * @returns Object
 */
var scatter = function scatter(data, settings) {
  var _settings$dataType = settings.dataType,
      dataType = _settings$dataType === undefined ? [] : _settings$dataType,
      _settings$axisNames = settings.axisNames,
      axisNames = _settings$axisNames === undefined ? [] : _settings$axisNames;

  var legend = dataHandler.getScatterLegend(data, dataType, axisNames);
  var tooltip = dataHandler.getScatterTooltip(axisNames, dataType);
  var xAxis = dataHandler.getScatterAxis(dataType[0], axisNames[0]);
  var yAxis = dataHandler.getScatterAxis(dataType[1], axisNames[1]);
  var series = dataHandler.getScatterSeries(data, dataType, axisNames);
  var options = { legend: legend, tooltip: tooltip, xAxis: xAxis, yAxis: yAxis, series: series };
  return options;
};

var chartMixin = {
  props: {
    data: { type: [Object, Array], default: null },
    settings: { type: Object, default: function _default() {
        return {};
      }
    },
    width: { type: String, default: 'auto' },
    height: { type: String, default: '400px' },
    beforeConfig: { type: Function },
    afterConfig: { type: Function },
    events: { type: Object }
  },

  watch: {
    data: function data(v) {
      var dataKeys = Object.keys(v);
      var dataKeyProp = v.key;
      if (dataKeyProp && Array.isArray(dataKeyProp) && dataKeyProp.length || dataKeys.length) {
        this.dataHandler(v);
      }
    },

    settings: {
      deep: true,
      handler: function handler(v) {
        this.chartHandler = this.chartLib[v.type];
        this.dataHandler(this.data);
      }
    }
  },

  computed: {
    canvasStyle: function canvasStyle() {
      return { width: this.width, height: this.height };
    }
  },

  methods: {
    dataHandler: function dataHandler(data) {
      if (!this.chartHandler) return;
      if (this.beforeConfig) data = this.beforeConfig(data);
      var options = this.chartHandler(data, this.settings);
      if (Array.isArray(this.settings.color)) options.color = this.settings.color;
      if (this.settings.grid) options.grid = this.settings.grid;
      if (this.afterConfig) options = this.afterConfig(options);
      if (options) this.echarts.setOption(options, true);
    },
    init: function init() {
      if (this.echarts) return;
      this.echarts = this.echartsLib.init(this.$refs.canvas, 've-chart');
      if (this.data) this.dataHandler(this.data);
      if (this.events) this.bindEvents();
    },
    bindEvents: function bindEvents() {
      var _this = this;

      Object.keys(this.events).forEach(function (event) {
        _this.echarts.on(event, _this.events[event]);
      });
    }
  },

  mounted: function mounted() {
    var _this2 = this;

    this.$nextTick(function () {
      _this2.init();
      window.addEventListener('resize', _this2.echarts.resize);
    });
  },
  beforeDestory: function beforeDestory() {
    window.removeEventListener('resize', this.echarts.resize);
    this.echarts.dispose();
  }
};

var index = {
  render: function render() {
    var _vm = this;var _h = _vm.$createElement;var _c = _vm._self._c || _h;return _c('div', { ref: "canvas", style: _vm.canvasStyle });
  },
  staticRenderFns: [],
  name: 'VeScatter',
  mixins: [chartMixin],
  created: function created() {
    this.chartHandler = scatter;
    this.echartsLib = echarts;
  }
};

module.exports = index;
