'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/radar');

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 dataHandler = {
  getRadarLegend: function getRadarLegend(data) {
    var legendData = [];
    data.forEach(function (val) {
      if (legendData.indexOf(val.name) === -1) legendData.push(val.name);
    });

    return { data: legendData };
  },
  getRadarTooltip: function getRadarTooltip(dataType, radar) {
    var typeTemp = [];
    var nameTemp = [];
    radar.indicator.map(function (item, index) {
      typeTemp[index] = dataType[item.name];
      nameTemp[index] = item.name;
    });
    return {
      formatter: function formatter(item) {
        var tpl = [];
        tpl.push('<span style="background-color:' + item.color + ';' + tipPointStyle + '"></span>');
        tpl.push(item.seriesName + '<br />');
        item.data.forEach(function (val, index) {
          tpl.push(nameTemp[index] + ': ' + getFormated(val, typeTemp[index]) + '<br />');
        });
        return tpl.join('');
      }
    };
  },
  getRadarSetting: function getRadarSetting(data) {
    var settingBase = {
      indicator: [],
      shape: 'circle',
      splitNumber: 5
    };
    var indicatorTemp = {};
    data.forEach(function (items) {
      Object.keys(items).forEach(function (key) {
        if (key !== 'name') {
          if (!indicatorTemp[key]) {
            indicatorTemp[key] = [items[key]];
          } else {
            indicatorTemp[key].push(items[key]);
          }
        }
      });
    });
    settingBase.indicator = Object.keys(indicatorTemp).map(function (key) {
      return {
        name: key,
        max: Math.max.apply(null, indicatorTemp[key])
      };
    });
    return settingBase;
  },
  getRadarSeries: function getRadarSeries(data, legend, radar) {
    data = JSON.parse(JSON.stringify(data));
    var radarIndexObj = {};
    radar.indicator.forEach(function (item, index) {
      radarIndexObj[item.name] = index;
    });
    var dataStore = {};
    data.forEach(function (items) {
      var name = items.name;
      delete items.name;
      if (!dataStore[name]) {
        dataStore[name] = [items];
      } else {
        dataStore[name].push(items);
      }
    });
    var series = legend.data.map(function (name, index) {
      var seriesBase = {
        name: name,
        type: 'radar',
        data: []
      };
      dataStore[name].forEach(function (items) {
        var dataArr = [];
        Object.keys(items).forEach(function (key) {
          dataArr[radarIndexObj[key]] = items[key];
        });
        seriesBase.data.push(dataArr);
      });
      return seriesBase;
    });
    return series;
  }
};

var radar = function radar(data, settings) {
  var _settings$dataType = settings.dataType,
      dataType = _settings$dataType === undefined ? {} : _settings$dataType;

  var legend = dataHandler.getRadarLegend(data);
  var radar = dataHandler.getRadarSetting(data);
  var tooltip = dataHandler.getRadarTooltip(dataType, radar);
  var series = dataHandler.getRadarSeries(data, legend, radar);
  var options = { legend: legend, tooltip: tooltip, radar: radar, 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: 'VeRadar',
  mixins: [chartMixin],
  created: function created() {
    this.chartHandler = radar;
    this.echartsLib = echarts;
  }
};

module.exports = index;
