import { isNullish } from "remeda";
import { array, clamper, regressionPolynomial } from "@visactor/vutils";
import { defaultRegressionLineColor } from "./common.js";
const columnPolynomialRegressionLine = (spec, context)=>{
    const result = {
        ...spec
    };
    const { advancedVSeed } = context;
    const { chartType, regressionLine } = advancedVSeed;
    const lineTheme = advancedVSeed.config[chartType]?.regressionLine;
    if (!regressionLine || !regressionLine.polynomialRegressionLine) return result;
    const lineList = array(regressionLine.polynomialRegressionLine);
    if (!result.customMark) result.customMark = [];
    lineList.forEach((line, lineIndex)=>{
        const theme = lineTheme.linearRegressionLine ?? {};
        const { color, lineWidth, lineDash, text, textColor, textFontSize, textFontWeight, confidenceIntervalOpacity, confidenceIntervalVisible = theme.confidenceIntervalVisible } = line;
        const childrenMarks = [];
        result.customMark.push({
            type: 'group',
            interactive: false,
            zIndex: 500,
            name: `polynomialRegressionLine-${lineIndex}`,
            style: {
                data: (datum, ctx)=>{
                    const vchart = ctx.vchart;
                    const chart = vchart.getChart();
                    const s = chart.getAllSeries()[0];
                    if (s) {
                        const rect = s.getRegion().getLayoutRect();
                        if (0 === rect.width || 0 === rect.height) return null;
                        const start = s.getRegion().getLayoutStartPoint();
                        const yClamper = clamper(start.y, start.y + rect.height);
                        const data = s.getViewData()?.latestData;
                        const fieldX = s.fieldX?.[0];
                        const fieldY = s.fieldY?.[0];
                        const xValues = s.getRawDataStatisticsByField(fieldX).values;
                        if (!fieldX || !fieldY || !data || data.length <= 2 || xValues.length <= 2) return null;
                        const { confidenceInterval, evaluateGrid } = regressionPolynomial(xValues.map((xVal, index)=>{
                            const filteredData = data.filter((d)=>d[fieldX] === xVal);
                            return {
                                x: index,
                                y: Math.max(...filteredData.map((d)=>d[fieldY]))
                            };
                        }), void 0, void 0, {
                            degree: line.degree ?? 2
                        });
                        const N = xValues.length;
                        const xAxisHelper = s.getXAxisHelper();
                        const halfBandWidth = xAxisHelper ? xAxisHelper.getBandwidth(0) / 2 : 0;
                        const lineData = evaluateGrid(N);
                        const linePoints = lineData.map((datum, index)=>{
                            const d = {
                                [fieldX]: xValues[index],
                                [fieldY]: datum.y
                            };
                            return {
                                x: s.dataToPositionX(d) + start.x + halfBandWidth,
                                y: yClamper(s.dataToPositionY(d) + start.y)
                            };
                        });
                        const result = {
                            linePoints,
                            color: s.getOption().globalScale.getScale('color')?.scale(s.getSeriesKeys()[0])
                        };
                        if (confidenceIntervalVisible) {
                            const intervalData = confidenceInterval(N);
                            result.areaPoints = intervalData.map((datum, index)=>{
                                const d = {
                                    [fieldX]: xValues[index],
                                    [fieldY]: datum.lower
                                };
                                return {
                                    x: s.dataToPositionX(d) + start.x + halfBandWidth,
                                    y: yClamper(s.dataToPositionY(d) + start.y),
                                    y1: yClamper(s.dataToPositionY({
                                        [fieldY]: datum.upper
                                    }) + start.y)
                                };
                            });
                        }
                        return result;
                    }
                    return null;
                }
            },
            children: childrenMarks
        });
        if (confidenceIntervalVisible) childrenMarks.push({
            type: 'area',
            interactive: false,
            zIndex: 500,
            style: {
                lineWidth: lineWidth ?? theme.lineWidth,
                lineDash: lineDash ?? theme.lineDash,
                fillOpacity: confidenceIntervalOpacity ?? theme.confidenceIntervalOpacity,
                fill: color ?? defaultRegressionLineColor,
                points: (datum, ctx, opt)=>{
                    const parentNode = opt.mark?._product?.parent;
                    if (parentNode?.attribute?.data) return parentNode.attribute.data.areaPoints;
                    return [];
                }
            }
        });
        childrenMarks.push({
            type: 'line',
            interactive: false,
            zIndex: 500,
            style: {
                lineWidth: lineWidth ?? theme.lineWidth,
                lineDash: lineDash ?? theme.lineDash,
                stroke: color ?? defaultRegressionLineColor,
                points: (datum, ctx, opt)=>{
                    const parentNode = opt.mark?._product?.parent;
                    if (parentNode?.attribute?.data) return parentNode.attribute.data.linePoints;
                    return [];
                }
            }
        });
        if (!isNullish(text)) childrenMarks.push({
            type: 'text',
            interactive: false,
            zIndex: 500,
            style: {
                textAlign: 'end',
                fill: textColor ?? theme.textColor,
                fontSize: textFontSize ?? theme.textFontSize,
                fontWeight: textFontWeight ?? theme.textFontWeight,
                text: text,
                x: (datum, ctx, opt)=>{
                    const parentNode = opt.mark?._product?.parent;
                    if (parentNode?.attribute?.data?.linePoints) {
                        const points = parentNode.attribute.data.linePoints;
                        return points[points.length - 1]?.x;
                    }
                },
                y: (datum, ctx, opt)=>{
                    const parentNode = opt.mark?._product?.parent;
                    if (parentNode?.attribute?.data?.linePoints) {
                        const points = parentNode.attribute.data.linePoints;
                        return points[points.length - 1]?.y;
                    }
                }
            }
        });
    });
    return result;
};
export { columnPolynomialRegressionLine };

//# sourceMappingURL=columnRegressionLine.js.map