"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.defineWecharts = void 0;
var Echarts = __importStar(require("echarts"));
var lodash_1 = require("lodash");
var element_resize_event_1 = __importDefault(require("element-resize-event"));
var utils_1 = require("./helper/utils");
var color_1 = require("./helper/color");
var theme_1 = __importDefault(require("./theme"));
var config_1 = __importDefault(require("./config"));
var performance_1 = require("./helper/performance");
var Wecharts = (function (_super) {
    __extends(Wecharts, _super);
    function Wecharts() {
        var _this = _super.call(this) || this;
        _this.chartInstance = null;
        _this.loadingNode = null;
        _this.cacheOptions = null;
        _this.attachShadow({ mode: 'open' });
        return _this;
    }
    Wecharts.prototype.connectedCallback = function () {
        this.renderDom();
        this.chartInit();
    };
    Wecharts.prototype.disconnectedCallback = function () {
        if (this.chartInstance) {
            this.chartInstance.clear();
            this.chartInstance = null;
        }
        var container = this.shadowRoot.getElementById('rEchartsContainer');
        if (container) {
            element_resize_event_1.default.unbind(container, this.onResize);
            Echarts.dispose(container);
            this.shadowRoot.innerHTML = '';
        }
    };
    Wecharts.prototype.clear = function () {
        this.cacheOptions = null;
    };
    Object.defineProperty(Wecharts, "observedAttributes", {
        get: function () {
            return ['loading'];
        },
        enumerable: false,
        configurable: true
    });
    Wecharts.prototype.attributeChangedCallback = function (name, oldValue, newValue) {
        if (name === 'loading') {
            this.setLoading(newValue);
        }
    };
    Wecharts.prototype.getProps = function (key) {
        return this.getAttribute(key);
    };
    Wecharts.prototype.setLoading = function (loading) {
        var loadingTrue = loading === 'true' || loading === '';
        if (this.loadingNode) {
            var loadingEle = this.shadowRoot.getElementById('rEchartsLoading');
            var isContainLoadingNode = this.shadowRoot.contains(loadingEle);
            if (loadingTrue) {
                var container = this.shadowRoot.getElementById('rEchartsContainer');
                container.before(this.loadingNode);
            }
            else if (isContainLoadingNode) {
                this.shadowRoot.removeChild(loadingEle);
            }
        }
        else if (this.chartInstance) {
            if (loadingTrue) {
                this.chartInstance.showLoading();
            }
            else {
                this.chartInstance.hideLoading();
            }
        }
    };
    Wecharts.prototype.onResize = function () {
        var event = new CustomEvent('resizeAfter');
        this.chartInstance.resize();
        this.dispatchEvent(event);
    };
    Wecharts.prototype.chartInit = function () {
        var _this = this;
        var container = this.shadowRoot.getElementById('rEchartsContainer');
        var theme = this.getProps('theme') || 'wtLight';
        if (container) {
            Object.keys(theme_1.default).forEach(function (key) {
                Echarts.registerTheme(key, theme_1.default[key]);
            });
            this.chartInstance = Echarts.init(container, theme);
            var loadingProp = this.getProps('loading');
            this.setGraphData(null);
            this.setLoading(loadingProp);
            var event_1 = new CustomEvent('chartAfter', {
                detail: this.chartInstance,
            });
            setTimeout(function () {
                _this.dispatchEvent(event_1);
                if (_this.cacheOptions) {
                    _this.setOptions(_this.cacheOptions);
                }
            });
            (0, element_resize_event_1.default)(container, this.onResize.bind(this));
        }
    };
    Wecharts.prototype.setChartEvents = function (arg) {
        var _this = this;
        var container = this.shadowRoot.getElementById('rEchartsContainer');
        if (container) {
            Object.entries(arg)
                .filter(function (_a) {
                var key = _a[0], fn = _a[1];
                return /^[a-zA-Z]*$/.test(key) && typeof fn === 'function';
            })
                .forEach(function (_a) {
                var key = _a[0], fn = _a[1];
                var eventName = key.toLowerCase();
                _this.chartInstance &&
                    _this.chartInstance.on(eventName, function (params) {
                        fn.call(_this, params, _this.chartInstance);
                    });
            });
        }
    };
    Wecharts.prototype.getChartConfig = function (graphType) {
        return JSON.parse(JSON.stringify(config_1.default[graphType] || {}));
    };
    Wecharts.prototype.getColor = function () {
        var colorStr = this.getProps('color');
        return (colorStr === null || colorStr === void 0 ? void 0 : colorStr.split(',')) || undefined;
    };
    Wecharts.prototype.getDimensionsData = function (dimension, data) {
        var _a;
        var dimensionRes = [dimension];
        var dataRes = data;
        var quotaStr = this.getProps('dataQuota');
        var dimensionObj = (0, utils_1.parseJsonStr)(dimension);
        if (dimensionObj || (0, utils_1.isPath)(dimension)) {
            var dimensionKey = '';
            var dimensionValue = [];
            if (dimensionObj) {
                var key = dimensionObj.key, value = dimensionObj.value;
                if ((0, utils_1.isPath)(key)) {
                    dimensionKey = (0, utils_1.getResByPath)(data, key);
                }
                dimensionValue = (0, utils_1.getResByPath)(data, value);
            }
            else {
                var pathArr = dimension.split('.');
                dimensionKey = pathArr[pathArr.length - 1];
                dimensionValue = (0, utils_1.getResByPath)(data, dimension);
            }
            dataRes = (_a = {},
                _a[dimensionKey] = dimensionValue,
                _a);
            var quotaObj = (0, utils_1.parseJsonStr)(quotaStr || '');
            var quotaKeys_1 = [];
            if (quotaObj) {
                quotaObj.forEach(function (_a) {
                    var key = _a.key, value = _a.value;
                    if ((0, utils_1.isPath)(key)) {
                        var quotaKey = (0, utils_1.getResByPath)(data, key);
                        quotaKeys_1.push(quotaKey);
                        dataRes[quotaKey] = (0, utils_1.getResByPath)(data, value);
                    }
                    else {
                        quotaKeys_1.push(key);
                        dataRes[key] = (0, utils_1.getResByPath)(data, value);
                    }
                });
            }
            else if (quotaStr) {
                quotaStr.split(',').forEach(function (item) {
                    if ((0, utils_1.isPath)(item)) {
                        var pathArr = item.split('.');
                        var quotaKey = pathArr[pathArr.length - 1];
                        quotaKeys_1.push(quotaKey);
                        dataRes[quotaKey] = (0, utils_1.getResByPath)(data, item);
                    }
                    else {
                        quotaKeys_1.push(item);
                        dataRes[item] = data[item];
                    }
                });
            }
            dimensionRes = __spreadArray([dimensionKey], quotaKeys_1, true);
        }
        else {
            var dataType = (0, utils_1.getDataType)(data);
            if (quotaStr) {
                dimensionRes = __spreadArray([dimension], quotaStr.split(','), true);
            }
            if (dataType === 'array-obj') {
                var quota = Object.keys(data[0]).filter(function (key) { return key !== dimension; });
                dimensionRes = __spreadArray([dimension], quota, true);
            }
            if (dataType === 'object') {
                var quota = Object.keys(data).filter(function (key) { return key !== dimension; });
                dimensionRes = __spreadArray([dimension], quota, true);
            }
        }
        return { dimensions: dimensionRes, data: dataRes };
    };
    Wecharts.prototype.getRadius = function (graphType) {
        var radius = this.getProps('radius');
        var configs = this.getChartConfig(graphType);
        var configSeries = configs === null || configs === void 0 ? void 0 : configs.series;
        var radiusVal = '60%';
        switch (graphType) {
            case 'pie':
                radiusVal = radius || configSeries.radius || '60%';
                break;
            case 'ring':
                radiusVal = radius
                    ? radius.split(',')
                    : configSeries.radius || ['40%', '60%'];
                break;
            case 'rose':
                if (radius) {
                    var res = radius.split(',');
                    radiusVal = res.length === 1 ? res[0] : res;
                }
                else {
                    radiusVal = configSeries.radius || ['5%', '60%'];
                }
                break;
            default:
                radiusVal = '60%';
        }
        return radiusVal;
    };
    Wecharts.prototype.getLegend = function (graphType) {
        var legendShow = this.getProps('showLegend');
        var legendPosition = this.getProps('legendPosition');
        var legendOrient = this.getProps('legendOrient');
        var configs = this.getChartConfig(graphType);
        var configLegend = configs === null || configs === void 0 ? void 0 : configs.legend;
        var legend = __assign({}, configLegend);
        if (legendShow === 'false') {
            legend.show = false;
        }
        else {
            legend.show = true;
            legend.orient = legendOrient || legend.orient || 'horizontal';
            if (legendPosition && ['right', 'left'].includes(legendPosition)) {
                if (legendPosition === 'right') {
                    legend.right = 0;
                }
                else {
                    legend.left = 0;
                }
            }
            else if (legend.orient === 'vertical') {
                legend.left = 0;
                legend.top = 'middle';
            }
            else {
                legend.left = legendPosition || legend.left;
                legend.top = 0;
            }
        }
        return legend;
    };
    Wecharts.prototype.getToolbox = function (graphType) {
        var toolboxShow = this.getProps('showToolbox');
        var toolboxVal = this.getProps('toolbox');
        var toolPosition = this.getProps('toolPosition');
        var toolOrient = this.getProps('toolOrient');
        var configs = this.getChartConfig(graphType);
        var configToolbox = configs === null || configs === void 0 ? void 0 : configs.toolbox;
        var toolbox = __assign({}, configToolbox);
        if (toolboxShow === 'false') {
            return {
                show: false,
            };
        }
        if (toolboxVal) {
            var feature_1 = {};
            toolboxVal.split(',').forEach(function (t) {
                if (!t.trim())
                    return;
                if (t === 'magicType') {
                    feature_1['magicType'] = {
                        type: ['line', 'bar', 'stack'],
                    };
                }
                else {
                    feature_1[t] = {};
                }
            });
            toolbox.show = true;
            toolbox.feature = feature_1;
            toolbox.orient = toolOrient || 'horizontal';
            toolbox.left = toolPosition || 'right';
        }
        return toolbox;
    };
    Wecharts.prototype.getTooltip = function (graphType) {
        var tooltipTrigger = this.getProps('tooltipTrigger');
        var configs = this.getChartConfig(graphType);
        var configTooltip = configs === null || configs === void 0 ? void 0 : configs.tooltip;
        var tooltip = __assign({}, configTooltip);
        if (tooltipTrigger) {
            tooltip.trigger = tooltipTrigger;
        }
        return tooltip;
    };
    Wecharts.prototype.getGrid = function (graphType, _a) {
        var legend = _a.legend, dataZoom = _a.dataZoom;
        var configs = this.getChartConfig(graphType);
        var configGrid = (configs === null || configs === void 0 ? void 0 : configs.grid) || {};
        if (legend.orient === 'horizontal') {
            if (legend.left) {
                configGrid.top = 60 + legend.top;
            }
            else if (legend.bottom) {
                configGrid.bottom = 200;
            }
        }
        else if (legend.orient === 'vertical') {
            if (legend.top) {
                configGrid.left = '16%';
            }
            else if (legend.right) {
                configGrid.right = '16%';
            }
        }
        if (dataZoom) {
            configGrid.bottom = (configGrid.bottom || 20) + 30;
        }
        return configGrid;
    };
    Wecharts.prototype.getxAxis = function (graphType) {
        var hideXaxis = this.getProps('hideXaxis');
        var configs = this.getChartConfig(graphType);
        var configXAxis = (configs === null || configs === void 0 ? void 0 : configs.xAxis) || {};
        if (hideXaxis) {
            configXAxis.show = false;
        }
        return configXAxis;
    };
    Wecharts.prototype.getyAxis = function (graphType) {
        var hideYaxis = this.getProps('hideYaxis');
        var configs = this.getChartConfig(graphType);
        var configYAxis = (configs === null || configs === void 0 ? void 0 : configs.yAxis) || {};
        configYAxis.axisLabel = configYAxis.axisLabel || {};
        if (hideYaxis) {
            configYAxis.show = false;
        }
        else {
            var scaleMap_1 = {
                BW: 1000000,
                tenY: 1000000000,
            };
            var scaleMapD_1 = {
                BW: 'M',
                tenY: 'B',
            };
            configYAxis.axisLabel.formatter = function (value) {
                var keys = Object.keys(scaleMap_1);
                for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {
                    var key = keys_1[_i];
                    if (value >= scaleMap_1[key]) {
                        return "".concat(value / scaleMap_1[key], " ").concat(scaleMapD_1[key]);
                    }
                }
                return value;
            };
        }
        return configYAxis;
    };
    Wecharts.prototype.getSeriesConfig = function (graphType) {
        var showLabelLine = this.getProps('showLabelLine');
        var showSeriesLabel = this.getProps('showSeriesLabel');
        var seriesLabelPosition = (this.getProps('seriesLabelPosition') || 'outside').split(',');
        var showLabel = showSeriesLabel !== null && showSeriesLabel !== void 0 ? showSeriesLabel : graphType === 'pie';
        var sLabelLine = showLabelLine !== null && showLabelLine !== void 0 ? showLabelLine : graphType === 'pie';
        var res = {
            label: {
                show: showLabel,
                position: seriesLabelPosition.length > 1
                    ? seriesLabelPosition
                    : seriesLabelPosition[0],
            },
            radius: this.getRadius(graphType),
            labelLine: { show: sLabelLine },
        };
        return res;
    };
    Wecharts.prototype.getSeries = function (graphType, data, dataLength) {
        var configs = this.getChartConfig(graphType);
        var quotaStr = this.getProps('dataQuota');
        var seriesConfig = this.getSeriesConfig(graphType);
        var mergeSeries = (0, lodash_1.merge)((configs === null || configs === void 0 ? void 0 : configs.series) || {}, seriesConfig);
        if (quotaStr) {
            var quota = (0, utils_1.parseJsonStr)(quotaStr)
                ? (0, utils_1.parseJsonStr)(quotaStr)
                : quotaStr.split(',');
            return quota.map(function () { return mergeSeries; });
        }
        var series = [];
        var dataType = (0, utils_1.getDataType)(data);
        if (dataType === 'array-matrix') {
            series = data[0].slice(1).map(function () { return mergeSeries; });
        }
        else if (dataType === 'array-obj') {
            series = Object.keys(data[0])
                .slice(1)
                .map(function () { return mergeSeries; });
        }
        else if (typeof data === 'object') {
            series = Object.keys(data)
                .slice(1)
                .map(function () { return mergeSeries; });
        }
        if (dataLength > 300) {
            series = series.map(function (s) { return (0, performance_1.optmizeChart)(s, dataLength); });
        }
        return series;
    };
    Wecharts.prototype.setGraphData = function (data) {
        var _this = this;
        var graphType = this.getProps('type');
        if (this.chartInstance) {
            if (data && graphType) {
                var graphTitle = this.getProps('title');
                var graphSubTitle = this.getProps('subTitle');
                var titlePositionVal = this.getProps('titlePosition');
                var showDataZoomVal = this.getProps('showDataZoom');
                var _a = (titlePositionVal === null || titlePositionVal === void 0 ? void 0 : titlePositionVal.split(',')) || ['center', 0], left = _a[0], top_1 = _a[1];
                var dimension = this.getProps('dataDimension');
                var backgroundColor = this.getProps('backgroundColor');
                if (graphType) {
                    var dataLength = data.length;
                    if (Array.isArray(data)) {
                        dataLength = data.length;
                    }
                    else if ((0, lodash_1.isObject)(data)) {
                        dataLength = Object.values(data)[0].length;
                    }
                    var graphOptions = this.getChartConfig(graphType);
                    graphOptions.series = this.getSeries(graphType, data, dataLength);
                    if (dimension && graphOptions.dataset) {
                        var dimensionsRes = this.getDimensionsData(dimension, data);
                        graphOptions.dataset.dimensions = dimensionsRes.dimensions;
                        graphOptions.dataset.source = dimensionsRes.data;
                    }
                    else if (graphOptions.dataset) {
                        graphOptions.dataset.source = data;
                    }
                    if (showDataZoomVal === 'false') {
                        graphOptions.dataZoom = null;
                    }
                    else if (dataLength >= (Number(showDataZoomVal) || 50)) {
                        graphOptions.grid = __assign(__assign({}, graphOptions.grid), { bottom: 40 });
                    }
                    else {
                        graphOptions.dataZoom = null;
                    }
                    if (graphOptions.title) {
                        graphOptions.title.text = graphTitle;
                        graphOptions.title.subtext = graphSubTitle;
                        graphOptions.title.left = left;
                        graphOptions.title.top = top_1 || 0;
                    }
                    graphOptions.legend = this.getLegend(graphType);
                    graphOptions.toolbox = this.getToolbox(graphType);
                    graphOptions.tooltip = this.getTooltip(graphType);
                    graphOptions.grid = this.getGrid(graphType, graphOptions);
                    graphOptions.xAxis = this.getxAxis(graphType);
                    graphOptions.yAxis = this.getyAxis(graphType);
                    var colors = this.getColor();
                    if (colors) {
                        graphOptions.color = colors;
                    }
                    if (backgroundColor) {
                        graphOptions.backgroundColor = backgroundColor;
                    }
                    this.chartInstance.setOption(graphOptions);
                    setTimeout(function () {
                        var _a;
                        (_a = _this.chartInstance) === null || _a === void 0 ? void 0 : _a.resize();
                    }, 100);
                }
            }
            else {
                this.setNoDataGraph();
            }
        }
    };
    Wecharts.prototype.setOptions = function (options) {
        var _this = this;
        if (this.chartInstance) {
            var isShowNoData = this.getProps('showNoData');
            var mode = this.getProps('mode');
            var keepCache = this.getProps('keepCache');
            var isShowDataBool = isShowNoData === 'true' || isShowNoData === '';
            if (!mode || mode === 'default') {
                this.chartInstance.clear();
            }
            if (options && !isShowDataBool) {
                var defaultOptions = __assign({}, options);
                defaultOptions.color = defaultOptions.color || color_1.COLORS_1_X;
                this.chartInstance.setOption(defaultOptions);
                this.chartInstance.resize();
                setTimeout(function () {
                    var _a;
                    (_a = _this.chartInstance) === null || _a === void 0 ? void 0 : _a.resize();
                }, 100);
                this.cacheOptions = keepCache === 'true' ? defaultOptions : null;
            }
            else {
                this.setNoDataGraph();
            }
        }
    };
    Wecharts.prototype.setNoDataGraph = function () {
        var _this = this;
        if (this.chartInstance) {
            var noDataTitle = this.getProps('noDataTitle');
            this.chartInstance.setOption(config_1.default.noData(noDataTitle || ''));
            setTimeout(function () {
                var _a;
                (_a = _this.chartInstance) === null || _a === void 0 ? void 0 : _a.resize();
            }, 100);
        }
    };
    Wecharts.prototype.renderDom = function () {
        var template = document.createElement('template');
        var children = Array.from(this.children);
        var hasCustomLoading = children.length &&
            children.some(function (child) { return child.getAttribute('slot') === 'loading'; });
        if (hasCustomLoading) {
            var loadingTemplate = document.createElement('template');
            loadingTemplate.innerHTML = "\n        <div class=\"w-echarts-loading\" id=\"rEchartsLoading\">\n          <div class=\"w-echarts-loading-spin\">\n            <slot name=\"loading\"></slot>\n          </div>\n        </div>\n      ";
            this.loadingNode = loadingTemplate.content.cloneNode(true);
        }
        template.innerHTML = "\n      <style>\n        :host {\n          display: block;\n          position: relative;\n          width: 100%;\n          height: 100%;\n        }\n\n        .w-echarts {\n          width: 100%;\n          height: 100%;\n        }\n\n        .w-echarts-loading {\n          box-sizing: border-box;\n          position: absolute;\n          top: 0;\n          left: 0;\n          z-index: 99;\n          width: 100%;\n          height: 100%;\n          text-align: center;\n          background-color: rgba(255, 255, 255, 0.6);\n        }\n\n        .w-echarts-loading-spin {\n          position: absolute;\n          top: 50%;\n          left: 50%;\n          z-index: 99;\n          transform: translate(-50%, -50%);\n          padding: 16px;\n          color: rgba(0, 0, 0, 0.6);\n        }\n      </style>\n\n      <div class=\"w-echarts\" id=\"rEchartsContainer\"></div>\n    ";
        this.shadowRoot.append(template.content.cloneNode(true));
    };
    return Wecharts;
}(HTMLElement));
var defineWecharts = function () {
    if (customElements.get('w-echarts'))
        return;
    customElements.define('w-echarts', Wecharts);
};
exports.defineWecharts = defineWecharts;
exports.default = Wecharts;
//# sourceMappingURL=index.js.map