import * as tslib_1 from "tslib";
import { BaseChart, formatScale, formatMoney } from './base.chart';
import * as echarts from 'echarts';
import { Component, ChangeDetectionStrategy, NgZone, ViewChild, ElementRef, ViewEncapsulation } from '@angular/core';
import * as _ from 'lodash';
import { generateColorsAsStrings } from './color.helpers';
import { DecimalPipe } from '@angular/common';
import * as moment from 'moment';
var EChartComponent = /** @class */ (function (_super) {
    tslib_1.__extends(EChartComponent, _super);
    function EChartComponent(zone) {
        var _this = _super.call(this, zone) || this;
        _this._echartsOptions = {};
        _this._typeMap = {
            bar: 'bar',
            horizontalBar: 'bar',
            doughnut: 'pie',
            pie: 'pie',
            line: 'line'
        };
        return _this;
    }
    EChartComponent.prototype._checkUpdate = function (resized) {
        if (this._chartContainer && !this._chart) {
            this._createChart();
        }
        else if (resized && !this.paramsChanged) {
            this._recalculateSize();
        }
        if (this.paramsChanged) {
            this._applyOptions();
            this.resetParamsChangeState();
            this._recalculateSize();
        }
    };
    EChartComponent.prototype._onDestroy = function () {
        if (this._chart && !this._chart.isDisposed()) {
            this._chart.dispose();
        }
    };
    EChartComponent.prototype._recalculateSize = function () {
        if (this._chartContainer) {
            var div = this._chartContainer.nativeElement;
            var height = Math.max(div.clientWidth / (this.ratio || 2), 240);
            div.style.height = height + "px";
            if (this._chart) {
                this._chart.resize();
                if (this._echartsOptions.legend) {
                    var opt = this._chart.getOption();
                    if (div.clientWidth <= 240 || div.clientHeight <= 240) {
                        opt.legend = undefined;
                    }
                    else {
                        opt.legend = _.cloneDeep(this._echartsOptions.legend);
                    }
                    this._chart.setOption(opt, true);
                }
            }
        }
    };
    EChartComponent.prototype._createChart = function () {
        this._chart = echarts.init(this._chartContainer.nativeElement);
    };
    EChartComponent.prototype._applyOptions = function () {
        var _this = this;
        var ds = this.datasets || [];
        this._echartsOptions = {};
        var mainType = this.type || 'bar';
        var series = ds.map(function (v) { return ({
            name: v.name || _.isString(v.label) ? v.label : '',
            type: _this._typeMap[v.type || mainType] || v.type || mainType,
            data: (v.data || []).map(function (d) { return _this._mapDataItem(d, _this.timeFormat); })
        }); });
        var isTime = series.some(function (s) { return s.data.some(function (d) { return d.name && moment(d.name).isValid(); }); });
        var labels = this.labels || [];
        var timeAxis = [
            {
                type: 'time'
            }
        ];
        var catAxis = [{ data: labels, type: 'category' }];
        var valAxis = [{ type: 'value' }];
        var tooltip = {
            axisPointer: {
                type: 'shadow'
            }
        };
        tooltip.formatter = this._formatTooltip.bind(this, this.currency, this.percentage, this.digits);
        if (this.currency) {
            valAxis[0].axisLabel = { formatter: function (value) { return formatScale(value, _this.currency); } };
        }
        this._echartsOptions = {
            series: series,
            tooltip: tooltip
        };
        if (mainType === 'horizontalBar') {
            this._echartsOptions.yAxis = catAxis;
            this._echartsOptions.xAxis = valAxis;
            this._echartsOptions.tooltip['trigger'] = 'axis';
        }
        else if (mainType === 'line' || mainType === 'bar') {
            this._echartsOptions.xAxis = isTime ? timeAxis : catAxis;
            this._echartsOptions.yAxis = valAxis;
            this._echartsOptions.tooltip['trigger'] = 'axis';
        }
        else if (this._typeMap[mainType] === 'pie') {
            this._definePieShape(series, labels, mainType === 'doughnut');
        }
        if (this.legend !== false) {
            this._echartsOptions.legend = this._generateLegendOptions(series.length > 1, this._typeMap[mainType] === 'pie');
        }
        this._defineColors(series, this._typeMap[mainType] === 'pie');
        var opt = _.cloneDeep(this._echartsOptions);
        opt = _.merge(opt, this.options);
        this._chart.setOption(opt, true);
    };
    EChartComponent.prototype._mapDataItem = function (item, timeFormat) {
        if (_.isNumber(item)) {
            return { value: item };
        }
        if (!item) {
            return undefined;
        }
        if (item.x && moment(item.x).isValid() && _.isNumber(item.y)) {
            var m = moment(item.x);
            return {
                name: moment(item.x).format(timeFormat || 'L'),
                value: [m.get('year') + "-" + m.get('month') + "-" + m.get('day'), item.y]
            };
        }
        return item;
    };
    EChartComponent.prototype._definePieShape = function (series, labels, makeDoughnut) {
        var r = 0;
        var step = 80;
        if (makeDoughnut) {
            r = 40;
        }
        step = (80 - r) / series.length;
        series.forEach(function (s) {
            s.data.forEach(function (d, i) { return (d.name = labels[i]); });
            s.radius = [r + "%", r + step - 1 + "%"];
            r = r + step;
            s.label = {
                normal: {
                    show: false,
                    position: 'center'
                },
                emphasis: {
                    show: makeDoughnut ? true : false,
                    textShadowColor: 'grey',
                    textShadowOffsetY: 1
                }
            };
            s['avoidLabelOverlap'] = false;
        });
    };
    EChartComponent.prototype._defineColors = function (series, pieLike) {
        var _this = this;
        var cf = this.colorsFor || 'auto';
        if (cf === 'auto') {
            if (pieLike) {
                cf = 'data';
            }
            else {
                cf = 'series';
            }
        }
        if (cf === 'series') {
            var colors_1 = generateColorsAsStrings(this.colors || [], series.length);
            series.forEach(function (s, i) { return (s['color'] = colors_1[i]); });
        }
        else if (cf === 'data') {
            series.forEach(function (s) {
                var colors = generateColorsAsStrings(_this.colors || [], s.data.length);
                s.data.forEach(function (d, i) { return (d.itemStyle = { color: colors[i] }); });
            });
        }
    };
    EChartComponent.prototype._formatTooltip = function (currencyCode, percent, digitInfo, param) {
        var formatParam = function (p) {
            var l = "<div class=\"ezy-echart-tooltip-item\"><span class=\"ezy-echart-series-indicator\" style=\"background-color: " + p.color + "\"></span>\n\t\t\t " + p.seriesName + ": ";
            var percentOnly = percent === 'only' && p.percent;
            var showPercent = percent && p.percent;
            var v = _.isArray(p.data.value) ? p.data.value[1] : p.data.value;
            if (!percentOnly) {
                if (currencyCode) {
                    l += formatMoney(v, currencyCode, digitInfo);
                }
                else {
                    l += new DecimalPipe(moment.locale()).transform(v, digitInfo);
                }
            }
            if (showPercent) {
                l += "<span> " + p.percent + "%</span>";
            }
            l += '</div>';
            return l;
        };
        var str = '<div style="max-width: 35vw; white-space:normal">';
        if (_.isArray(param)) {
            str += "<strong>" + param[0].name + "</strong><br/>";
            str += "" + param.map(function (p) { return formatParam(p); }).join('');
        }
        else {
            str += "<strong>" + param.name + "</strong><br/>";
            str += "" + formatParam(param);
        }
        return str + '</div>';
    };
    EChartComponent.prototype._generateLegendOptions = function (multiSeries, pieLike) {
        var l = this.legend || 'auto';
        if ((l === 'auto' && (multiSeries || pieLike)) || _.isString(this.legend)) {
            var legend = {};
            if (l === 'auto' && pieLike) {
                legend.x = 'left';
            }
            if (['left', 'right', 'top', 'bottom'].indexOf(l) >= 0) {
                legend.x = l;
            }
            if (legend.x === 'left' || legend.x === 'right') {
                legend.orient = 'vertical';
            }
            return legend;
        }
        else if (_.isObject(this.legend)) {
            return this.legend;
        }
    };
    tslib_1.__decorate([
        ViewChild('chartContainer', { read: ElementRef }),
        tslib_1.__metadata("design:type", ElementRef)
    ], EChartComponent.prototype, "_chartContainer", void 0);
    EChartComponent = tslib_1.__decorate([
        Component({
            selector: 'ezy-echart',
            template: "<div #chartContainer></div>",
            changeDetection: ChangeDetectionStrategy.OnPush,
            encapsulation: ViewEncapsulation.None,
            styles: [
                ".ezy-echart-series-indicator {\n\t\t\tdisplay: inline-block;\n\t\t\tborder-radius: 10px;\n\t\t\tborder-width: 1px;\n\t\t\tborder-style: solid;\n\t\t\tborder-color: white;\n\t\t\twidth: 10px;\n\t\t\theight: 10px;\n\t\t}\n\t\t.ezy-echart-tooltip-item {\n\t\t\ttext-indent: -13px;\n\t\t\tpadding-left: 13px;\n\t\t}\n\t\t"
            ]
        }),
        tslib_1.__metadata("design:paramtypes", [NgZone])
    ], EChartComponent);
    return EChartComponent;
}(BaseChart));
export { EChartComponent };
//# sourceMappingURL=echart.component.js.map