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

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 = {
  getWaterfallTooltip: function getWaterfallTooltip(dataType) {
    return {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: function formatter(items) {
        var item = items[1];
        return [item.name + '<br/>' + item.seriesName + ' :', '' + getFormated(item.value, dataType)].join('');
      }
    };
  },
  getWaterfallXAxis: function getWaterfallXAxis(data) {
    return {
      type: 'category',
      splitLine: { show: false },
      data: ['总计'].concat(Object.keys(data))
    };
  },
  getWaterfallYAxis: function getWaterfallYAxis(dataType) {
    return {
      type: 'value',
      axisTick: { show: false },
      axisLabel: {
        formatter: function formatter(val) {
          return getFormated(val, dataType);
        }
      }
    };
  },
  getWaterfallSeries: function getWaterfallSeries(data, dataType) {
    var seriesBase = { type: 'bar', stack: '总量' };
    var dataSum = Object.keys(data).reduce(function (pre, cur) {
      return pre + Number(data[cur]);
    }, 0).toFixed(2);
    var dataSumTemp = dataSum;
    var series = [];
    series.push(Object.assign({
      name: '辅助',
      itemStyle: {
        normal: { opacity: 0 },
        emphasis: { opacity: 0 }
      },
      data: [0].concat(Object.keys(data).map(function (key) {
        dataSumTemp -= data[key];
        return dataSumTemp;
      }))
    }, seriesBase));
    series.push(Object.assign({
      name: '数值',
      label: {
        normal: {
          show: true,
          position: 'top',
          formatter: function formatter(item) {
            return getFormated(item.value, dataType);
          }
        }
      },
      data: [dataSum].concat(Object.keys(data).map(function (key) {
        return data[key];
      }))
    }, seriesBase));
    return series;
  }
};

/**
 * 瀑布图
 * settings = { dataType: 'KMB' } 坐标轴类型 支持KMB, percent, normal
 * data = { d1: 100, d2: 200, d3: 300 }
 * @param {Object} data 原始数据
 * @param {Object} settings 配置项
 * @returns Object
 */
var waterfall = function waterfall(data, settings) {
  var dataType = settings.dataType;

  var tooltip = dataHandler.getWaterfallTooltip(dataType);
  var xAxis = dataHandler.getWaterfallXAxis(data);
  var yAxis = dataHandler.getWaterfallYAxis(dataType);
  var series = dataHandler.getWaterfallSeries(data, dataType);
  var options = { 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: 'VeWaterfall',
  mixins: [chartMixin],
  created: function created() {
    this.chartHandler = waterfall;
    this.echartsLib = echarts;
  }
};

module.exports = index;
