import { ChartEvent } from "../../constant/event";

import { DEFAULT_DATA_KEY, DEFAULT_DATA_SERIES_FIELD, DEFAULT_SERIES_STYLE_NAME, STACK_FIELD_END, STACK_FIELD_END_PERCENT, STACK_FIELD_START, STACK_FIELD_START_PERCENT } from "../../constant/data";

import { AttributeLevel } from "../../constant/attribute";

import { PREFIX } from "../../constant/base";

import { DataView } from "@visactor/vdataset";

import { BaseModel } from "../../model/base-model";

import { dataToDataView, dataViewFromDataView, updateDataViewInData } from "../../data/initialize";

import { mergeFields, getFieldAlias } from "../../util/data";

import { couldBeValidNumber } from "../../util/type";

import { mergeSpec } from "@visactor/vutils-extension";

import { addVChartProperty } from "../../data/transforms/add-property";

import { registerDataSetInstanceTransform } from "../../data/register";

import { BaseSeriesTooltipHelper } from "./tooltip-helper";

import { dimensionStatistics, dimensionStatisticsOfSimpleData } from "../../data/transforms/dimension-statistics";

import { invalidTravel } from "../../data/transforms/invalid-travel";

import { getDataScheme } from "../../theme/color-scheme/util";

import { addDataKey, initKeyMap } from "../../data/transforms/data-key";

import { STATE_VALUE_ENUM } from "../../compile/mark";

import { array, isEqual, isNil, isValid, isBoolean, isString, isFunction, isArray, isValidNumber, isObject, minInArray, maxInArray, merge } from "@visactor/vutils";

import { ColorOrdinalScale } from "../../scale/color-ordinal-scale";

import { baseSeriesMark, defaultSeriesIgnoreCheckKeys, defaultSeriesCompileCheckKeys } from "./constant";

import { animationConfig, userAnimationConfig, isAnimationEnabledForSeries } from "../../animation/utils";

import { BaseSeriesSpecTransformer } from "./base-series-transformer";

import { getDefaultInteractionConfigByMode } from "../../interaction/config";

import { LayoutZIndex } from "../../constant/layout";

import { CompilableData } from "../../compile/data";

import { filterMarksOfInteraction } from "../../interaction/triggers/util";

export class BaseSeries extends BaseModel {
    getRegion() {
        return this._region;
    }
    getLayoutStartPoint() {
        return this._region.getLayoutStartPoint();
    }
    getRootMark() {
        return this._rootMark;
    }
    getSeriesMark() {
        return this._seriesMark;
    }
    getRawData() {
        return this._rawData;
    }
    getViewDataFilter() {
        return this._viewDataFilter;
    }
    getViewData() {
        var _a;
        return null === (_a = this._data) || void 0 === _a ? void 0 : _a.getDataView();
    }
    getViewDataProductId() {
        var _a;
        return null === (_a = this._data) || void 0 === _a ? void 0 : _a.getProductId();
    }
    getViewDataStatistics() {
        return this._viewDataStatistics;
    }
    getViewStackData() {
        return this._viewStackData;
    }
    getSeriesField() {
        return this._seriesField;
    }
    setSeriesField(field) {
        isValid(field) && (this._seriesField = field);
    }
    getGroups() {
        return this._groups;
    }
    getStack() {
        var _a;
        return null === (_a = this.getSpecInfo()) || void 0 === _a ? void 0 : _a.stack;
    }
    getStackValue() {
        var _a;
        return null !== (_a = this._spec.stackValue) && void 0 !== _a ? _a : `${PREFIX}_series_${this.type}`;
    }
    getPercent() {
        return this._spec.percent;
    }
    getStackOffsetSilhouette() {
        return this._spec.stackOffsetSilhouette;
    }
    get tooltipHelper() {
        return this._tooltipHelper || this.initTooltip(), this._tooltipHelper;
    }
    getInvalidType() {
        return this._invalidType;
    }
    setInvalidType(t) {
        var _a;
        this._invalidType = t, null === (_a = this.getViewData()) || void 0 === _a || _a.reRunAllTransform();
    }
    getMarkAttributeContext() {
        return this._markAttributeContext;
    }
    constructor(spec, options) {
        var _a;
        super(spec, options), this.specKey = "series", this.type = "series", this.layoutType = "absolute", 
        this.modelType = "series", this.name = void 0, this.transformerConstructor = BaseSeriesSpecTransformer, 
        this.coordinate = "none", this._region = null, this._layoutStartPoint = {
            x: 0,
            y: 0
        }, this._layoutRect = {
            width: null,
            height: null
        }, this.getLayoutRect = () => {
            var _a, _b;
            return {
                width: null !== (_a = this._layoutRect.width) && void 0 !== _a ? _a : this._region.getLayoutRect().width,
                height: null !== (_b = this._layoutRect.height) && void 0 !== _b ? _b : this._region.getLayoutRect().height
            };
        }, this._rootMark = null, this._seriesMark = null, this._viewDataMap = new Map, 
        this._viewDataFilter = null, this._data = null, this.layoutZIndex = LayoutZIndex.SeriesGroup, 
        this._invalidType = "break", this._region = options.region, this._dataSet = options.dataSet, 
        (null === (_a = this._spec) || void 0 === _a ? void 0 : _a.name) && (this.name = this._spec.name);
    }
    created() {
        super.created(), this._buildMarkAttributeContext(), this.initData(), this.initGroups(), 
        this.initStatisticalData(), this.event.emit(ChartEvent.afterInitData, {
            model: this
        }), this.initRootMark(), this.initMark();
        const hasAnimation = isAnimationEnabledForSeries(this);
        this._initExtensionMark({
            hasAnimation: hasAnimation
        }), this.initMarkStyle(), this.initMarkState(), hasAnimation && this.initAnimation(), 
        this.afterInitMark(), this.initEvent(), this.event.emit(ChartEvent.afterInitEvent, {
            model: this
        });
    }
    _buildMarkAttributeContext() {
        this._markAttributeContext = {
            vchart: this._option.globalInstance,
            globalScale: (key, value) => {
                var _a;
                return null === (_a = this._option.globalScale.getScale(key)) || void 0 === _a ? void 0 : _a.scale(value);
            },
            seriesColor: seriesValue => {
                var _a;
                return isNil(seriesValue) && (seriesValue = this.getSeriesKeys()[0]), null === (_a = this._option.globalScale.getScale("color")) || void 0 === _a ? void 0 : _a.scale(seriesValue);
            },
            getRegion: () => this._region
        };
    }
    setAttrFromSpec() {
        super.setAttrFromSpec(), this.setSeriesField(this._spec.seriesField), isValid(this._spec.invalidType) && (this._invalidType = this._spec.invalidType);
    }
    getInvalidCheckFields() {
        return [ this.getStackValueField() ];
    }
    initInvalidDataTransform() {
        var _a, _b;
        "zero" === this._invalidType && (null === (_a = this._rawData) || void 0 === _a ? void 0 : _a.dataSet) && (registerDataSetInstanceTransform(this._rawData.dataSet, "invalidTravel", invalidTravel), 
        null === (_b = this._rawData) || void 0 === _b || _b.transform({
            type: "invalidTravel",
            options: {
                config: () => ({
                    invalidType: this._invalidType,
                    checkField: this.getInvalidCheckFields()
                })
            }
        }, !1));
    }
    initData() {
        var _a, _b, _c;
        const d = null !== (_a = this._spec.data) && void 0 !== _a ? _a : this._option.getSeriesData(this._spec.dataId, this._spec.dataIndex);
        if (d && (this._rawData = dataToDataView(d, this._dataSet, this._option.sourceDataList)), 
        null === (_c = null === (_b = this._rawData) || void 0 === _b ? void 0 : _b.target) || void 0 === _c || _c.addListener("change", this.rawDataUpdate.bind(this)), 
        this._addDataIndexAndKey(), this._rawData) {
            this.getStack() && (this._viewDataFilter = dataViewFromDataView(this._rawData, this._dataSet, {
                name: `${this.type}_${this.id}_viewDataFilter`
            }));
            const viewData = dataViewFromDataView(this.getStack() ? this._viewDataFilter : this._rawData, this._dataSet, {
                name: `${this.type}_${this.id}_viewData`
            });
            this._data = new CompilableData(this._option, viewData), this.getStack() && this._viewDataFilter.target.removeListener("change", viewData.reRunAllTransform);
        }
        this.initInvalidDataTransform();
    }
    initGroups() {
        const groupFields = this.getGroupFields();
        groupFields && groupFields.length && (this._groups = {
            fields: groupFields
        });
    }
    initStatisticalData() {
        this._data && this._statisticViewData();
    }
    getRawDataStatisticsByField(field, isNumeric) {
        var _a, _b, _c;
        if (this._rawStatisticsCache || (this._rawStatisticsCache = {}), !this._rawStatisticsCache[field] || isNumeric && (isNil(this._rawStatisticsCache[field].min) || isNil(this._rawStatisticsCache[field].max)) || !isNumeric && isNil(this._rawStatisticsCache[field].values)) {
            if (this._viewDataStatistics && (!this._viewDataFilter || this._viewDataFilter.transformsArr.length <= 1) && this.getViewData().transformsArr.length <= 1 && (null === (_a = this._viewDataStatistics.latestData) || void 0 === _a ? void 0 : _a[field])) this._rawStatisticsCache[field] = this._viewDataStatistics.latestData[field]; else if (this._rawData) {
                const fieldInfo = null === (_b = this._rawData.getFields()) || void 0 === _b ? void 0 : _b[field];
                if (fieldInfo && fieldInfo.lockStatisticsByDomain && fieldInfo.domain) this._rawStatisticsCache[field] = {}, 
                isNumeric ? (this._rawStatisticsCache[field].min = minInArray(fieldInfo.domain), 
                this._rawStatisticsCache[field].max = maxInArray(fieldInfo.domain)) : this._rawStatisticsCache[field].values = fieldInfo.domain; else {
                    const result = dimensionStatisticsOfSimpleData(this._rawData.latestData, [ {
                        key: field,
                        operations: isNumeric ? [ "min", "max" ] : [ "values" ]
                    } ])[field];
                    this._rawStatisticsCache[field] = merge(null !== (_c = this._rawStatisticsCache[field]) && void 0 !== _c ? _c : {}, result);
                }
            }
        }
        return this._rawStatisticsCache[field];
    }
    _statisticViewData() {
        registerDataSetInstanceTransform(this._dataSet, "dimensionStatistics", dimensionStatistics);
        const viewDataStatisticsName = `${this.type}_${this.id}_viewDataStatic`;
        this._viewDataStatistics = new DataView(this._dataSet, {
            name: viewDataStatisticsName
        }), this._viewDataStatistics.parse([ this._data.getDataView() ], {
            type: "dataview"
        }), this._viewDataStatistics.transform({
            type: "dimensionStatistics",
            options: {
                fields: () => {
                    const fields = this.getStatisticFields();
                    return this._seriesField && mergeFields(fields, [ {
                        key: this._seriesField,
                        operations: [ "values" ]
                    } ]), fields;
                },
                target: "latest"
            }
        }, !1), this._data.getDataView().target.removeListener("change", this._viewDataStatistics.reRunAllTransform), 
        this.getStack() && this.createdStackData();
    }
    createStatisticalData(dataName, rawData, staticFields) {
        registerDataSetInstanceTransform(this._dataSet, "dimensionStatistics", dimensionStatistics);
        const data = new DataView(this._dataSet, {
            name: dataName
        });
        return data.parse([ rawData ], {
            type: "dataview"
        }), data.transform({
            type: "dimensionStatistics",
            options: {
                operations: [ "max", "min", "values" ],
                fields: () => {
                    var _a;
                    const fields = mergeFields(this.getStatisticFields(), null !== (_a = null == staticFields ? void 0 : staticFields(rawData.name)) && void 0 !== _a ? _a : []);
                    return this._seriesField && mergeFields(fields, [ {
                        key: this._seriesField,
                        operations: [ "values" ]
                    } ]), fields;
                },
                target: "latest"
            }
        }, !1), data;
    }
    createdStackData() {
        const dataName = `${this.type}_${this.id}_viewStackData`;
        this._viewStackData = new DataView(this._dataSet, {
            name: dataName
        }), this._viewStackData.parse([ this._viewDataFilter ], {
            type: "dataview"
        }), this._viewStackData.transform({
            type: "stackSplit",
            options: {
                fields: this.getStackGroupFields()
            }
        }, !1);
    }
    _noAnimationDataKey(datum, index) {
        return index;
    }
    generateDefaultDataKey(dataKey) {
        var _a;
        return isNil(dataKey) ? (datum, index, context) => {
            if (!1 === this._spec.animation) {
                const v = this._noAnimationDataKey(datum, index);
                if (void 0 !== v) return v;
            }
            const {keyMap: keyMap} = context, seriesDataKey = this._getSeriesDataKey(datum);
            return void 0 === keyMap.get(seriesDataKey) ? (keyMap.set(seriesDataKey, 0), seriesDataKey) : (keyMap.set(seriesDataKey, keyMap.get(seriesDataKey) + 1), 
            `${seriesDataKey}_${keyMap.get(seriesDataKey)}`);
        } : isString(dataKey) ? datum => datum[dataKey] : isArray(dataKey) && dataKey.every((d => isString(d))) ? datum => dataKey.map((k => datum[k])).join("-") : isFunction(dataKey) ? (datum, index) => dataKey(datum, index) : (null === (_a = this._option) || void 0 === _a || _a.onError(`invalid dataKey: ${dataKey}`), 
        (datum, index) => {});
    }
    _addDataIndexAndKey() {
        var _a;
        (null === (_a = this._rawData) || void 0 === _a ? void 0 : _a.dataSet) && (registerDataSetInstanceTransform(this._rawData.dataSet, "addVChartProperty", addVChartProperty), 
        this._rawData.transform({
            type: "addVChartProperty",
            options: {
                beforeCall: initKeyMap.bind(this),
                call: addDataKey
            }
        }, !1));
    }
    updateRawData(d) {
        this._rawData && this._rawData.updateRawData(d);
    }
    rawDataUpdate(d) {
        var _a;
        null === (_a = this._rawDataStatistics) || void 0 === _a || _a.reRunAllTransform(), 
        this._rawStatisticsCache = null, this.event.emit(ChartEvent.rawDataUpdate, {
            model: this
        });
    }
    viewDataFilterOver(d) {
        this.event.emit(ChartEvent.viewDataFilterOver, {
            model: this
        });
    }
    viewDataUpdate(d) {
        var _a;
        this.event.emit(ChartEvent.viewDataUpdate, {
            model: this
        }), null === (_a = this._data) || void 0 === _a || _a.updateData(), this._viewDataStatistics && this._viewDataStatistics.reRunAllTransform();
    }
    viewDataStatisticsUpdate(d) {
        this.event.emit(ChartEvent.viewDataStatisticsUpdate, {
            model: this
        });
    }
    getDatumPositionValue(datum, field) {
        return !datum || isNil(field) ? null : datum[field];
    }
    getDatumPositionValues(datum, fields) {
        return !datum || isNil(fields) ? [] : isString(fields) ? [ datum[fields] ] : fields.map((f => datum[f]));
    }
    setValueFieldToStack() {}
    setValueFieldToPercent() {}
    setValueFieldToStackOffsetSilhouette() {}
    initRootMark() {
        var _a, _b, _c;
        this._rootMark = this._createMark({
            type: "group",
            name: `seriesGroup_${this.type}_${this.id}`
        }, {
            parent: null === (_b = (_a = this._region).getGroupMark) || void 0 === _b ? void 0 : _b.call(_a),
            dataView: !1
        }), this._rootMark.setMarkConfig({
            zIndex: null !== (_c = this._spec.zIndex) && void 0 !== _c ? _c : this.layoutZIndex
        });
    }
    _getExtensionMarkNamePrefix() {
        return `${this.type}_${this.id}_extensionMark`;
    }
    _initExtensionMark(options) {
        var _a;
        this._spec.extensionMark && (null === (_a = this._spec.extensionMark) || void 0 === _a || _a.forEach(((m, i) => {
            this._createExtensionMark(m, null, this._getExtensionMarkNamePrefix(), i, options);
        })));
    }
    _createExtensionMark(spec, parentMark, namePrefix, index, options) {
        var _a;
        const mark = this._createMark({
            type: spec.type,
            name: isValid(spec.name) ? `${spec.name}` : `${namePrefix}_${index}`
        }, {
            skipBeforeLayouted: !0,
            markSpec: spec,
            parent: parentMark,
            dataView: !1,
            componentType: spec.componentType,
            key: spec.dataKey
        });
        if (mark) {
            if (isValid(spec.id) && mark.setUserId(spec.id), options.hasAnimation && !1 !== spec.animation) {
                const config = animationConfig({}, userAnimationConfig(spec.type, spec, this._markAttributeContext));
                mark.setAnimationConfig(config);
            }
            if ("group" === spec.type && (namePrefix = `${namePrefix}_${index}`, null === (_a = spec.children) || void 0 === _a || _a.forEach(((s, i) => {
                this._createExtensionMark(s, mark, namePrefix, i, options);
            }))), !isNil(spec.dataId) || !isNil(spec.dataIndex)) {
                const dataView = this._option.getSeriesData(spec.dataId, spec.dataIndex);
                dataView === this._rawData ? mark.setData(this._data) : (mark.setDataView(dataView), 
                dataView.target.addListener("change", (() => {
                    mark.getData().updateData();
                })));
            }
        }
    }
    _updateExtensionMarkSpec() {
        var _a;
        null === (_a = this._spec.extensionMark) || void 0 === _a || _a.forEach(((spec, i) => {
            const mark = this._marks.getMarkWithInfo({
                name: isValid(spec.name) ? `${spec.name}` : `${this._getExtensionMarkNamePrefix()}_${i}`
            });
            mark && (this.initMarkStyleWithSpec(mark, spec), mark.commit(!1, !0));
        }));
    }
    getStackData() {
        var _a;
        return null === (_a = this._viewStackData) || void 0 === _a ? void 0 : _a.latestData;
    }
    _parseDefaultInteractionConfig(mainMarks) {
        if (!(null == mainMarks ? void 0 : mainMarks.length)) return [];
        const defaultConfig = getDefaultInteractionConfigByMode(this._option.mode);
        let finalHoverSpec = Object.assign({}, null == defaultConfig ? void 0 : defaultConfig.hover), finalSelectSpec = Object.assign({}, null == defaultConfig ? void 0 : defaultConfig.select);
        const hoverSpec = this._spec.hover;
        isBoolean(hoverSpec) ? finalHoverSpec.enable = hoverSpec : isObject(hoverSpec) && (finalHoverSpec.enable = !0, 
        finalHoverSpec = mergeSpec(finalHoverSpec, hoverSpec));
        const selectSpec = this._spec.select;
        isBoolean(selectSpec) ? finalSelectSpec.enable = selectSpec : isObject(selectSpec) && (finalSelectSpec.enable = !0, 
        finalSelectSpec = mergeSpec(finalSelectSpec, selectSpec));
        const res = [ {
            trigger: {
                type: "dimension-hover"
            },
            marks: mainMarks
        } ];
        if (finalHoverSpec.enable) {
            const marks = filterMarksOfInteraction(finalHoverSpec, mainMarks);
            marks.length && res.push({
                trigger: this._defaultHoverConfig(finalHoverSpec),
                marks: marks
            });
        }
        if (finalSelectSpec.enable) {
            const marks = filterMarksOfInteraction(finalSelectSpec, mainMarks);
            marks.length && res.push({
                trigger: this._defaultSelectConfig(finalSelectSpec),
                marks: marks
            });
        }
        return res;
    }
    _defaultHoverConfig(finalHoverSpec) {
        return {
            type: "element-highlight",
            trigger: finalHoverSpec.trigger,
            triggerOff: finalHoverSpec.triggerOff,
            blurState: STATE_VALUE_ENUM.STATE_HOVER_REVERSE,
            highlightState: STATE_VALUE_ENUM.STATE_HOVER
        };
    }
    _defaultSelectConfig(finalSelectSpec) {
        const isMultiple = "multiple" === finalSelectSpec.mode, triggerOff = isValid(finalSelectSpec.triggerOff) ? finalSelectSpec.triggerOff : isMultiple ? [ "empty" ] : [ "empty", finalSelectSpec.trigger ];
        return {
            type: "element-select",
            trigger: finalSelectSpec.trigger,
            triggerOff: triggerOff,
            reverseState: STATE_VALUE_ENUM.STATE_SELECTED_REVERSE,
            state: STATE_VALUE_ENUM.STATE_SELECTED,
            isMultiple: isMultiple
        };
    }
    _parseInteractionConfig(mainMarks) {
        const {interactions: interactions} = this._spec, res = this._parseDefaultInteractionConfig(mainMarks);
        return interactions && interactions.length && interactions.forEach((interaction => {
            const marks = filterMarksOfInteraction(interaction, this.getMarks());
            marks.length && res.push({
                trigger: interaction,
                marks: marks
            });
        })), res;
    }
    getInteractionTriggers() {
        if (!0 !== this._option.disableTriggerEvent) {
            const marks = this.getMarksWithoutRoot();
            return this._parseInteractionConfig(marks);
        }
        return [];
    }
    initAnimation() {}
    initMarkState() {
        this.initSeriesStyleState();
    }
    initSeriesStyleState() {
        var _a;
        const seriesStyle = this._spec.seriesStyle;
        if (!seriesStyle || !seriesStyle.length) return;
        const groupBy = null !== (_a = this._seriesField) && void 0 !== _a ? _a : DEFAULT_DATA_SERIES_FIELD;
        this.getMarksWithoutRoot().forEach((mark => {
            const filterMap = {}, attrMap = {}, markStyle = {};
            seriesStyle.forEach((item => {
                var _a;
                const style = null === (_a = item[mark.name]) || void 0 === _a ? void 0 : _a.style;
                style && (filterMap[item.name] = !0, markStyle[item.name] = markStyle[item.name] || {}, 
                Object.keys(style).forEach((key => {
                    attrMap[key] = !0, markStyle[item.name][key] = style[key];
                })));
            })), mark.state.addStateInfo({
                stateValue: DEFAULT_SERIES_STYLE_NAME,
                level: -1,
                filter: datum => Array.isArray(datum) ? 0 !== datum.length && !0 === filterMap[datum[0][groupBy]] : !0 === filterMap[datum[groupBy]]
            });
            const style = {};
            Object.keys(attrMap).forEach((key => {
                style[key] = datum => {
                    var _a, _b;
                    let style;
                    if (Array.isArray(datum)) {
                        if (0 === datum.length) return;
                        style = null === (_a = markStyle[datum[0][groupBy]]) || void 0 === _a ? void 0 : _a[key];
                    }
                    return style = null === (_b = markStyle[datum[groupBy]]) || void 0 === _b ? void 0 : _b[key], 
                    isValid(style) ? style : mark.getAttribute(key, datum);
                };
            })), this.setMarkStyle(mark, style, DEFAULT_SERIES_STYLE_NAME, AttributeLevel.User_SeriesStyle);
        }));
    }
    afterInitMark() {
        this.event.emit(ChartEvent.afterInitMark, {
            model: this
        }), this.setSeriesField(this._spec.seriesField), this.getMarks().forEach((m => {
            var _a, _b;
            (null === (_b = null === (_a = m.stateStyle) || void 0 === _a ? void 0 : _a.normal) || void 0 === _b ? void 0 : _b.lineWidth) && m.setAttribute("stroke", this.getColorAttribute(), "normal", AttributeLevel.Base_Series);
        }));
    }
    getMarksWithoutRoot() {
        return this.getMarks().filter((m => {
            var _a;
            return !(null === (_a = m.name) || void 0 === _a ? void 0 : _a.includes("seriesGroup"));
        }));
    }
    getMarksInType(type) {
        return this._marks.getMarksInType(type);
    }
    getMarkInName(name) {
        return this._marks.get(name);
    }
    getMarkInId(markId) {
        return this.getMarks().find((m => m.id === markId));
    }
    initEvent() {
        var _a, _b, _c;
        null === (_b = null === (_a = this._data) || void 0 === _a ? void 0 : _a.getDataView()) || void 0 === _b || _b.target.addListener("change", this.viewDataUpdate.bind(this)), 
        null === (_c = this._viewDataStatistics) || void 0 === _c || _c.target.addListener("change", this.viewDataStatisticsUpdate.bind(this));
    }
    _releaseEvent() {
        super._releaseEvent();
    }
    initTooltip() {
        this._tooltipHelper = new BaseSeriesTooltipHelper(this);
    }
    _compareExtensionMarksSpec(newMarks, prevMarks, compareResult) {
        newMarks.length !== prevMarks.length || prevMarks.some(((prev, index) => prev.type !== newMarks[index].type || prev.id !== newMarks[index].id || prev.name !== newMarks[index].name)) ? compareResult.reMake = !0 : prevMarks.some(((prev, index) => prev.visible !== newMarks[index].visible)) && (compareResult.reCompile = !0);
    }
    _compareLabelSpec(newLabels, prevLabels, compareResult) {
        newLabels.length !== prevLabels.length || prevLabels.some(((prev, index) => prev.labelLayout !== newLabels[index].labelLayout || prev.visible !== newLabels[index].visible)) ? compareResult.reMake = !0 : !compareResult.reCompile && prevLabels.some(((prev, index) => !isEqual(prev, newLabels[index]))) && (compareResult.reCompile = !0);
    }
    _compareSpec(spec, prevSpec, ignoreCheckKeys) {
        const result = super._compareSpec(spec, prevSpec), currentKeys = Object.keys(prevSpec || {}).sort(), nextKeys = Object.keys(spec || {}).sort();
        if (!isEqual(currentKeys, nextKeys)) return result.reMake = !0, result;
        const ignores = Object.assign(Object.assign(Object.assign(Object.assign({}, defaultSeriesIgnoreCheckKeys), defaultSeriesCompileCheckKeys), ignoreCheckKeys), {
            extensionMark: !0,
            label: !0,
            totalLabel: !0
        });
        return this._compareExtensionMarksSpec(array(spec.extensionMark), array(prevSpec.extensionMark), result), 
        !result.reMake && this._compareLabelSpec(array(spec.label), array(prevSpec.label), result), 
        !result.reMake && this._compareLabelSpec(array(spec.totalLabel), array(prevSpec.totalLabel), result), 
        result.reMake ? result : (!result.reCompile && this._marks.getMarks().some((m => {
            var _a, _b;
            return ignores[m.name] = !0, (null === (_a = prevSpec[m.name]) || void 0 === _a ? void 0 : _a.visible) !== (null === (_b = spec[m.name]) || void 0 === _b ? void 0 : _b.visible);
        })) && (result.reCompile = !0), !result.reCompile && currentKeys.some((k => defaultSeriesCompileCheckKeys[k] && !isEqual(spec[k], prevSpec[k]))) && (result.reCompile = !0), 
        currentKeys.some((k => !ignores[k] && !isEqual(spec[k], prevSpec[k]))) ? (result.reMake = !0, 
        result) : result);
    }
    _updateSpecData() {
        !this._rawData || !this._spec.data || this._spec.data instanceof DataView || updateDataViewInData(this._rawData, this._spec.data, !0);
    }
    reInit(spec) {
        super.reInit(spec);
        const marks = this.getMarksWithoutRoot();
        marks.forEach((mark => {
            this._spec[mark.name] && this.initMarkStyleWithSpec(mark, this._spec[mark.name]);
        })), this.initMarkStyle(), marks.forEach((mark => {
            mark.commit(!1);
        })), this._updateExtensionMarkSpec(), this._updateSpecData(), this._tooltipHelper && this._tooltipHelper.updateTooltipSpec();
        isAnimationEnabledForSeries(this) && this.initAnimation();
    }
    onEvaluateEnd(ctx) {
        this._data.updateData();
    }
    release() {
        var _a, _b;
        super.release(), this._viewDataMap.clear();
        const transformIndex = null === (_b = null === (_a = this._rawData) || void 0 === _a ? void 0 : _a.transformsArr) || void 0 === _b ? void 0 : _b.findIndex((t => "addVChartProperty" === t.type));
        transformIndex >= 0 && this._rawData.transformsArr.splice(transformIndex, 1), this._dataSet = this._data = this._rawData = this._rawDataStatistics = this._spec = this._region = this._viewDataStatistics = this._viewStackData = null;
    }
    setLayoutStartPosition(pos) {
        isValidNumber(pos.x) && (this._layoutStartPoint.x = pos.x), isValidNumber(pos.y) && (this._layoutStartPoint.y = pos.y);
    }
    setLayoutRect({width: width, height: height}, levelMap) {
        isValidNumber(width) && (this._layoutRect.width = width), isValidNumber(height) && (this._layoutRect.height = height);
    }
    getSeriesKeys() {
        var _a, _b;
        return this._seriesField ? null !== (_b = null === (_a = this.getRawDataStatisticsByField(this._seriesField)) || void 0 === _a ? void 0 : _a.values) && void 0 !== _b ? _b : [] : this.name ? [ this.name ] : this.userId ? [ `${this.userId}` ] : [ `${this.type}_${this.id}` ];
    }
    getSeriesStyle(datum) {
        return attribute => {
            var _a, _b;
            return null !== (_b = null === (_a = this._seriesMark) || void 0 === _a ? void 0 : _a.getAttribute(attribute, datum)) && void 0 !== _b ? _b : void 0;
        };
    }
    _getSeriesInfo(field, keys) {
        const defaultShapeType = this.getDefaultShapeType();
        return keys.map((key => ({
            key: key,
            originalKey: key,
            style: this.getSeriesStyle({
                [field]: key
            }),
            shapeType: defaultShapeType
        })));
    }
    getSeriesInfoInField(field) {
        var _a, _b;
        return this._getSeriesInfo(field, null !== (_b = null === (_a = this.getRawDataStatisticsByField(field)) || void 0 === _a ? void 0 : _a.values) && void 0 !== _b ? _b : []);
    }
    getSeriesInfoList() {
        var _a;
        return this._getSeriesInfo(null !== (_a = this._seriesField) && void 0 !== _a ? _a : DEFAULT_DATA_SERIES_FIELD, this.getSeriesKeys());
    }
    _getDefaultColorScale() {
        var _a, _b;
        const colorDomain = this.getDefaultColorDomain(), colorRange = this._getDataScheme();
        return null === (_b = (_a = (new ColorOrdinalScale).domain(colorDomain)).range) || void 0 === _b ? void 0 : _b.call(_a, colorRange);
    }
    _getDataScheme() {
        return getDataScheme(this.getColorScheme(), this.type);
    }
    getDefaultColorDomain() {
        var _a, _b;
        return this._seriesField ? null === (_b = null === (_a = this.getViewDataStatistics()) || void 0 === _a ? void 0 : _a.latestData[this._seriesField]) || void 0 === _b ? void 0 : _b.values : [];
    }
    getColorAttribute() {
        var _a, _b;
        return {
            scale: null !== (_a = this._option.globalScale.getScale("color")) && void 0 !== _a ? _a : this._getDefaultColorScale(),
            field: null !== (_b = this._seriesField) && void 0 !== _b ? _b : DEFAULT_DATA_SERIES_FIELD
        };
    }
    getDimensionField() {
        return [];
    }
    getMeasureField() {
        return [];
    }
    onMarkPositionUpdate() {
        this.onMarkTreePositionUpdate(this.getMarksWithoutRoot());
    }
    onMarkTreePositionUpdate(marks) {}
    _createMark(markInfo, option = {}, config = {}) {
        var _a, _b, _c, _d, _e;
        const {key: key, groupKey: groupKey, skipBeforeLayouted: skipBeforeLayouted, themeSpec: themeSpec = {}, markSpec: markSpec, dataView: dataView, parent: parent, isSeriesMark: isSeriesMark, noSeparateStyle: noSeparateStyle = !1} = option, m = super._createMark(markInfo, {
            key: null != key ? key : this._getDataIdKey(),
            seriesId: this.id,
            attributeContext: this._markAttributeContext,
            componentType: option.componentType,
            noSeparateStyle: noSeparateStyle,
            parent: !1 !== parent ? null != parent ? parent : this._rootMark : null
        });
        if (isValid(m)) {
            const spec = this.getSpec() || {};
            this._marks.addMark(m, {
                name: markInfo.name
            }), isSeriesMark && (this._seriesMark = m), isNil(dataView) ? m.setData(this._data) : !1 !== dataView && m.setDataView(dataView), 
            m.setSkipBeforeLayouted(!1 !== skipBeforeLayouted), isNil(groupKey) || m.setGroupKey(groupKey);
            const markConfig = Object.assign(Object.assign({}, config), {
                progressiveStep: spec.progressiveStep,
                progressiveThreshold: spec.progressiveThreshold,
                large: spec.large,
                largeThreshold: spec.largeThreshold,
                morph: null !== (_a = config.morph) && void 0 !== _a && _a,
                useSequentialAnimation: spec.useSequentialAnimation,
                support3d: null !== (_b = config.support3d) && void 0 !== _b ? _b : spec.support3d || !!spec.zField,
                morphKey: (null === (_c = spec.morph) || void 0 === _c ? void 0 : _c.morphKey) || `${this.getSpecIndex()}_${this.getMarks().length}`,
                morphElementKey: null !== (_e = null === (_d = spec.morph) || void 0 === _d ? void 0 : _d.morphElementKey) && void 0 !== _e ? _e : config.morphElementKey
            });
            m.setMarkConfig(markConfig), this.initMarkStyleWithSpec(m, mergeSpec({}, themeSpec, markSpec || spec[m.name]));
        }
        return m;
    }
    _getDataIdKey() {
        var _a;
        return null !== (_a = super._getDataIdKey()) && void 0 !== _a ? _a : DEFAULT_DATA_KEY;
    }
    _getSeriesDataKey(datum) {
        let key = "";
        if (!datum) return key;
        const dimensionFields = this.getDimensionField();
        key = dimensionFields.map((field => datum[field])).join("_");
        const seriesField = this.getSeriesField();
        return seriesField && !dimensionFields.includes(seriesField) && (key += `_${datum[seriesField]}`), 
        key;
    }
    addViewDataFilter(option) {
        var _a, _b;
        null === (_b = null !== (_a = this._viewDataFilter) && void 0 !== _a ? _a : this.getViewData()) || void 0 === _b || _b.transform(option, !1);
    }
    reFilterViewData() {
        var _a, _b;
        null === (_b = null !== (_a = this._viewDataFilter) && void 0 !== _a ? _a : this.getViewData()) || void 0 === _b || _b.reRunAllTransform();
    }
    reTransformViewData() {
        var _a, _b;
        null === (_b = null === (_a = this._data) || void 0 === _a ? void 0 : _a.getDataView()) || void 0 === _b || _b.reRunAllTransform();
    }
    fillData() {
        var _a;
        null === (_a = this.getRawData()) || void 0 === _a || _a.reRunAllTransform();
    }
    compile() {
        this.compileData();
    }
    getDefaultShapeType() {
        return "circle";
    }
    getFieldAlias(field) {
        var _a;
        return field !== STACK_FIELD_END && field !== STACK_FIELD_END_PERCENT && field !== STACK_FIELD_START && field !== STACK_FIELD_START_PERCENT || (field = this.getStackValueField()), 
        null !== (_a = getFieldAlias(this.getRawData(), field)) && void 0 !== _a ? _a : field;
    }
    _getInvalidConnectType() {
        return "zero" === this._invalidType ? "zero" : "link" === this._invalidType ? "connect" : "none";
    }
    _getInvalidDefined(datum) {
        const checkFields = this.getInvalidCheckFields();
        return !checkFields.length || checkFields.every((field => couldBeValidNumber(datum[field])));
    }
    _getRelatedComponentSpecInfo(specKey) {
        var _a;
        const specIndex = this.getSpecIndex(), relatedComponent = null === (_a = this._option.getSpecInfo().component[specKey]) || void 0 === _a ? void 0 : _a.filter((componentInfo => componentInfo.seriesIndexes.includes(specIndex)));
        return null != relatedComponent ? relatedComponent : [];
    }
    _forEachStackGroup(callback, node) {
        var _a, _b;
        (node = null != node ? node : null === (_a = this._viewStackData) || void 0 === _a ? void 0 : _a.latestData) && ((null === (_b = node.values) || void 0 === _b ? void 0 : _b.length) ? callback(node) : node.nodes && Object.values(node.nodes).forEach((n => {
            this._forEachStackGroup(callback, n);
        })));
    }
    isDatumInViewData(datum) {
        if (!datum) return !1;
        const viewDataList = this.getViewData().latestData;
        return !!viewDataList && (!!viewDataList.includes(datum) || viewDataList.some((viewDatum => Object.keys(datum).every((key => datum[key] === viewDatum[key])))));
    }
    getSeriesFieldValue(datum, seriesField) {
        var _a;
        return datum[null !== (_a = null != seriesField ? seriesField : this.getSeriesField()) && void 0 !== _a ? _a : DEFAULT_DATA_SERIES_FIELD];
    }
}

BaseSeries.mark = baseSeriesMark, BaseSeries.transformerConstructor = BaseSeriesSpecTransformer;
//# sourceMappingURL=base-series.js.map
