import * as i1$1 from '@angular/common';
import { CommonModule } from '@angular/common';
import * as i0 from '@angular/core';
import { Injectable, Optional, inject, ElementRef, DestroyRef, Injector, input, computed, afterNextRender, runInInjectionContext, effect, Directive, output, Component, ChangeDetectionStrategy } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import * as i1 from '@metad/ocap-angular/core';
import { NgmLanguageEnum, NgmIsNilPipe } from '@metad/ocap-angular/core';
import * as i2 from '@metad/ocap-core';
import { SmartIndicatorDataService, PeriodFunctions, isNumber, IndicatorTagEnum, TimeGranularity } from '@metad/ocap-core';
import { combineLatest, map, startWith } from 'rxjs';
import { TinyArea } from '@antv/g2plot/esm/plots/tiny-area';
import { TranslateService } from '@ngx-translate/core';

var Trend;
(function (Trend) {
    Trend[Trend["None"] = 0] = "None";
    Trend[Trend["Up"] = 1] = "Up";
    Trend[Trend["Down"] = 2] = "Down";
})(Trend || (Trend = {}));
var TrendColor;
(function (TrendColor) {
    TrendColor["None"] = "#40A9FF";
    TrendColor["Up"] = "#31c75a";
    TrendColor["Down"] = "#fe3c2e";
})(TrendColor || (TrendColor = {}));
var TrendReverseColor;
(function (TrendReverseColor) {
    TrendReverseColor["None"] = "#40A9FF";
    TrendReverseColor["Down"] = "#31c75a";
    TrendReverseColor["Up"] = "#fe3c2e";
})(TrendReverseColor || (TrendReverseColor = {}));
var StatisticalType;
(function (StatisticalType) {
    StatisticalType["CurrentPeriod"] = "CurrentPeriod";
    StatisticalType["Accumulative"] = "Accumulative";
    StatisticalType["Yoy"] = "Yoy";
    StatisticalType["Mom"] = "Mom";
})(StatisticalType || (StatisticalType = {}));

class NgmIndicatorService extends SmartIndicatorDataService {
    constructor(dsCoreService, smartFilterBar) {
        super(dsCoreService, smartFilterBar);
    }
    selectQuery(options) {
        const lookBack = this.get((state) => state.lookBack);
        return combineLatest([
            super.selectQuery(options, null, [PeriodFunctions.CURRENT, PeriodFunctions.MOM, PeriodFunctions.YOY, PeriodFunctions.YTD], 0),
            super.selectQuery(options, null, [PeriodFunctions.CURRENT], lookBack ?? 1)
        ]).pipe(map(([current, trends]) => {
            if (current.error || trends.error) {
                return {
                    indicator: this.indicator,
                    error: `${(current.error ?? '').trim()}\n${(trends.error ?? '').trim()}`.trim()
                };
            }
            const items = trends.data?.filter((item) => isNumber(item.CURRENT));
            const start = items[0]?.CURRENT;
            const end = items[items.length - 1]?.CURRENT;
            return {
                indicator: this.indicator,
                trends: trends.data,
                data: current.data?.[0],
                trend: start > end ? Trend.Down : start < end ? Trend.Up : Trend.None
            };
        }));
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: NgmIndicatorService, deps: [{ token: i1.NgmDSCoreService }, { token: i2.SmartFilterBarService, optional: true }], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: NgmIndicatorService }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: NgmIndicatorService, decorators: [{
            type: Injectable
        }], ctorParameters: () => [{ type: i1.NgmDSCoreService }, { type: i2.SmartFilterBarService, decorators: [{
                    type: Optional
                }] }] });

class NgmSparkLineDirective {
    #elementRef;
    #injector;
    #translate;
    constructor() {
        this.#elementRef = inject(ElementRef);
        this.destroyRef = inject(DestroyRef);
        this.#injector = inject(Injector);
        this.#translate = inject(TranslateService);
        this.indicator = input.required();
        this.trend = input();
        this.trends = input();
        this.statisticalType = input(StatisticalType.CurrentPeriod);
        this.primaryTheme = input();
        this.config$ = computed(() => {
            const trends = this.trends();
            const measureFilter = this.statisticalType();
            let data = [];
            switch (measureFilter) {
                case StatisticalType.CurrentPeriod:
                    data = trends?.map((y) => y['CURRENT']) || [];
                    break;
                case StatisticalType.Accumulative:
                    data = trends?.map((y) => y['YTD']) || [];
                    break;
            }
            const color = this.#translate.currentLang === NgmLanguageEnum.SimplifiedChinese
                ? TrendReverseColor[Trend[this.trend()]]
                : TrendColor[Trend[this.trend()]];
            return {
                data,
                color
            };
        });
        afterNextRender(() => {
            const tinyArea = new TinyArea(this.#elementRef.nativeElement, {
                animation: false,
                autoFit: true,
                data: [],
                smooth: false,
                line: {
                    size: 2
                },
                tooltip: false
            });
            tinyArea.render();
            runInInjectionContext(this.#injector, () => {
                effect(() => {
                    const { data, color } = this.config$();
                    tinyArea.changeData(data);
                    tinyArea.update({
                        line: {
                            color: color
                        },
                        areaStyle: {
                            fill: `l(270) 0:${color}00 1:${color}${this.primaryTheme() === 'dark' ? '' : '70'}`
                        },
                        annotations: [
                            {
                                type: 'line',
                                start: ['min', 'mean'],
                                end: ['max', 'mean'],
                                // text: {
                                //   content: '平均值',
                                //   offsetY: -2,
                                //   style: {
                                //     textAlign: 'left',
                                //     fontSize: 10,
                                //     fill: 'rgba(44, 53, 66, 0.45)',
                                //     textBaseline: 'bottom',
                                //   },
                                // },
                                style: {
                                    lineWidth: 2,
                                    lineDash: [2, 2],
                                    stroke: color
                                }
                            }
                        ]
                    });
                });
            });
        });
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: NgmSparkLineDirective, deps: [], target: i0.ɵɵFactoryTarget.Directive }); }
    static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "17.3.12", type: NgmSparkLineDirective, isStandalone: true, selector: "[ngmSparkLine]", inputs: { indicator: { classPropertyName: "indicator", publicName: "indicator", isSignal: true, isRequired: true, transformFunction: null }, trend: { classPropertyName: "trend", publicName: "trend", isSignal: true, isRequired: false, transformFunction: null }, trends: { classPropertyName: "trends", publicName: "trends", isSignal: true, isRequired: false, transformFunction: null }, statisticalType: { classPropertyName: "statisticalType", publicName: "statisticalType", isSignal: true, isRequired: false, transformFunction: null }, primaryTheme: { classPropertyName: "primaryTheme", publicName: "primaryTheme", isSignal: true, isRequired: false, transformFunction: null } }, ngImport: i0 }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: NgmSparkLineDirective, decorators: [{
            type: Directive,
            args: [{
                    standalone: true,
                    selector: '[ngmSparkLine]'
                }]
        }], ctorParameters: () => [] });

class NgmIndicatorComponent {
    constructor() {
        this.statisticalType = StatisticalType.CurrentPeriod;
        this.TREND = Trend;
        this.TagEnum = IndicatorTagEnum;
        this.dataService = inject(NgmIndicatorService);
        // Inputs
        this.dataSettings = input.required();
        this.indicatorCode = input.required();
        this.lookBack = input.required();
        this.primaryTheme = input();
        this.tagType = input(IndicatorTagEnum.MOM);
        this.timeGranularity = input(TimeGranularity.Day);
        // Outputs
        this.toggleTag = output();
        this.initied = toSignal(this.dataService.onAfterServiceInit().pipe(map(() => true), startWith(false)));
        this.loading = toSignal(this.dataService.loading$);
        this.indicator = computed(() => {
            const code = this.indicatorCode();
            if (code && this.initied()) {
                return this.dataService.getIndicator(code);
            }
            return null;
        });
        this.data = toSignal(this.dataService.selectResult());
        this.main = computed(() => this.data()?.data);
        this.trend = computed(() => this.data()?.trend);
        this.trends = computed(() => this.data()?.trends);
        effect(() => {
            // console.log(this.indicator(), this.data())
        });
        effect(() => {
            if (this.dataSettings()) {
                this.dataService.dataSettings = this.dataSettings();
            }
        });
        effect(() => {
            if (this.timeGranularity()) {
                this.dataService.timeGranularity = this.timeGranularity();
            }
        });
        effect(() => {
            this.dataService.patchState({
                indicatorId: this.indicatorCode(),
                lookBack: this.lookBack()
            });
            if (this.initied()) {
                this.dataService.refresh();
            }
        }, { allowSignalWrites: true });
    }
    _toggleTag(event) {
        event.stopPropagation();
        event.preventDefault();
        this.toggleTag.emit();
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: NgmIndicatorComponent, deps: [], target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "17.3.12", type: NgmIndicatorComponent, isStandalone: true, selector: "ngm-indicator", inputs: { dataSettings: { classPropertyName: "dataSettings", publicName: "dataSettings", isSignal: true, isRequired: true, transformFunction: null }, indicatorCode: { classPropertyName: "indicatorCode", publicName: "indicatorCode", isSignal: true, isRequired: true, transformFunction: null }, lookBack: { classPropertyName: "lookBack", publicName: "lookBack", isSignal: true, isRequired: true, transformFunction: null }, primaryTheme: { classPropertyName: "primaryTheme", publicName: "primaryTheme", isSignal: true, isRequired: false, transformFunction: null }, tagType: { classPropertyName: "tagType", publicName: "tagType", isSignal: true, isRequired: false, transformFunction: null }, timeGranularity: { classPropertyName: "timeGranularity", publicName: "timeGranularity", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { toggleTag: "toggleTag" }, providers: [NgmIndicatorService], ngImport: i0, template: "@if (indicator(); as indicator) {\n  <div class=\"pac-item-meta flex-1 flex flex-col overflow-hidden\"\n    [class.text-gray-500]=\"loading()\"\n  >\n    <div class=\"pac-item-meta-title text-lg flex justify-start items-center overflow-hidden\">\n      <span class=\"flex-1 font-semibold whitespace-nowrap text-ellipsis overflow-hidden\">{{ indicator.code }}</span>\n    </div>\n    <div class=\"pac-item-meta-description text-base\">\n      <span>{{ indicator.name }}</span>\n    </div>\n  </div>\n\n  <div class=\"w-28 h-12 px-2\" ngmSparkLine [indicator]=\"indicator\" [statisticalType]=\"statisticalType\"\n    [trend]=\"trend()\"\n    [trends]=\"trends()\"\n  ></div>\n\n\n  <div class=\"w-16 flex flex-col justify-around items-end z-10\">\n    <div>\n      @if (indicator.unit === '%') {\n        <span>\n          {{ main()?.CURRENT * 100 | number:'0.0-2' | isNil:'-' }}\n        </span>\n      } @else {\n        <span>\n          {{ main()?.CURRENT | number:'0.0-2' | isNil:'-' }}\n        </span>\n      }\n    </div>\n\n    <div (click)=\"_toggleTag($event)\" class=\"pac-indicator__tag text-sm bg-gray-500 bg-opacity-25\"\n      [ngClass]=\"{'Trend-Up': trend() === TREND.Up, 'Trend-Down': trend() === TREND.Down}\"\n    >\n      @switch (tagType()) {\n        @case(TagEnum.UNIT) {\n          <span>\n            {{ indicator.unit }}\n          </span>\n        }\n        @case(TagEnum.MOM) {\n          <span>\n            {{ main()?.MOM | percent:'0.2-2' }}\n          </span>\n        }\n        @case(TagEnum.YOY) {\n          <span>\n            {{ main()?.YOY | percent:'0.2-2' }}\n          </span>\n        }\n      }\n    </div>\n\n  </div>\n}", styles: [":host{display:flex;justify-content:flex-start;padding-left:1rem;padding-right:1rem;color:var(--color-text-primary)}.pac-indicator__tag{width:60px;text-align:right;border-radius:5px;padding:0 5px;cursor:pointer}.pac-indicator__tag.Trend-Up{background-color:#31c75a;color:#fff}.pac-indicator__tag.Trend-Down{background-color:#fe3c2e;color:#fff}.Trend-Up{color:#31c75a}.Trend-Down{color:#fe3c2e}:host.reverse-semantic-color .Trend-Up{color:#fe3c2e}:host.reverse-semantic-color .Trend-Down{color:#31c75a}:host.reverse-semantic-color .pac-indicator__tag.Trend-Up{background-color:#fe3c2e;--tw-text-opacity: 1;color:rgb(245 245 245 / var(--tw-text-opacity))}:host.reverse-semantic-color .pac-indicator__tag.Trend-Down{background-color:#31c75a;--tw-text-opacity: 1;color:rgb(245 245 245 / var(--tw-text-opacity))}\n"], dependencies: [{ kind: "ngmodule", type: CommonModule }, { kind: "directive", type: i1$1.NgClass, selector: "[ngClass]", inputs: ["class", "ngClass"] }, { kind: "pipe", type: i1$1.DecimalPipe, name: "number" }, { kind: "pipe", type: i1$1.PercentPipe, name: "percent" }, { kind: "directive", type: NgmSparkLineDirective, selector: "[ngmSparkLine]", inputs: ["indicator", "trend", "trends", "statisticalType", "primaryTheme"] }, { kind: "pipe", type: NgmIsNilPipe, name: "isNil" }], changeDetection: i0.ChangeDetectionStrategy.OnPush }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: NgmIndicatorComponent, decorators: [{
            type: Component,
            args: [{ standalone: true, changeDetection: ChangeDetectionStrategy.OnPush, selector: 'ngm-indicator', providers: [NgmIndicatorService], imports: [CommonModule, NgmSparkLineDirective, NgmIsNilPipe], template: "@if (indicator(); as indicator) {\n  <div class=\"pac-item-meta flex-1 flex flex-col overflow-hidden\"\n    [class.text-gray-500]=\"loading()\"\n  >\n    <div class=\"pac-item-meta-title text-lg flex justify-start items-center overflow-hidden\">\n      <span class=\"flex-1 font-semibold whitespace-nowrap text-ellipsis overflow-hidden\">{{ indicator.code }}</span>\n    </div>\n    <div class=\"pac-item-meta-description text-base\">\n      <span>{{ indicator.name }}</span>\n    </div>\n  </div>\n\n  <div class=\"w-28 h-12 px-2\" ngmSparkLine [indicator]=\"indicator\" [statisticalType]=\"statisticalType\"\n    [trend]=\"trend()\"\n    [trends]=\"trends()\"\n  ></div>\n\n\n  <div class=\"w-16 flex flex-col justify-around items-end z-10\">\n    <div>\n      @if (indicator.unit === '%') {\n        <span>\n          {{ main()?.CURRENT * 100 | number:'0.0-2' | isNil:'-' }}\n        </span>\n      } @else {\n        <span>\n          {{ main()?.CURRENT | number:'0.0-2' | isNil:'-' }}\n        </span>\n      }\n    </div>\n\n    <div (click)=\"_toggleTag($event)\" class=\"pac-indicator__tag text-sm bg-gray-500 bg-opacity-25\"\n      [ngClass]=\"{'Trend-Up': trend() === TREND.Up, 'Trend-Down': trend() === TREND.Down}\"\n    >\n      @switch (tagType()) {\n        @case(TagEnum.UNIT) {\n          <span>\n            {{ indicator.unit }}\n          </span>\n        }\n        @case(TagEnum.MOM) {\n          <span>\n            {{ main()?.MOM | percent:'0.2-2' }}\n          </span>\n        }\n        @case(TagEnum.YOY) {\n          <span>\n            {{ main()?.YOY | percent:'0.2-2' }}\n          </span>\n        }\n      }\n    </div>\n\n  </div>\n}", styles: [":host{display:flex;justify-content:flex-start;padding-left:1rem;padding-right:1rem;color:var(--color-text-primary)}.pac-indicator__tag{width:60px;text-align:right;border-radius:5px;padding:0 5px;cursor:pointer}.pac-indicator__tag.Trend-Up{background-color:#31c75a;color:#fff}.pac-indicator__tag.Trend-Down{background-color:#fe3c2e;color:#fff}.Trend-Up{color:#31c75a}.Trend-Down{color:#fe3c2e}:host.reverse-semantic-color .Trend-Up{color:#fe3c2e}:host.reverse-semantic-color .Trend-Down{color:#31c75a}:host.reverse-semantic-color .pac-indicator__tag.Trend-Up{background-color:#fe3c2e;--tw-text-opacity: 1;color:rgb(245 245 245 / var(--tw-text-opacity))}:host.reverse-semantic-color .pac-indicator__tag.Trend-Down{background-color:#31c75a;--tw-text-opacity: 1;color:rgb(245 245 245 / var(--tw-text-opacity))}\n"] }]
        }], ctorParameters: () => [] });

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

export { NgmIndicatorComponent, StatisticalType, Trend, TrendColor, TrendReverseColor };
//# sourceMappingURL=metad-ocap-angular-indicator.mjs.map
