
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements.  See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership.  The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License.  You may obtain a copy of the License at
*
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied.  See the License for the
* specific language governing permissions and limitations
* under the License.
*/


/**
 * AUTO-GENERATED FILE. DO NOT MODIFY.
 */

/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements.  See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership.  The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License.  You may obtain a copy of the License at
*
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied.  See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { __extends } from "tslib";
import SymbolDraw from '../helper/SymbolDraw.js';
import * as graphic from '../../util/graphic.js';
import { createClipPath } from '../helper/createClipPathFromCoordSys.js';
import ChartView from '../../view/Chart.js';
import { createSymbol } from '../../util/symbol.js';
import { each, map } from 'tvrender/lib/core/util.js';
import LinePlotPath from './LinePlotPath.js';
import PolyPlotPath from './PolyPlotPath.js';
import HistogramPlotPath from './HistogramPlotPath.js';
import BarPath from './BarPath.js';
import GradientBarPath from './GradientBarPath.js';
import GradientHistogramPlotPath from './GradientHistogramPlotPath.js';
import SymbolPath from './SymbolPath.js';
import { lerp } from 'tvrender/lib/tool/color.js';
import { getFormatColor } from '../../util/format.js';
import { getECData } from '../../util/innerStore.js';
import { toggleHoverEmphasis } from '../../util/states.js';
var LastZ2 = -1;
var lineStyleMap = {
  style_dotted: [2, 2],
  style_solid: 'solid',
  style_dashed: [5, 5]
};
function clipColorStops(colorStops, maxSize) {
  var newColorStops = [];
  var len = colorStops.length;
  // coord will always < 0 in prevOutOfRangeColorStop.
  var prevOutOfRangeColorStop;
  var prevInRangeColorStop;
  function lerpStop(stop0, stop1, clippedCoord) {
    var coord0 = stop0.coord;
    var p = (clippedCoord - coord0) / (stop1.coord - coord0);
    var color = lerp(p, [stop0.color, stop1.color]);
    return {
      coord: clippedCoord,
      color: color
    };
  }
  for (var i = 0; i < len; i++) {
    var stop_1 = colorStops[i];
    var coord = stop_1.coord;
    if (coord < 0) {
      prevOutOfRangeColorStop = stop_1;
    } else if (coord > maxSize) {
      if (prevInRangeColorStop) {
        newColorStops.push(lerpStop(prevInRangeColorStop, stop_1, maxSize));
      } else if (prevOutOfRangeColorStop) {
        // If there are two stops and coord range is between these two stops
        newColorStops.push(lerpStop(prevOutOfRangeColorStop, stop_1, 0), lerpStop(prevOutOfRangeColorStop, stop_1, maxSize));
      }
      // All following stop will be out of range. So just ignore them.
      break;
    } else {
      if (prevOutOfRangeColorStop) {
        newColorStops.push(lerpStop(prevOutOfRangeColorStop, stop_1, 0));
        // Reset
        prevOutOfRangeColorStop = null;
      }
      newColorStops.push(stop_1);
      prevInRangeColorStop = stop_1;
    }
  }
  return newColorStops;
}
function calculatebandWidth(seriesModel, data) {
  var baseAxis = seriesModel.getBaseAxis();
  var extent;
  var bandWidth = baseAxis.type === 'category' ? baseAxis.getBandWidth() : (extent = baseAxis.getExtent(), Math.abs(extent[1] - extent[0]) / data.count());
  return bandWidth;
}
function getVisualGradient(data, coordSys, api) {
  var visualMetaList = data.getVisual('visualMeta');
  if (!visualMetaList || !visualMetaList.length || !data.count()) {
    // When data.count() is 0, gradient range can not be calculated.
    return;
  }
  if (coordSys.type !== 'cartesian2d') {
    if (process.env.NODE_ENV !== 'production') {
      console.warn('Visual map on line style is only supported on cartesian2d.');
    }
    return;
  }
  var coordDim;
  var visualMeta;
  for (var i = visualMetaList.length - 1; i >= 0; i--) {
    var dimInfo = data.getDimensionInfo(visualMetaList[i].dimension);
    coordDim = dimInfo && dimInfo.coordDim;
    // Can only be x or y
    if (coordDim === 'x' || coordDim === 'y') {
      visualMeta = visualMetaList[i];
      break;
    }
  }
  if (!visualMeta) {
    if (process.env.NODE_ENV !== 'production') {
      console.warn('Visual map on line style only support x or y dimension.');
    }
    return;
  }
  // If the area to be rendered is bigger than area defined by LinearGradient,
  // the canvas spec prescribes that the color of the first stop and the last
  // stop should be used. But if two stops are added at offset 0, in effect
  // browsers use the color of the second stop to render area outside
  // LinearGradient. So we can only infinitesimally extend area defined in
  // LinearGradient to render `outerColors`.
  var axis = coordSys.getAxis(coordDim);
  // dataToCoord mapping may not be linear, but must be monotonic.
  var colorStops = map(visualMeta.stops, function (stop) {
    // offset will be calculated later.
    return {
      coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
      color: stop.color
    };
  });
  var stopLen = colorStops.length;
  var outerColors = visualMeta.outerColors.slice();
  if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
    colorStops.reverse();
    outerColors.reverse();
  }
  var colorStopsInRange = clipColorStops(colorStops, coordDim === 'x' ? api.getWidth() : api.getHeight());
  var inRangeStopLen = colorStopsInRange.length;
  if (!inRangeStopLen && stopLen) {
    // All stops are out of range. All will be the same color.
    return colorStops[0].coord < 0 ? outerColors[1] ? outerColors[1] : colorStops[stopLen - 1].color : outerColors[0] ? outerColors[0] : colorStops[0].color;
  }
  var tinyExtent = 10; // Arbitrary value: 10px
  var minCoord = colorStopsInRange[0].coord - tinyExtent;
  var maxCoord = colorStopsInRange[inRangeStopLen - 1].coord + tinyExtent;
  var coordSpan = maxCoord - minCoord;
  if (coordSpan < 1e-3) {
    return 'transparent';
  }
  each(colorStopsInRange, function (stop) {
    stop.offset = (stop.coord - minCoord) / coordSpan;
  });
  colorStopsInRange.push({
    // NOTE: inRangeStopLen may still be 0 if stoplen is zero.
    offset: inRangeStopLen ? colorStopsInRange[inRangeStopLen - 1].offset : 0.5,
    color: outerColors[1] || 'transparent'
  });
  colorStopsInRange.unshift({
    offset: inRangeStopLen ? colorStopsInRange[0].offset : 0.5,
    color: outerColors[0] || 'transparent'
  });
  var gradient = new graphic.LinearGradient(0, 0, 0, 0, colorStopsInRange, true);
  gradient[coordDim] = minCoord;
  gradient[coordDim + '2'] = maxCoord;
  return gradient;
}
function getAreaGradient(data, seriesModel, api) {
  var colorStopsInRange = [];
  var areaGradient = seriesModel.get('areaGradient');
  var height = api.getHeight();
  var valueByType = {
    start: 0,
    end: 1
  };
  if (!areaGradient) {
    return;
  }
  var coordSys = seriesModel.coordinateSystem;
  var axis = coordSys.getAxis('y');
  // const extent = axis.getExtent();
  // const span = extent[1] - extent[0];
  each(areaGradient, function (item) {
    var _a;
    var offset = (_a = valueByType[item.type]) !== null && _a !== void 0 ? _a : axis.toGlobalCoord(axis.dataToCoord(item.value)) / height;
    if (offset < 0 || offset > 1) {
      return;
    }
    colorStopsInRange.push({
      color: item.color,
      offset: offset
    });
  });
  var gradient = new graphic.LinearGradient(0, 0, 0, height, colorStopsInRange, true);
  return gradient;
}
var LinesPlotView = /** @class */function (_super) {
  __extends(LinesPlotView, _super);
  function LinesPlotView() {
    var _this = _super !== null && _super.apply(this, arguments) || this;
    _this.type = LinesPlotView.type;
    return _this;
  }
  LinesPlotView.prototype.init = function () {
    // const lineGroup = new graphic.Group();
    // const symbolDraw = new SymbolDraw();
    // this.group.add(symbolDraw.group);
    // this._symbolDraw = symbolDraw;
    // this._lineGroup = lineGroup;
    // this.group.add(this._lineGroup);
  };
  LinesPlotView.prototype.render = function (seriesModel, ecModel, api) {
    var data = seriesModel.getData();
    var groupId = seriesModel.get('groupId');
    this._renderLine(data, seriesModel, api);
    this._renderArea(data, seriesModel, api);
    this._renderSymbol(data, seriesModel);
    this._renderHistogram(data, seriesModel);
    this._renderBar(data, seriesModel);
    var clipPath = seriesModel.get('clip', true) && createClipPath(seriesModel.coordinateSystem, false, seriesModel);
    if (clipPath) {
      this.group.setClipPath(clipPath);
    } else {
      this.group.removeClipPath();
    }
    // this._lastZlevel = zlevel;
    toggleHoverEmphasis(this.group, null, null, false);
    getECData(this.group).groupId = groupId;
    this._finished = true;
  };
  LinesPlotView.prototype._getClipShape = function (seriesModel) {
    if (!seriesModel.get('clip', true)) {
      return;
    }
    var coordSys = seriesModel.coordinateSystem;
    // PENDING make `0.1` configurable, for example, `clipTolerance`?
    return coordSys && coordSys.getArea && coordSys.getArea(.1);
  };
  LinesPlotView.prototype._renderLine = function (data, seriesModel, api) {
    var linePointsByKey = data.getLayout('linePointsByKey');
    var lineVisible = seriesModel.get('lineVisible');
    if (lineVisible) {
      var emphasisState_1 = seriesModel.get('emphasis').emphasisState;
      if (!this._lineGroup) {
        this._lineGroup = new graphic.Group();
        this.group.add(this._lineGroup);
      } else {
        this._lineGroup.removeAll();
      }
      var lineGroup_1 = this._lineGroup;
      var z2_1 = seriesModel.get('z2');
      // const isGradient = data.getLayout('isGradient');
      // if (isGradient) {
      //     const pointInfos = data.getLayout('pointInfos');
      //     const el = new GradientLinePath({
      //         shape: {
      //             points: pointInfos,
      //         },
      //         style: {
      //             fill: 'none',
      //             stroke: '#000000',
      //             lineWidth: pointInfos[0].width,
      //             lineJoin: 'round',
      //             lineDash: 'solid',
      //         },
      //         z2: z2,
      //     });
      //     el.states.emphasis = emphasisState;
      //     lineGroup.add(el);
      //     return;
      // }
      var visualColor_1 = getVisualGradient(data, seriesModel.coordinateSystem, api);
      var connectNulls_1 = seriesModel.get('connectNulls');
      var isMobile_1 = seriesModel.get('isMobile');
      var step_1 = seriesModel.get('step');
      var barSpace_1 = Math.floor((seriesModel.coordinateSystem.getAxesByScale('ordinal')[0].scale.barSpace || calculatebandWidth(seriesModel, data)) * 0.8) || 1;
      each(linePointsByKey, function (item, key) {
        var _a = key.split(':'),
          stroke = _a[0],
          lineDash = _a[1],
          lineWidth = _a[2];
        var _b = getFormatColor(stroke),
          color = _b.color,
          isDefaultColor = _b.isDefaultColor;
        if (stroke === 'transparent' && !visualColor_1) {
          return;
        }
        var el = new LinePlotPath({
          shape: {
            points: item,
            connectSelf: !connectNulls_1 && !step_1,
            barWidth: barSpace_1,
            stroke: color,
            isWebviewRender: isMobile_1
          },
          style: {
            lineDash: lineStyleMap[lineDash],
            stroke: visualColor_1 || color,
            lineWidth: +lineWidth,
            lineCap: 'round',
            lineJoin: 'round'
          },
          z2: isDefaultColor ? LastZ2 : z2_1
        });
        el.states.emphasis = emphasisState_1;
        lineGroup_1.add(el);
      });
    } else if (this._lineGroup) {
      this._lineGroup.removeAll();
      this.group.remove(this._lineGroup);
      this._lineGroup = null;
    }
  };
  LinesPlotView.prototype._renderArea = function (data, seriesModel, api) {
    var areaVisible = seriesModel.get('areaVisible');
    var emphasisState = seriesModel.get('emphasis').emphasisState;
    if (areaVisible) {
      if (!this._polygonGroup) {
        this._polygonGroup = new graphic.Group();
        this.group.add(this._polygonGroup);
      } else {
        this._polygonGroup.removeAll();
      }
      var linePointsByKey = data.getLayout('linePointsByKey');
      var polygonGroup_1 = this._polygonGroup;
      var histbase = seriesModel.get('histbase') || 0;
      var z2_2 = seriesModel.get('z2');
      var baseY_1 = seriesModel.coordinateSystem.dataToPoint([0, histbase], true)[1];
      var visualColor_2 = getAreaGradient(data, seriesModel, api);
      var connectNulls_2 = seriesModel.get('connectNulls');
      var step_2 = seriesModel.get('step');
      var barSpace_2 = Math.floor((seriesModel.coordinateSystem.getAxesByScale('ordinal')[0].scale.barSpace || calculatebandWidth(seriesModel, data)) * 0.8) || 1;
      each(linePointsByKey, function (item, key) {
        var stroke = key.split(':')[0];
        var _a = getFormatColor(stroke),
          color = _a.color,
          isDefaultColor = _a.isDefaultColor;
        var el = new PolyPlotPath({
          shape: {
            points: item,
            baseY: baseY_1,
            connectSelf: !connectNulls_2 && !step_2,
            barWidth: barSpace_2
          },
          style: {
            stroke: 'none',
            fill: visualColor_2 || color,
            lineJoin: 'round'
          },
          z2: isDefaultColor ? LastZ2 : z2_2
        });
        el.states.emphasis = emphasisState;
        polygonGroup_1.add(el);
      });
    } else if (this._polygonGroup) {
      this._polygonGroup.removeAll();
      this.group.remove(this._polygonGroup);
      this._polygonGroup = null;
    }
  };
  LinesPlotView.prototype._renderHistogram = function (data, seriesModel) {
    var histogramVisible = seriesModel.get('histogramVisible');
    var emphasisState = seriesModel.get('emphasis').emphasisState;
    if (histogramVisible) {
      if (!this._histogramGroup) {
        this._histogramGroup = new graphic.Group();
        this.group.add(this._histogramGroup);
      } else {
        this._histogramGroup.removeAll();
      }
      var linePointsByKey = data.getLayout('linePointsByKey');
      var histogramGroup_1 = this._histogramGroup;
      var histbase = seriesModel.get('histbase') || 0;
      var z2_3 = seriesModel.get('z2');
      var isMobile_2 = seriesModel.get('isMobile');
      var baseY_2 = seriesModel.coordinateSystem.dataToPoint([0, histbase], true)[1];
      each(linePointsByKey, function (item, key) {
        var _a = key.split(':'),
          stroke = _a[0],
          lineDash = _a[1],
          lineWidth = _a[2];
        var _b = getFormatColor(stroke),
          color = _b.color,
          isDefaultColor = _b.isDefaultColor;
        var el = new HistogramPlotPath({
          shape: {
            points: item,
            baseY: baseY_2,
            stroke: color,
            isWebviewRender: isMobile_2
          },
          style: {
            stroke: color,
            lineWidth: +lineWidth
          },
          z2: isDefaultColor ? LastZ2 : z2_3
        });
        el.states.emphasis = emphasisState;
        histogramGroup_1.add(el);
      });
    } else if (this._histogramGroup) {
      this._histogramGroup.removeAll();
      this.group.remove(this._histogramGroup);
      this._histogramGroup = null;
    }
  };
  LinesPlotView.prototype._renderSymbol = function (data, seriesModel) {
    var symbolVisible = seriesModel.get('symbolVisible');
    var symbolPointsByColor = data.getLayout('symbolPointsByColor');
    var shadowShape = seriesModel.get('shadowShape');
    if (symbolVisible) {
      var emphasisState_2 = seriesModel.get('emphasis').emphasisState;
      if (!this._symbolGroup) {
        this._symbolGroup = new graphic.Group();
        this.group.add(this._symbolGroup);
      } else {
        this._symbolGroup.removeAll();
      }
      var symbolGroup_1 = this._symbolGroup;
      var z2_4 = seriesModel.get('z2');
      var isMobile_3 = seriesModel.get('isMobile');
      each(symbolPointsByColor, function (item, key) {
        // const [type] = key.split("_");
        if (shadowShape) {
          var shadowEl = new SymbolPath({
            shape: {
              points: item,
              isShadow: true
            },
            style: {
              // fill: stroke,
              opacity: 0.3
            },
            z2: z2_4
          });
          shadowEl.symbolProxy = createSymbol(key, 0, 0, 0, 0);
          shadowEl.states.emphasis = emphasisState_2;
          symbolGroup_1.add(shadowEl);
        }
        var el = new SymbolPath({
          shape: {
            points: item,
            isWebviewRender: isMobile_3
          },
          style: {
            fill: '#000000'
          },
          z2: z2_4
        });
        el.symbolProxy = createSymbol(key, 0, 0, 0, 0);
        el.states.emphasis = emphasisState_2;
        //  el.symbolProxy.setColor("pink")
        //  console.log('%c [ symbolProxy ]-228', 'font-size:13px; background:pink; color:#bf2c9f;', el.symbolProxy)
        symbolGroup_1.add(el);
      });
    } else if (this._symbolGroup) {
      this._symbolGroup.removeAll();
      this.group.remove(this._symbolGroup);
      this._symbolGroup = null;
    }
    // const symbolDraw = this._symbolDraw;
    // if (symbolVisible) {
    //     const symbolDraw = this._updateSymbolDraw(data, seriesModel);
    //     const points = data.getLayout('points') as number[] || [];
    //     symbolDraw.updateData(data as any, {
    //         // isIgnore: getIsIgnoreFunc(seriesModel, data, seriesModel.coordinateSystem as Cartesian2D),
    //         // TODO
    //         // If this parameter should be a shape or a bounding volume
    //         // shape will be more general.
    //         // But bounding volume like bounding rect will be much faster in the contain calculation
    //         clipShape: this._getClipShape(seriesModel),
    //         disableAnimation: true,
    //         getSymbolPoint(idx) {
    //             return [points[idx * 2], points[idx * 2 + 1]];
    //         }
    //     });
    // } else if(symbolDraw){
    //     symbolDraw.remove();
    //     this._symbolDraw = null
    // }
  };

  LinesPlotView.prototype._renderBar = function (data, seriesModel) {
    var barVisible = seriesModel.get('barVisible');
    if (barVisible) {
      var emphasisState_3 = seriesModel.get('emphasis').emphasisState;
      if (!this._barGroup) {
        this._barGroup = new graphic.Group();
        this.group.add(this._barGroup);
      } else {
        this._barGroup.removeAll();
      }
      var linePointsByKey = data.getLayout('linePointsByKey');
      var isGradient = data.getLayout('isGradient');
      var barGroup_1 = this._barGroup;
      var histbase = seriesModel.get('histbase') || 0;
      var z2_5 = seriesModel.get('z2');
      var barSpace = seriesModel.coordinateSystem.getAxesByScale('ordinal')[0].scale.barSpace || calculatebandWidth(seriesModel, data);
      // console.log('%c [ barSpace ]-271', 'font-size:13px; background:pink; color:#bf2c9f;', barSpace)
      var width_1 = barSpace;
      var baseY_3 = seriesModel.coordinateSystem.dataToPoint([0, histbase])[1];
      if (isGradient) {
        var pointInfos = data.getLayout('pointInfos');
        if (width_1 <= 1) {
          var el_1 = new GradientHistogramPlotPath({
            shape: {
              points: pointInfos,
              baseY: baseY_3
            },
            style: {
              stroke: '#000',
              fill: 'none'
            },
            z2: z2_5
          });
          el_1.states.emphasis = emphasisState_3;
          barGroup_1.add(el_1);
          return;
        }
        var el = new GradientBarPath({
          shape: {
            points: pointInfos,
            baseY: baseY_3,
            width: width_1
          },
          style: {
            fill: '#000000',
            stroke: 'none'
          },
          z2: z2_5
        });
        el.states.emphasis = emphasisState_3;
        barGroup_1.add(el);
        return;
      }
      if (width_1 <= 1) {
        each(linePointsByKey, function (item, key) {
          var stroke = key.split(':')[0];
          var _a = getFormatColor(stroke),
            color = _a.color,
            isDefaultColor = _a.isDefaultColor;
          var el = new HistogramPlotPath({
            shape: {
              points: item,
              baseY: baseY_3
            },
            style: {
              stroke: color
            },
            z2: isDefaultColor ? LastZ2 : z2_5
          });
          el.states.emphasis = emphasisState_3;
          barGroup_1.add(el);
        });
        return;
      }
      var isMobile_4 = seriesModel.get('isMobile');
      each(linePointsByKey, function (item, key) {
        var stroke = key.split(':')[0];
        var _a = getFormatColor(stroke),
          color = _a.color,
          isDefaultColor = _a.isDefaultColor;
        var el = new BarPath({
          shape: {
            points: item,
            baseY: baseY_3,
            width: width_1,
            isWebviewRender: isMobile_4,
            fill: color
          },
          style: {
            fill: color
          },
          z2: isDefaultColor ? LastZ2 : z2_5
        });
        el.states.emphasis = emphasisState_3;
        barGroup_1.add(el);
      });
    } else if (this._barGroup) {
      this._barGroup.removeAll();
      this.group.remove(this._barGroup);
      this._barGroup = null;
    }
  };
  LinesPlotView.prototype._updateSymbolDraw = function (data, seriesModel) {
    var symbolDraw = this._symbolDraw;
    if (!symbolDraw) {
      symbolDraw = new SymbolDraw();
      this._symbolDraw = symbolDraw;
    }
    // else {
    //     symbolDraw.remove();
    // }
    // const pipelineContext = seriesModel.pipelineContext;
    // const isLargeDraw = pipelineContext.large;
    // if (!symbolDraw || isLargeDraw !== this._isLargeDraw) {
    //     symbolDraw && symbolDraw.remove();
    //     symbolDraw = this._symbolDraw = isLargeDraw
    //         ? new LargeSymbolDraw()
    //         : new SymbolDraw();
    //     this._isLargeDraw = isLargeDraw;
    //     this.group.removeAll();
    // }
    this.group.add(symbolDraw.group);
    return symbolDraw;
  };
  LinesPlotView.prototype.remove = function (ecModel, api) {
    // this._lineDraw && this._lineDraw.remove();
    // this._lineDraw = null;
    // Clear motion when lineDraw is removed
    // this._clearLayer(api);
    this._lineGroup && this._lineGroup.removeAll();
    this._lineGroup = null;
    this._polygonGroup && this._polygonGroup.removeAll();
    this._polygonGroup = null;
    // this._symbolDraw && this._symbolDraw.remove();
    // this._symbolDraw = null;
    this._symbolGroup && this._symbolGroup.removeAll();
    this._symbolGroup = null;
    this._histogramGroup && this._histogramGroup.removeAll();
    this._histogramGroup = null;
    this._barGroup && this._barGroup.removeAll();
    this._barGroup = null;
    // this.group.removeAll();
  };

  LinesPlotView.prototype.dispose = function (ecModel, api) {
    this.remove(ecModel, api);
    // this._lineGroup.removeAll();
  };

  LinesPlotView.type = 'linesPlot';
  return LinesPlotView;
}(ChartView);
export default LinesPlotView;