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

var SIGN = '@_@';
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 = {
  getFunnelTooltip: function getFunnelTooltip() {
    return {
      trigger: 'item',
      formatter: function formatter(item) {
        var tpl = [];
        var name = item.name.split(SIGN)[0];
        var type = item.name.split(SIGN)[1];
        tpl.push('<span style="background-color:' + item.color + ';' + tipPointStyle + '"></span>');
        tpl.push(name + ': ' + getFormated(item.data.realValue, type));
        return tpl.join('');
      }
    };
  },
  getFunnelLegend: function getFunnelLegend(data, sequence, dataType) {
    var legendData = (sequence || Object.keys(data)).map(function (item) {
      return '' + item + SIGN + dataType;
    });
    var formatter = function formatter(item) {
      return item.split(SIGN)[0];
    };

    return { data: legendData, formatter: formatter };
  },
  getFunnelSeries: function getFunnelSeries(data, sequence, dataType, ascending) {
    var series = {
      type: 'funnel',
      label: { normal: {
          formatter: function formatter(item) {
            return item.name.split(SIGN)[0];
          }
        } },
      data: []
    };

    var realData = dataHandler.getFunnelValue(data, sequence);
    realData.forEach(function (d) {
      series.data.push({ name: '' + d.name + SIGN + dataType, value: d.value, realValue: d.realValue });
    });
    if (ascending) series.sort = 'ascending';
    return series;
  },
  getFunnelValue: function getFunnelValue(data, sequence) {
    var lastName = void 0;
    var falseFunnel = false;
    if (sequence) {
      sequence.some(function (value) {
        if (data[lastName] - data[value] < 0) {
          falseFunnel = true;
          return true;
        } else {
          lastName = value;
        }
      });
    }
    var step = 100 / Object.keys(data).length;
    var resultData = falseFunnel ? sequence.slice().reverse().map(function (key, index) {
      return { name: key, value: (index + 1) * step, realValue: data[key] };
    }) : Object.keys(data).map(function (key) {
      return { name: key, value: data[key], realValue: data[key] };
    });
    return resultData;
  }
};
/**
 * 漏斗图
 * settings = {
 *   dataType: 'KMB', 坐标轴类型 支持KMB, percent, normal
 *   sequence: ['d-1', 'd-2', 'd-3', 'd-4'], 可选，漏斗展示顺序
 *   ascending: true, 是否为金字塔
 * }
 * data = {
 *   'd-1': 100000,
 *   'd-2': 200000,
 *   'd-3': 50000,
 *   'd-4': 3000000
 * }
 * @param {Object} data 原始数据
 * @param {Object} settings 配置项
 * @returns Object
 */
var funnel = function funnel(data, settings) {
  var dataType = settings.dataType,
      sequence = settings.sequence,
      ascending = settings.ascending;

  var tooltip = dataHandler.getFunnelTooltip();
  var legend = dataHandler.getFunnelLegend(data, sequence, dataType);
  var series = dataHandler.getFunnelSeries(data, sequence, dataType, ascending);
  var options = { tooltip: tooltip, legend: legend, 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: 'VeFunnel',
  mixins: [chartMixin],
  created: function created() {
    this.chartHandler = funnel;
    this.echartsLib = echarts;
  }
};

module.exports = index;
