import '@sd-angular/core/common';
import { InjectionToken, Component, ChangeDetectorRef, Optional, Inject, Input, ViewChild, NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { __awaiter, __classPrivateFieldGet } from 'tslib';
import * as Chart from 'chart.js';
import $ from 'jquery';
import { v4 } from 'uuid';

const ChartColors = {
    Red: 'rgb(255, 99, 132)',
    Orange: 'rgb(255, 159, 64)',
    Yellow: 'rgb(255, 205, 86)',
    Green: 'rgb(75, 192, 192)',
    Blue: 'rgb(54, 162, 235)',
    Purple: 'rgb(153, 102, 255)',
    Grey: 'rgb(201, 203, 207)',
    Purple700: '#2E224C',
    Purple600: '#453372',
    Purple500: '#574191',
    Purple400: '#7356BF',
    Purple300: '#957FCE',
    Purple200: '#C1B4E2',
    Purple100: '#E3DDF2',
    Purple50: '#F3F1F9',
    Blue700: '#0F2C60',
    Blue600: '#174291',
    Blue500: '#1D53B7',
    Blue400: '#276EF1',
    Blue300: '#5A90F4',
    Blue200: '#9FBFF8',
    Blue100: '#D4E2FC',
    Blue50: '#EDF3FD',
    Green700: '#0D4020',
    Green600: '#156A36',
    Green500: '#09863D',
    Green400: '#21A453',
    Green300: '#43BF75',
    Green200: '#9EE2B8',
    Green100: '#CFF3DD',
    Green50: '#F0FAF3',
    Yellow700: '#664C1A',
    Yellow600: '#997328',
    Yellow500: '#C19132',
    Yellow400: '#FFC043',
    Yellow300: '#FFCF70',
    Yellow200: '#FFE3AC',
    Yellow100: '#FFF2D9',
    Yellow50: '#FFF9EF',
    Orange700: '#5F2C14',
    Orange600: '#8E421E',
    Orange500: '#B45326',
    Orange400: '#ED6E33',
    Orange300: '#F19063',
    Orange200: '#F7BFA5',
    Orange100: '#FBE2D6',
    Orange50: '#FDF3EE',
    Red700: '#541A14',
    Red600: '#7F281E',
    Red500: '#A13226',
    Red400: '#D44333',
    Red300: '#DE7063',
    Red200: '#ECACA5',
    Red100: '#F6D9D6',
    Red50: '#FBEFEE',
    Brown700: '#3D281E',
    Brown600: '#5B3C2D',
    Brown500: '#744C39',
    Brown400: '#99644C',
    Brown300: '#B18976',
    Brown200: '#D2BAB0',
    Brown100: '#EBE0DB',
    Brown50: '#F6F2F0',
    Gray900: '#141414',
    Gray800: '#1F1F1F',
    Gray700: '#333333',
    Gray600: '#545454',
    Gray500: '#757575',
    Gray400: '#AFAFAF',
    Gray300: '#CBCBCB',
    Gray200: '#E2E2E2',
    Gray100: '#EEEEEE',
    Gray50: '#F6F6F6',
    Platinum700: '#394145',
    Platinum600: '#556268',
    Platinum500: '#6C7C83',
    Platinum400: '#8EA3AD',
    Platinum300: '#A1BDCA',
    Platinum200: '#CCDFE5',
    Platinum100: '#EBF5F7',
    Platinum50: '#F4FAFB',
    EatsGreen400: '#21A453',
    FreightBlue400: '#21A453',
    JumpRed400: '#FF0A2D',
    Black: '#000000',
    White: '#FFFFFF',
};
const CHART_CONFIG = new InjectionToken('chart.configuration');

var _drawTotalOfStackedBar;
class SdChart {
    constructor(ref, chartConfiguration) {
        this.ref = ref;
        this.chartConfiguration = chartConfiguration;
        this.initialized = false;
        this.isLoading = false;
        this.visible = true;
        this.height = '300px';
        this.loadingStart = () => {
            this.isLoading = true;
        };
        _drawTotalOfStackedBar.set(this, (chartType) => {
            return {
                afterDraw(chartInstance, easing, options) {
                    var _a, _b;
                    if ((_b = (_a = chartInstance === null || chartInstance === void 0 ? void 0 : chartInstance.data) === null || _a === void 0 ? void 0 : _a.datasets) === null || _b === void 0 ? void 0 : _b.length) {
                        const ctx = chartInstance.ctx;
                        chartInstance.data.datasets[0].data.forEach((dataPoint, index) => {
                            let curLastIndex = 0;
                            let curTotal = 0;
                            chartInstance.data.datasets.forEach((dataset, setIndex) => {
                                if (dataset.data[index] != 0 && (!dataset.hidden) && dataset.type !== 'line') {
                                    curLastIndex = setIndex;
                                    if (Number.isNumber(dataset.data[index])) {
                                        curTotal += Number(dataset.data[index]);
                                    }
                                    else
                                        curTotal += 0;
                                }
                            });
                            const { x, y } = chartInstance.getDatasetMeta(curLastIndex).data[index]._model;
                            const textWidth = ctx.measureText(curTotal.toString()).width;
                            ctx.fillStyle = 'black';
                            let xTextPosition = (x - textWidth / 2) - textWidth > 0 ? (x - textWidth / 2) : 0;
                            if (index == 0) {
                                xTextPosition = x + 10;
                            }
                            else if (index === chartInstance.data.datasets[0].data.length - 1) {
                                xTextPosition = x - textWidth - 10;
                            }
                            ctx.font = '300 10px';
                            ctx.fillText(curTotal.toString(), chartType === 'horizontalBar' ? x + 10 : xTextPosition, chartType === 'horizontalBar' ? y : y - 10);
                        });
                    }
                },
            };
        });
    }
    set chartOption(chartOption) {
        this.pChartOption = chartOption;
        if (this.initialized) {
            this.renderChart();
        }
    }
    ngOnInit() {
    }
    ngAfterViewInit() {
        this.renderChart(true);
        this.initialized = true;
        this.ref.detectChanges();
    }
    renderChart(firstRender) {
        var _a, _b;
        return __awaiter(this, void 0, void 0, function* () {
            this.height = ((_a = this.pChartOption) === null || _a === void 0 ? void 0 : _a.height) || '300px';
            if (!firstRender) {
                this.visible = false;
                yield new Promise(resolve => setTimeout(resolve, 200));
                this.visible = true;
            }
            yield new Promise(resolve => setTimeout(resolve, 200));
            if ((_b = this.chartRef) === null || _b === void 0 ? void 0 : _b.nativeElement) {
                const canvas = this.chartRef.nativeElement;
                this.ctx = canvas.getContext('2d');
                switch (this.pChartOption.type) {
                    case 'pie':
                        this.renderPieChart(this.pChartOption);
                        break;
                    case 'bar':
                        this.renderBarChart(this.pChartOption);
                        break;
                    case 'horizontalBar':
                        this.renderHorizontalBarChart(this.pChartOption);
                        break;
                    case 'line':
                        this.renderLineChart(this.pChartOption);
                        break;
                    case 'stackArea':
                        this.renderStackAreaChart(this.pChartOption);
                        break;
                    case 'barline':
                        this.renderBarLineChart(this.pChartOption);
                        break;
                    case 'doughnut':
                        this.renderDoughnutChart(this.pChartOption);
                    default:
                        break;
                }
            }
        });
    }
    renderPieChart(option) {
        var _a, _b, _c;
        const configuration = {
            type: 'pie',
            options: {
                responsive: true,
                title: {
                    display: true,
                    text: option.title
                },
                legend: {
                    display: !option.hideLegend
                },
                tooltips: {
                    callbacks: {
                        label: (tooltipItem, data) => {
                            var _a, _b, _c;
                            const datasetLabel = (_a = data === null || data === void 0 ? void 0 : data.datasets[tooltipItem.datasetIndex]) === null || _a === void 0 ? void 0 : _a.label;
                            const label = data === null || data === void 0 ? void 0 : data.labels[tooltipItem.index];
                            const value = (_b = data === null || data === void 0 ? void 0 : data.datasets[tooltipItem.datasetIndex]) === null || _b === void 0 ? void 0 : _b.data[tooltipItem.index];
                            return ((_c = option.tooltips) === null || _c === void 0 ? void 0 : _c.label({
                                datasetLabel,
                                label,
                                value
                            })) || `${datasetLabel ? `[${datasetLabel}] ` : ''}${label} : ${Number.toVNCurrency(value)}`;
                        }
                    }
                }
            },
            data: {
                labels: ((_a = option.datasets) === null || _a === void 0 ? void 0 : _a.map(e => e.label)) || [],
                datasets: [{
                        data: ((_b = option.datasets) === null || _b === void 0 ? void 0 : _b.map(e => e.value)) || [],
                        backgroundColor: ((_c = option.datasets) === null || _c === void 0 ? void 0 : _c.map((e, idx) => {
                            var _a, _b, _c;
                            return e.backgroundColor
                                || ((_c = (_b = (_a = this.chartConfiguration) === null || _a === void 0 ? void 0 : _a.defaultColors) === null || _b === void 0 ? void 0 : _b[idx]) === null || _c === void 0 ? void 0 : _c.backgroundColor)
                                || this.dynamicColor;
                        })) || []
                    }]
            }
        };
        if (option.hover === 'ShowAll') {
            configuration.options.tooltips = Object.assign(Object.assign({}, configuration.options.tooltips), { mode: 'index', intersect: false });
            configuration.options.hover = Object.assign(Object.assign({}, configuration.options.hover), { mode: 'index', intersect: false });
        }
        this.chart = new Chart(this.ctx, configuration);
        this.isLoading = false;
    }
    renderDoughnutChart(option) {
        var _a, _b, _c;
        const configuration = {
            type: 'doughnut',
            options: {
                responsive: true,
                maintainAspectRatio: false,
                title: {
                    display: true,
                    text: option.title
                },
                legend: {
                    display: !option.hideLegend
                },
                tooltips: {
                    callbacks: {
                        label: (tooltipItem, data) => {
                            var _a, _b, _c;
                            const datasetLabel = (_a = data === null || data === void 0 ? void 0 : data.datasets[tooltipItem.datasetIndex]) === null || _a === void 0 ? void 0 : _a.label;
                            const label = data === null || data === void 0 ? void 0 : data.labels[tooltipItem.index];
                            const value = (_b = data === null || data === void 0 ? void 0 : data.datasets[tooltipItem.datasetIndex]) === null || _b === void 0 ? void 0 : _b.data[tooltipItem.index];
                            return ((_c = option.tooltips) === null || _c === void 0 ? void 0 : _c.label({
                                datasetLabel,
                                label,
                                value
                            })) || `${datasetLabel ? `[${datasetLabel}] ` : ''}${label} : ${Number.toVNCurrency(value)}`;
                        }
                    }
                }
            },
            data: {
                labels: ((_a = option.datasets) === null || _a === void 0 ? void 0 : _a.map(e => e.label)) || [],
                datasets: [{
                        data: ((_b = option.datasets) === null || _b === void 0 ? void 0 : _b.map(e => e.value)) || [],
                        backgroundColor: ((_c = option.datasets) === null || _c === void 0 ? void 0 : _c.map((e, idx) => {
                            var _a, _b, _c;
                            return e.backgroundColor
                                || ((_c = (_b = (_a = this.chartConfiguration) === null || _a === void 0 ? void 0 : _a.defaultColors) === null || _b === void 0 ? void 0 : _b[idx]) === null || _c === void 0 ? void 0 : _c.backgroundColor)
                                || this.dynamicColor;
                        })) || []
                    }]
            }
        };
        if (option.hover === 'ShowAll') {
            configuration.options.tooltips = Object.assign(Object.assign({}, configuration.options.tooltips), { mode: 'index', intersect: false });
            configuration.options.hover = Object.assign(Object.assign({}, configuration.options.hover), { mode: 'index', intersect: false });
        }
        this.chart = new Chart(this.ctx, configuration);
        this.isLoading = false;
    }
    renderBarChart(option) {
        var _a, _b;
        const labelWidth = (_a = option.labelWidth) !== null && _a !== void 0 ? _a : 50;
        if (option.datasets.length) {
            // const newwidth = Math.max(option.labels.length * option.datasets.length * labelWidth, $(this.chartWrapperRef.nativeElement).width());
            // $(this.chartAreaWrapperExtendRef.nativeElement).width(newwidth);
            const newwidth = option.labels.length * option.datasets.length * labelWidth;
            $(this.chartAreaWrapperExtendRef.nativeElement).css('width', `max(100%,${newwidth}px)`);
        }
        const configuration = {
            options: {
                responsive: true,
                maintainAspectRatio: false,
                legend: {
                    display: !option.hideLegend
                },
                scales: {
                    xAxes: [{
                            display: true,
                            scaleLabel: {
                                display: !!option.xTitle,
                                labelString: option.xTitle || ''
                            },
                            ticks: {
                                callback: (value, index) => {
                                    var _a;
                                    return ((_a = option.ticks) === null || _a === void 0 ? void 0 : _a.xLabel(value, index)) || (Number.isNumber(value) ? Number.toVNCurrency(value) : value);
                                }
                            }
                        }],
                    yAxes: [{
                            display: true,
                            ticks: {
                                beginAtZero: (_b = option.beginAtZero) !== null && _b !== void 0 ? _b : true,
                                callback: (value, index) => {
                                    var _a;
                                    return ((_a = option.ticks) === null || _a === void 0 ? void 0 : _a.yLabel(value, index)) || (Number.isNumber(value) ? Number.toVNCurrency(value) : value);
                                }
                            },
                            scaleLabel: {
                                display: !!option.yTitle,
                                labelString: option.yTitle || ''
                            }
                        }]
                },
                tooltips: {
                    callbacks: {
                        label: (tooltipItem, data) => {
                            var _a, _b, _c;
                            const datasetLabel = (_a = data === null || data === void 0 ? void 0 : data.datasets[tooltipItem.datasetIndex]) === null || _a === void 0 ? void 0 : _a.label;
                            const label = data === null || data === void 0 ? void 0 : data.labels[tooltipItem.index];
                            const value = (_b = data === null || data === void 0 ? void 0 : data.datasets[tooltipItem.datasetIndex]) === null || _b === void 0 ? void 0 : _b.data[tooltipItem.index];
                            return ((_c = option.tooltips) === null || _c === void 0 ? void 0 : _c.label({
                                datasetLabel,
                                label,
                                value
                            })) || `${datasetLabel} : ${Number.toVNCurrency(value)}`;
                        }
                    }
                }
            },
            type: 'bar',
            data: {
                labels: option.labels,
                datasets: option.datasets.map((e, idx) => {
                    var _a, _b, _c, _d, _e, _f;
                    const dynamicColor = this.dynamicColor;
                    const result = {
                        label: e.label,
                        fill: e.backgroundColor || ((_c = (_b = (_a = this.chartConfiguration) === null || _a === void 0 ? void 0 : _a.defaultColors) === null || _b === void 0 ? void 0 : _b[idx]) === null || _c === void 0 ? void 0 : _c.backgroundColor) || dynamicColor,
                        backgroundColor: e.backgroundColor || ((_f = (_e = (_d = this.chartConfiguration) === null || _d === void 0 ? void 0 : _d.defaultColors) === null || _e === void 0 ? void 0 : _e[idx]) === null || _f === void 0 ? void 0 : _f.backgroundColor) || dynamicColor,
                        data: e.data,
                        stack: e.stack
                    };
                    return result;
                })
            }
        };
        if (option.hover === 'ShowAll') {
            configuration.options.tooltips = Object.assign(Object.assign({}, configuration.options.tooltips), { mode: 'index', intersect: false });
            configuration.options.hover = Object.assign(Object.assign({}, configuration.options.hover), { mode: 'index', intersect: false });
        }
        this.chart = new Chart(this.ctx, configuration);
        this.isLoading = false;
    }
    renderHorizontalBarChart(option) {
        var _a;
        // const labelWidth = option.labelWidth ?? 50;
        // if (option.datasets.length) {
        //   const newwidth = Math.max(option.labels.length * option.datasets.length * labelWidth, $(this.chartWrapperRef.nativeElement).width());
        //   $(this.chartAreaWrapperExtendRef.nativeElement).width(newwidth);
        // }
        const plugins = [];
        if (option.showTotalStack) {
            plugins.push(__classPrivateFieldGet(this, _drawTotalOfStackedBar).call(this, option.type));
        }
        const configuration = {
            options: {
                responsive: true,
                maintainAspectRatio: false,
                legend: {
                    display: !option.hideLegend,
                    onClick: (event, legendItem) => {
                        let index = legendItem.datasetIndex;
                        let ci = this.chart;
                        let meta = ci.getDatasetMeta(index);
                        if (option.showTotalStack) {
                            event.stopPropagation();
                        }
                        else {
                            // See controller.isDatasetVisible comment
                            meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null;
                            // We hid a dataset ... rerender the chart
                            ci.update();
                        }
                    },
                },
                layout: {
                    padding: {
                        right: 20
                    }
                },
                scales: {
                    xAxes: [{
                            display: true,
                            scaleLabel: {
                                display: !!option.xTitle,
                                labelString: option.xTitle || '',
                            },
                            stacked: true,
                            ticks: {
                                beginAtZero: (_a = option.beginAtZero) !== null && _a !== void 0 ? _a : true,
                                callback: (value, index) => {
                                    var _a;
                                    return ((_a = option.ticks) === null || _a === void 0 ? void 0 : _a.xLabel(value, index)) || (Number.isNumber(value) ? Number.toVNCurrency(value) : value);
                                }
                            },
                        }],
                    yAxes: [{
                            display: true,
                            stacked: true,
                            ticks: {
                                callback: (value, index) => {
                                    var _a;
                                    return ((_a = option.ticks) === null || _a === void 0 ? void 0 : _a.yLabel(value, index)) || (Number.isNumber(value) ? Number.toVNCurrency(value) : value);
                                }
                            },
                            scaleLabel: {
                                display: !!option.yTitle,
                                labelString: option.yTitle || ''
                            }
                        }]
                },
                tooltips: {
                    mode: 'nearest',
                    axis: 'y',
                    callbacks: {
                        label: (tooltipItem, data) => {
                            var _a, _b, _c;
                            const datasetLabel = (_a = data === null || data === void 0 ? void 0 : data.datasets[tooltipItem.datasetIndex]) === null || _a === void 0 ? void 0 : _a.label;
                            const label = data === null || data === void 0 ? void 0 : data.labels[tooltipItem.index];
                            const value = (_b = data === null || data === void 0 ? void 0 : data.datasets[tooltipItem.datasetIndex]) === null || _b === void 0 ? void 0 : _b.data[tooltipItem.index];
                            return ((_c = option.tooltips) === null || _c === void 0 ? void 0 : _c.label({
                                datasetLabel,
                                label,
                                value
                            })) || `${datasetLabel} : ${Number.toVNCurrency(value)}`;
                        }
                    }
                }
            },
            type: 'horizontalBar',
            data: {
                labels: option.labels,
                datasets: option.datasets.map((e, idx) => {
                    var _a, _b, _c, _d, _e, _f;
                    const dynamicColor = this.dynamicColor;
                    const result = {
                        label: e.label,
                        fill: e.backgroundColor || ((_c = (_b = (_a = this.chartConfiguration) === null || _a === void 0 ? void 0 : _a.defaultColors) === null || _b === void 0 ? void 0 : _b[idx]) === null || _c === void 0 ? void 0 : _c.backgroundColor) || dynamicColor,
                        backgroundColor: e.backgroundColor || ((_f = (_e = (_d = this.chartConfiguration) === null || _d === void 0 ? void 0 : _d.defaultColors) === null || _e === void 0 ? void 0 : _e[idx]) === null || _f === void 0 ? void 0 : _f.backgroundColor) || dynamicColor,
                        data: e.data,
                        stack: e.stack
                    };
                    return result;
                })
            },
            plugins: plugins
        };
        if (option.hover === 'ShowAll') {
            configuration.options.tooltips = Object.assign(Object.assign({}, configuration.options.tooltips), { mode: 'index', intersect: false });
            configuration.options.hover = Object.assign(Object.assign({}, configuration.options.hover), { mode: 'index', intersect: false });
        }
        this.chart = new Chart(this.ctx, configuration);
        this.isLoading = false;
    }
    renderLineChart(option) {
        var _a, _b;
        const labelWidth = (_a = option.labelWidth) !== null && _a !== void 0 ? _a : 50;
        if (option.datasets.length) {
            // const newwidth = Math.max(option.labels.length * labelWidth, $(this.chartWrapperRef.nativeElement).width());
            // $(this.chartAreaWrapperExtendRef.nativeElement).width(newwidth);
            const newwidth = option.labels.length * labelWidth;
            $(this.chartAreaWrapperExtendRef.nativeElement).css('width', `max(100%,${newwidth}px)`);
        }
        const configuration = {
            options: {
                responsive: true,
                maintainAspectRatio: false,
                legend: {
                    display: !option.hideLegend
                },
                scales: {
                    xAxes: [{
                            display: true,
                            scaleLabel: {
                                display: !!option.xTitle,
                                labelString: option.xTitle || ''
                            },
                            ticks: {
                                callback: (value, index) => {
                                    var _a;
                                    return ((_a = option.ticks) === null || _a === void 0 ? void 0 : _a.xLabel(value, index)) || (Number.isNumber(value) ? Number.toVNCurrency(value) : value);
                                }
                            },
                        }],
                    yAxes: [{
                            display: true,
                            ticks: {
                                beginAtZero: (_b = option.beginAtZero) !== null && _b !== void 0 ? _b : true,
                                callback: (value, index) => {
                                    var _a;
                                    return ((_a = option.ticks) === null || _a === void 0 ? void 0 : _a.yLabel(value, index)) || (Number.isNumber(value) ? Number.toVNCurrency(value) : value);
                                }
                            },
                            scaleLabel: {
                                display: !!option.yTitle,
                                labelString: option.yTitle || ''
                            }
                        }]
                },
                tooltips: {
                    callbacks: {
                        label: (tooltipItem, data) => {
                            var _a, _b, _c;
                            const datasetLabel = (_a = data === null || data === void 0 ? void 0 : data.datasets[tooltipItem.datasetIndex]) === null || _a === void 0 ? void 0 : _a.label;
                            const label = data === null || data === void 0 ? void 0 : data.labels[tooltipItem.index];
                            const value = (_b = data === null || data === void 0 ? void 0 : data.datasets[tooltipItem.datasetIndex]) === null || _b === void 0 ? void 0 : _b.data[tooltipItem.index];
                            return ((_c = option.tooltips) === null || _c === void 0 ? void 0 : _c.label({
                                datasetLabel,
                                label,
                                value
                            })) || `${datasetLabel} : ${Number.toVNCurrency(value)}`;
                        }
                    }
                }
            },
            type: 'line',
            data: {
                labels: option.labels,
                datasets: option.datasets.map((e, idx) => {
                    var _a, _b, _c, _d, _e, _f, _g, _h, _j;
                    const dynamicColor = this.dynamicColor;
                    const result = {
                        label: e.label,
                        fill: e.backgroundColor || ((_c = (_b = (_a = this.chartConfiguration) === null || _a === void 0 ? void 0 : _a.defaultColors) === null || _b === void 0 ? void 0 : _b[idx]) === null || _c === void 0 ? void 0 : _c.backgroundColor) || dynamicColor,
                        backgroundColor: e.backgroundColor || ((_f = (_e = (_d = this.chartConfiguration) === null || _d === void 0 ? void 0 : _d.defaultColors) === null || _e === void 0 ? void 0 : _e[idx]) === null || _f === void 0 ? void 0 : _f.backgroundColor) || dynamicColor,
                        borderColor: e.borderColor || ((_j = (_h = (_g = this.chartConfiguration) === null || _g === void 0 ? void 0 : _g.defaultColors) === null || _h === void 0 ? void 0 : _h[idx]) === null || _j === void 0 ? void 0 : _j.borderColor) || dynamicColor,
                        data: e.data,
                        lineTension: 0,
                    };
                    return result;
                })
            }
        };
        if (option.hover === 'ShowAll') {
            configuration.options.tooltips = Object.assign(Object.assign({}, configuration.options.tooltips), { mode: 'index', intersect: false });
            configuration.options.hover = Object.assign(Object.assign({}, configuration.options.hover), { mode: 'index', intersect: false });
        }
        this.chart = new Chart(this.ctx, configuration);
        this.isLoading = false;
    }
    renderStackAreaChart(option) {
        var _a, _b;
        const labelWidth = (_a = option.labelWidth) !== null && _a !== void 0 ? _a : 50;
        if (option.datasets.length) {
            // const newwidth = Math.max(option.labels.length * labelWidth, $(this.chartWrapperRef.nativeElement).width());
            // $(this.chartAreaWrapperExtendRef.nativeElement).width(newwidth);
            const newwidth = option.labels.length * labelWidth;
            $(this.chartAreaWrapperExtendRef.nativeElement).css('width', `max(100%,${newwidth}px)`);
        }
        const configuration = {
            options: {
                responsive: true,
                maintainAspectRatio: false,
                legend: {
                    display: !option.hideLegend
                },
                scales: {
                    xAxes: [{
                            display: true,
                            scaleLabel: {
                                display: !!option.xTitle,
                                labelString: option.xTitle || ''
                            },
                            ticks: {
                                callback: (value, index) => {
                                    var _a;
                                    return ((_a = option.ticks) === null || _a === void 0 ? void 0 : _a.xLabel(value, index)) || (Number.isNumber(value) ? Number.toVNCurrency(value) : value);
                                }
                            },
                        }],
                    yAxes: [{
                            display: true,
                            ticks: {
                                beginAtZero: (_b = option.beginAtZero) !== null && _b !== void 0 ? _b : true,
                                callback: (value, index) => {
                                    var _a;
                                    return ((_a = option.ticks) === null || _a === void 0 ? void 0 : _a.yLabel(value, index)) || (Number.isNumber(value) ? Number.toVNCurrency(value) : value);
                                }
                            },
                            stacked: true,
                            scaleLabel: {
                                display: !!option.yTitle,
                                labelString: option.yTitle || ''
                            }
                        }]
                },
                tooltips: {
                    callbacks: {
                        label: (tooltipItem, data) => {
                            var _a, _b, _c;
                            const datasetLabel = (_a = data === null || data === void 0 ? void 0 : data.datasets[tooltipItem.datasetIndex]) === null || _a === void 0 ? void 0 : _a.label;
                            const label = data === null || data === void 0 ? void 0 : data.labels[tooltipItem.index];
                            const value = (_b = data === null || data === void 0 ? void 0 : data.datasets[tooltipItem.datasetIndex]) === null || _b === void 0 ? void 0 : _b.data[tooltipItem.index];
                            return ((_c = option.tooltips) === null || _c === void 0 ? void 0 : _c.label({
                                datasetLabel,
                                label,
                                value
                            })) || `${datasetLabel} : ${Number.toVNCurrency(value)}`;
                        }
                    }
                }
            },
            type: 'line',
            data: {
                labels: option.labels,
                datasets: option.datasets.map((e, idx) => {
                    var _a, _b, _c, _d, _e, _f;
                    const dynamicColor = this.dynamicColor;
                    const result = {
                        label: e.label,
                        // fill: e.backgroundColor,
                        backgroundColor: e.backgroundColor || ((_c = (_b = (_a = this.chartConfiguration) === null || _a === void 0 ? void 0 : _a.defaultColors) === null || _b === void 0 ? void 0 : _b[idx]) === null || _c === void 0 ? void 0 : _c.backgroundColor) || dynamicColor,
                        borderColor: e.borderColor || ((_f = (_e = (_d = this.chartConfiguration) === null || _d === void 0 ? void 0 : _d.defaultColors) === null || _e === void 0 ? void 0 : _e[idx]) === null || _f === void 0 ? void 0 : _f.borderColor) || dynamicColor,
                        data: e.data,
                        lineTension: 0,
                    };
                    return result;
                })
            }
        };
        if (option.hover === 'ShowAll') {
            configuration.options.tooltips = Object.assign(Object.assign({}, configuration.options.tooltips), { mode: 'index', intersect: false });
            configuration.options.hover = Object.assign(Object.assign({}, configuration.options.hover), { mode: 'index', intersect: false });
        }
        this.chart = new Chart(this.ctx, configuration);
        this.isLoading = false;
    }
    renderBarLineChart(option) {
        var _a, _b, _c, _d;
        const plugins = [];
        if (option.showTotalStack) {
            plugins.push(__classPrivateFieldGet(this, _drawTotalOfStackedBar).call(this, option.type));
        }
        const labelWidth = (_a = option.labelWidth) !== null && _a !== void 0 ? _a : 50;
        if (option.datasets.length) {
            const numberOfBars = option.datasets.filter(e => e.type === 'bar').length;
            if (numberOfBars <= 1) {
                // const newwidth = Math.max(option.labels.length * labelWidth, $(this.chartWrapperRef.nativeElement).width());
                // $(this.chartAreaWrapperExtendRef.nativeElement).width(newwidth);
                const newwidth = option.labels.length * labelWidth;
                $(this.chartAreaWrapperExtendRef.nativeElement).css('width', `max(100%,${newwidth}px)`);
            }
            else {
                // const newwidth = Math.max(option.labels.length * numberOfBars * labelWidth, $(this.chartWrapperRef.nativeElement).width());
                // $(this.chartAreaWrapperExtendRef.nativeElement).width(newwidth);
                const newwidth = option.labels.length * numberOfBars * labelWidth;
                $(this.chartAreaWrapperExtendRef.nativeElement).css('width', `max(100%,${newwidth}px)`);
            }
        }
        const leftId = `I${v4()}`;
        const rightId = `I${v4()}`;
        const yAxes = [{
                type: 'linear',
                display: true,
                position: 'left',
                id: leftId,
                ticks: {
                    beginAtZero: (_b = option.beginAtZero) !== null && _b !== void 0 ? _b : true,
                    suggestedMin: 0,
                    callback: (value, index) => {
                        var _a;
                        return ((_a = option.ticks) === null || _a === void 0 ? void 0 : _a.yLabel(value, index)) || (Number.isNumber(value) ? Number.toVNCurrency(value) : value);
                    }
                },
                scaleLabel: {
                    display: !!option.yTitle,
                    labelString: option.yTitle || '',
                },
                stacked: !!option.yStacked,
            }];
        if (option.datasets.some(e => e.yAlign === 'right')) {
            yAxes.push({
                type: 'linear',
                display: true,
                position: 'right',
                id: rightId,
                ticks: {
                    beginAtZero: (_c = option.beginAtZero) !== null && _c !== void 0 ? _c : true,
                    suggestedMin: 0,
                    callback: (value, index) => {
                        var _a;
                        return ((_a = option.ticks) === null || _a === void 0 ? void 0 : _a.yRightLabel(value, index)) || (Number.isNumber(value) ? Number.toVNCurrency(value) : value);
                    }
                },
                scaleLabel: {
                    display: !!option.yRightTitle,
                    labelString: option.yRightTitle || ''
                },
                stacked: !!option.yStacked,
            });
        }
        const configuration = {
            options: {
                responsive: true,
                maintainAspectRatio: false,
                legend: {
                    display: !option.hideLegend,
                    onClick: (event, legendItem) => {
                        let index = legendItem.datasetIndex;
                        let ci = this.chart;
                        let meta = ci.getDatasetMeta(index);
                        if (option.showTotalStack) {
                            event.stopPropagation();
                        }
                        else {
                            // See controller.isDatasetVisible comment
                            meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null;
                            // We hid a dataset ... rerender the chart
                            ci.update();
                        }
                    },
                    position: (_d = option === null || option === void 0 ? void 0 : option.legendPosition) !== null && _d !== void 0 ? _d : 'top'
                },
                layout: {
                    padding: 10
                },
                title: {
                    display: true,
                    text: option.title
                },
                scales: {
                    xAxes: [{
                            display: true,
                            scaleLabel: {
                                display: !!option.xTitle,
                                labelString: option.xTitle || ''
                            },
                            ticks: {
                                callback: (value, index) => {
                                    var _a;
                                    return ((_a = option.ticks) === null || _a === void 0 ? void 0 : _a.xLabel(value, index)) || (Number.isNumber(value) ? Number.toVNCurrency(value) : value);
                                }
                            },
                            stacked: !!option.xStacked
                        }],
                    yAxes
                },
                tooltips: {
                    callbacks: {
                        label: (tooltipItem, data) => {
                            var _a, _b, _c;
                            const datasetLabel = (_a = data === null || data === void 0 ? void 0 : data.datasets[tooltipItem.datasetIndex]) === null || _a === void 0 ? void 0 : _a.label;
                            const label = data === null || data === void 0 ? void 0 : data.labels[tooltipItem.index];
                            const value = (_b = data === null || data === void 0 ? void 0 : data.datasets[tooltipItem.datasetIndex]) === null || _b === void 0 ? void 0 : _b.data[tooltipItem.index];
                            return ((_c = option.tooltips) === null || _c === void 0 ? void 0 : _c.label({
                                datasetLabel,
                                label,
                                value,
                                datasetIndex: tooltipItem.datasetIndex,
                                dataIndex: tooltipItem.index
                            })) || `${datasetLabel ? `[${datasetLabel}] ` : ''} ${label} : ${Number.toVNCurrency(value)}`;
                        }
                    }
                }
            },
            data: {
                labels: option.labels,
                datasets: option.datasets.map((e, idx) => {
                    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
                    const dynamicColor = this.dynamicColor;
                    const result = {
                        type: e.type,
                        label: e.label,
                        fill: e.backgroundColor || ((_c = (_b = (_a = this.chartConfiguration) === null || _a === void 0 ? void 0 : _a.defaultColors) === null || _b === void 0 ? void 0 : _b[idx]) === null || _c === void 0 ? void 0 : _c.backgroundColor) || dynamicColor,
                        backgroundColor: e.backgroundColor || ((_f = (_e = (_d = this.chartConfiguration) === null || _d === void 0 ? void 0 : _d.defaultColors) === null || _e === void 0 ? void 0 : _e[idx]) === null || _f === void 0 ? void 0 : _f.backgroundColor) || dynamicColor,
                        borderColor: e.borderColor || ((_j = (_h = (_g = this.chartConfiguration) === null || _g === void 0 ? void 0 : _g.defaultColors) === null || _h === void 0 ? void 0 : _h[idx]) === null || _j === void 0 ? void 0 : _j.borderColor) || dynamicColor,
                        data: e.data,
                        yAxisID: e.yAlign === 'right' ? rightId : leftId,
                        lineTension: 0,
                        order: (_k = e.order) !== null && _k !== void 0 ? _k : 1
                    };
                    return result;
                }),
            },
            plugins: plugins
        };
        if (option.hover === 'ShowAll') {
            configuration.options.tooltips = Object.assign(Object.assign({}, configuration.options.tooltips), { mode: 'index', intersect: false });
            configuration.options.hover = Object.assign(Object.assign({}, configuration.options.hover), { mode: 'index', intersect: false });
        }
        this.chart = new Chart(this.ctx, configuration);
        this.isLoading = false;
    }
    get dynamicColor() {
        const r = Math.floor(Math.random() * 255);
        const g = Math.floor(Math.random() * 255);
        const b = Math.floor(Math.random() * 255);
        return 'rgb(' + r + ',' + g + ',' + b + ')';
    }
}
_drawTotalOfStackedBar = new WeakMap();
SdChart.decorators = [
    { type: Component, args: [{
                selector: 'sd-chart',
                template: "<div *ngIf=\"visible\" class=\"c-chart-wrapper mt-2\" >\r\n  <div class=\"c-chart-area-wrapper\" #chartWrapper>\r\n    <div class=\"c-chart-area-wrapper-extend position-relative\" [ngStyle]=\"{'height':height}\" #chartAreaWrapperExtend [ngClass]=\"{'c-loading': isLoading}\">\r\n      <i [ngClass]=\"{'d-none': !isLoading}\" class=\"fa fa-5x fa-spinner fa-pulse c-loading-icon\"></i>\r\n      <canvas #chart [ngClass]=\"{'c-loading-margin': isLoading}\"></canvas>\r\n    </div>\r\n  </div>\r\n</div>\r\n",
                styles: [".c-container{background:#f5f6f7;border-radius:5px}.c-flex{border-radius:8px;display:flex;margin:15px}.c-chart-container{background:#fff;border-radius:5px;border-radius:8px;box-shadow:0 0 13px 0 rgba(82,63,105,.1);margin:15px;padding:15px}.c-btn-dashboard{align-self:center;height:60%;vertical-align:middle}.c-chart-wrapper{position:relative}.c-chart-wrapper>canvas{left:0;pointer-events:none;position:absolute;top:0}.c-chart-area-wrapper{overflow-x:auto;position:relative;width:100%}.c-chart-area-wrapper-extend{position:relative}.c-loading{opacity:.4}.c-loading-icon{left:calc(50% - 2.5rem);position:-webkit-sticky;position:sticky;top:calc(50% - 2.5rem)}.c-loading-margin{margin-top:-6rem}::-webkit-scrollbar{height:7px;width:7px}::-webkit-scrollbar-track{background:#f1f1f1}::-webkit-scrollbar-thumb{background:#888;border-radius:50px}::-webkit-scrollbar-thumb:hover{background:#555}"]
            },] }
];
SdChart.ctorParameters = () => [
    { type: ChangeDetectorRef },
    { type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [CHART_CONFIG,] }] }
];
SdChart.propDecorators = {
    chartOption: [{ type: Input }],
    chartRef: [{ type: ViewChild, args: ['chart',] }],
    chartWrapperRef: [{ type: ViewChild, args: ['chartWrapper',] }],
    chartAxisRef: [{ type: ViewChild, args: ['chartAxis',] }],
    chartAreaWrapperExtendRef: [{ type: ViewChild, args: ['chartAreaWrapperExtend',] }]
};

class SdChartModule {
}
SdChartModule.decorators = [
    { type: NgModule, args: [{
                imports: [
                    CommonModule
                ],
                declarations: [
                    SdChart
                ],
                exports: [
                    SdChart
                ],
                providers: []
            },] }
];

/**
 * Generated bundle index. Do not edit.
 */

export { CHART_CONFIG, ChartColors, SdChart, SdChartModule };
//# sourceMappingURL=sd-angular-core-chart.js.map
