
/*
* 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 { subPixelOptimize } from '../../util/graphic.js';
import createRenderPlanner from '../helper/createRenderPlanner.js';
import { each, map } from 'tvrender/lib/core/util.js';
import { isMobileRender } from "../../util/mobile.js";
import { contrastColor } from '../../util/color.js';
import { DynamicTypedArray } from '../../util/DynamicTypedArray.js';
var positiveBorderColorQuery = ['itemStyle', 'borderColor'];
var negativeBorderColorQuery = ['itemStyle', 'borderColor0'];
var dojiBorderColorQuery = ['itemStyle', 'borderColorDoji'];
var positiveColorQuery = ['itemStyle', 'color'];
var negativeColorQuery = ['itemStyle', 'color0'];
var positiveWickColorQuery = ['itemStyle', 'wickColor'];
var negativeWickColorQuery = ['itemStyle', 'wickColor0'];
function getFormatSumVol(vol) {
  if (vol > 1000000) {
    return vol / 1000000;
  } else if (vol > 1000) {
    return vol / 1000;
  }
  return vol;
}
function getColor(sign, model, ignoreParentColor) {
  return model.get(sign > 0 ? positiveColorQuery : negativeColorQuery, ignoreParentColor);
}
function getBorderColor(sign, model, ignoreParentColor) {
  return model.get(sign === 0 ? dojiBorderColorQuery : sign > 0 ? positiveBorderColorQuery : negativeBorderColorQuery, ignoreParentColor);
}
function getWickColor(sign, model, ignoreParentColor) {
  return model.get(sign > 0 ? positiveWickColorQuery : negativeWickColorQuery, ignoreParentColor);
}
var buyVolColor = "#089981";
var sellVolColor = "#f23645";
var unbalancedWidth = 3;
var volPathLayout = {
  seriesType: 'volPath',
  plan: createRenderPlanner(),
  reset: function (seriesModel) {
    var coordSys = seriesModel.coordinateSystem;
    var data = seriesModel.getData();
    var _a = calculateCandleWidth(seriesModel, data),
      candleWidth = _a.candleWidth,
      bandWidth = _a.bandWidth,
      textRectWidth = _a.textRectWidth,
      gapWidth = _a.gapWidth,
      totalWidth = _a.totalWidth;
    var cDimIdx = 0;
    var vDimIdx = 1;
    var coordDims = ['x', 'y'];
    var cDimI = data.getDimensionIndex(data.mapDimension(coordDims[cDimIdx]));
    var vDimsI = map(data.mapDimensionsAll(coordDims[vDimIdx]), data.getDimensionIndex, data);
    var openDimI = vDimsI[0];
    var closeDimI = vDimsI[1];
    var lowestDimI = vDimsI[2];
    var highestDimI = vDimsI[3];
    var isSimpleBox = candleWidth <= 1.3;
    // 85
    var showTotal = bandWidth >= 80 && seriesModel.get('isShowSummary');
    var showRect = textRectWidth >= 2;
    var showText = textRectWidth >= 15;
    if (cDimI < 0 || vDimsI.length < 4) {
      return;
    }
    var showLast = seriesModel.get('showLast');
    var ignoreParentColor = seriesModel.get('ignoreParentColor');
    var isShowPoc = seriesModel.get('isShowPoc');
    var theme = seriesModel.get('theme');
    var isShowVA = seriesModel.get('isShowVA');
    var isShowFvg = seriesModel.get('isShowFvg') && bandWidth > 10;
    var isGradientBgColor = seriesModel.get('isGradientBgColor');
    var displayMode = seriesModel.get('displayMode');
    var isOverview = displayMode === 'overview';
    var infoType = seriesModel.get('infoType');
    var isBuyAndSell = infoType === 'buyAndSell';
    var isDelta = infoType === 'delta';
    var isTotal = infoType === 'total';
    var isLadder = infoType === 'ladder';
    var isBuyAndSellLadder = isBuyAndSell || isLadder;
    // const lineHeight = seriesModel.get('lineHeight');
    var yAxis = coordSys.getAxis('y');
    // const rectHeight = yAxis.dataToCoord(lineHeight);
    var itemStyle = seriesModel.get('itemStyle');
    var isDark = theme === 'dark';
    var lightweight = theme === 'dark' ? 200 : 100;
    var textFill = isDark ? "#fff" : "#000";
    var sellBgList = itemStyle.sellBgList,
      pocColor = itemStyle.pocColor,
      buyBgColor = itemStyle.buyBgColor,
      sellBgColor = itemStyle.sellBgColor,
      buyBgList = itemStyle.buyBgList,
      totalBgList = itemStyle.totalBgList,
      buyFvgColor = itemStyle.buyFvgColor,
      sellFvgColor = itemStyle.sellFvgColor;
    var offsetX = isMobileRender ? 0 : 0.5;
    var formatY = isMobileRender ? function (y) {
      return y;
    } : function (y) {
      return Math.floor(y);
    };
    return {
      progress: normalProgress
    };
    function normalProgress(params, candleData) {
      var store = candleData.getStore();
      var bodyPointsByColor = {};
      var wickPointsByColor = {};
      var rectPointsByColor = new Map();
      var textPointsByColor = new Map();
      var totalPointsByColor = new Map();
      var unbalancedPointsByColor = new Map();
      if (isShowFvg) {
        if (!unbalancedPointsByColor.get(sellFvgColor)) {
          unbalancedPointsByColor.set(sellFvgColor, new DynamicTypedArray());
        }
        if (!unbalancedPointsByColor.get(buyFvgColor)) {
          unbalancedPointsByColor.set(buyFvgColor, new DynamicTypedArray());
        }
      }
      var sumPoints = new DynamicTypedArray(900);
      var vaPoints = new DynamicTypedArray(900);
      var textColorByBg = new Map();
      var lastIndex = candleData.count(true) - 1;
      var maxSumVol = 0;
      var maxFSumVol = 0;
      var rectHeight = 0;
      for (var dataIndex = params.start; dataIndex < params.end; dataIndex++) {
        if (showLast && lastIndex - candleData.getRawIndex(dataIndex) >= showLast) {
          continue;
        }
        var axisDimVal = store.get(cDimI, dataIndex);
        var openVal = store.get(openDimI, dataIndex);
        var closeVal = store.get(closeDimI, dataIndex);
        var lowestVal = store.get(lowestDimI, dataIndex);
        var highestVal = store.get(highestDimI, dataIndex);
        var ocLow = Math.min(openVal, closeVal);
        var ocHigh = Math.max(openVal, closeVal);
        var _a = coordSys.dataToPoint([axisDimVal, ocLow]),
          ocLowX = _a[0],
          ocLowY = _a[1];
        var x = ocLowX + offsetX;
        var ocLowPoint = [x, formatY(ocLowY)];
        var ocHighPoint = coordSys.dataToPoint([axisDimVal, ocHigh]);
        ocHighPoint[0] = x;
        ocHighPoint[1] = formatY(ocHighPoint[1]);
        var lowestPoint = coordSys.dataToPoint([axisDimVal, lowestVal]);
        lowestPoint[0] = x;
        lowestPoint[1] = formatY(lowestPoint[1]);
        var highestPoint = coordSys.dataToPoint([axisDimVal, highestVal]);
        highestPoint[0] = x;
        highestPoint[1] = formatY(highestPoint[1]);
        var itemModel = candleData.getItemModel(dataIndex);
        // const hasDojiColor = !!itemModel.get(['itemStyle', 'borderColorDoji']);
        var sign = getSign(store, dataIndex, openVal, closeVal, closeDimI, false);
        var color = getColor(sign, itemModel, ignoreParentColor);
        var border = getBorderColor(sign, itemModel, ignoreParentColor);
        if (!color && !border) {
          continue;
        }
        var key = (color || 'none') + ":" + (border || 'none');
        var bodyPoints = bodyPointsByColor[key] || [];
        if (isSimpleBox) {
          bodyPoints.push(ocHighPoint, lowestPoint);
        } else {
          addBodyEnd(bodyPoints, ocHighPoint, 0);
          addBodyEnd(bodyPoints, ocLowPoint, 1);
        }
        if (!bodyPointsByColor[key]) bodyPointsByColor[key] = bodyPoints;
        var wickKey = getWickColor(sign, itemModel, ignoreParentColor);
        if (wickKey) {
          var wickPoint = wickPointsByColor[wickKey] || [];
          wickPoint.push(highestPoint, ocHighPoint, lowestPoint, ocLowPoint);
          if (!wickPointsByColor[wickKey]) wickPointsByColor[wickKey] = wickPoint;
        }
        var volList = itemModel.option.itemData.volList;
        if (showRect && volList) {
          handleRectText(itemModel, ocLowX);
        }
      }
      candleData.setLayout({
        bodyPointsByColor: bodyPointsByColor,
        wickPointsByColor: wickPointsByColor,
        isSimpleBox: isSimpleBox,
        rectPointsByColor: rectPointsByColor,
        textPointsByColor: textPointsByColor,
        textRectWidth: textRectWidth,
        rectHeight: rectHeight,
        totalPointsByColor: totalPointsByColor,
        isOverview: isOverview,
        maxSumVol: maxSumVol,
        isBuyAndSellLadder: isBuyAndSellLadder,
        sumPoints: sumPoints,
        totalWidth: totalWidth,
        vaPoints: vaPoints,
        bandWidth: bandWidth,
        unbalancedPointsByColor: unbalancedPointsByColor,
        gapWidth: gapWidth
      });
      function handleRectText(itemModel, ocLowX) {
        var _a = itemModel.option.itemData,
          sellSum = _a.sellSum,
          buySum = _a.buySum,
          pocIndex = _a.pocIndex,
          volList = _a.volList,
          total = _a.total,
          maxBuy = _a.maxBuy,
          maxSell = _a.maxSell,
          delta = _a.delta,
          vahPrice = _a.vahPrice,
          valPrice = _a.valPrice;
        var sellX = isOverview ? ocLowX - gapWidth : ocLowX - gapWidth - textRectWidth;
        var buyX = ocLowX + gapWidth + 1;
        var leftX = buyX;
        var firstBottomY = 0;
        var maxVol = Math.max(maxBuy, maxSell);
        var maxFVol = getFormatSumVol(maxVol);
        if (maxFVol > maxFSumVol) {
          maxSumVol = maxVol;
          maxFSumVol = maxFVol;
        }
        // const pocItem = volList[pocIndex];
        each(volList, function (item, i) {
          var buyColorKey = buyBgColor;
          var sellColorKey = sellBgColor;
          var isPoc = isShowPoc && i === pocIndex;
          if (isPoc) {
            buyColorKey = pocColor;
            sellColorKey = pocColor;
          } else if (isTotal) {
            var tColorIndex = Math.floor((item.sellVol + item.buyVol) / total / 0.25);
            buyColorKey = totalBgList[tColorIndex];
            // sellColorKey = totalBgList[tColorIndex];
          } else if (isGradientBgColor) {
            var sColorIndex = sellSum ? Math.floor(item.sellVol / sellSum / 0.25) : 0;
            var bColorIndex = buySum ? Math.floor(item.buyVol / buySum / 0.25) : 0;
            buyColorKey = buyBgList[Math.min(bColorIndex, 3)];
            sellColorKey = sellBgList[Math.min(sColorIndex, 3)];
          }
          var bottomY = Math.floor(yAxis.toGlobalCoord(yAxis.dataToCoord(item.lPrice)));
          var topY = Math.floor(yAxis.toGlobalCoord(yAxis.dataToCoord(item.hPrice))) + 1;
          if (i === 0) {
            firstBottomY = Math.max(bottomY, topY);
          }
          if (isBuyAndSell || isLadder) {
            var showSell = isBuyAndSell || item.sellVol > item.buyVol || isPoc;
            var showBuy = isBuyAndSell || item.buyVol > item.sellVol || isPoc;
            var sellWidthPct = item.sellVol / maxSell;
            if (showSell) {
              var sellRectPoint = rectPointsByColor.get(sellColorKey) || new DynamicTypedArray(800);
              sellRectPoint.push(sellX);
              sellRectPoint.push(topY);
              sellRectPoint.push(isOverview ? -Math.max(Math.round(textRectWidth * sellWidthPct), 1) : textRectWidth);
              sellRectPoint.push(bottomY - topY);
              if (!rectPointsByColor.get(sellColorKey)) {
                rectPointsByColor.set(sellColorKey, sellRectPoint);
              }
            }
            var buyWidthPct = item.buyVol / maxBuy;
            if (showBuy) {
              var buyRectPoint = rectPointsByColor.get(buyColorKey) || new DynamicTypedArray(800);
              buyRectPoint.push(buyX);
              buyRectPoint.push(topY);
              buyRectPoint.push(isOverview ? Math.max(Math.round(textRectWidth * buyWidthPct), 1) : textRectWidth);
              buyRectPoint.push(bottomY - topY);
              if (!rectPointsByColor.get(buyColorKey)) {
                rectPointsByColor.set(buyColorKey, buyRectPoint);
              }
            }
            if (isShowFvg) {
              if (item.isSellFvg) {
                var sellUnBLPoint = unbalancedPointsByColor.get(sellFvgColor);
                sellUnBLPoint.push(sellX + (isOverview ? 1 : -1));
                sellUnBLPoint.push(topY);
                sellUnBLPoint.push(isOverview ? unbalancedWidth : -unbalancedWidth);
                sellUnBLPoint.push(bottomY - topY);
              }
              if (item.isBuyFvg) {
                var buyUnBlPoint = unbalancedPointsByColor.get(buyFvgColor);
                buyUnBlPoint.push(isOverview ? buyX - 1 : buyX + textRectWidth + 1);
                buyUnBlPoint.push(topY);
                buyUnBlPoint.push(isOverview ? -unbalancedWidth : unbalancedWidth);
                buyUnBlPoint.push(bottomY - topY);
              }
            }
            if (showText) {
              if (!rectHeight) {
                rectHeight = Math.abs(bottomY - topY);
              }
              var buyTextColor = showBuy ? getContrastColor(buyColorKey) : textFill;
              var sellTextColor = showSell ? getContrastColor(sellColorKey) : textFill;
              var textY = (bottomY + topY) / 2;
              var sellTextPoint = textPointsByColor.get(sellTextColor) || new DynamicTypedArray(800);
              sellTextPoint.push(isOverview ? sellX : sellX + textRectWidth / 2);
              sellTextPoint.push(textY);
              sellTextPoint.push(item.sellVol);
              sellTextPoint.push(isOverview ? -1 : 0);
              if (isOverview) {
                sellTextPoint.push(-Math.max(Math.round(textRectWidth * sellWidthPct), 1));
              }
              if (!textPointsByColor.get(sellTextColor)) {
                textPointsByColor.set(sellTextColor, sellTextPoint);
              }
              var buyTextPoint = textPointsByColor.get(buyTextColor) || new DynamicTypedArray(800);
              buyTextPoint.push(isOverview ? buyX : buyX + textRectWidth / 2);
              buyTextPoint.push(textY);
              buyTextPoint.push(item.buyVol);
              buyTextPoint.push(isOverview ? 1 : 0);
              if (isOverview) {
                buyTextPoint.push(Math.max(Math.round(textRectWidth * buyWidthPct), 1));
              }
              if (!textPointsByColor.get(buyTextColor)) {
                textPointsByColor.set(buyTextColor, buyTextPoint);
              }
            }
          } else {
            // const textColor = getContrastColor(buyColorKey);
            var rectWidth = textRectWidth * 2;
            // 如果为求差值 则哪个方向的成交量大就用那个
            if (isDelta && item.buyVol < item.sellVol) {
              buyColorKey = sellColorKey;
            }
            var buyRectPoint = rectPointsByColor.get(buyColorKey) || new DynamicTypedArray(800);
            var widthPct = item.buyVol / maxBuy;
            buyRectPoint.push(leftX);
            buyRectPoint.push(topY);
            buyRectPoint.push(isOverview ? Math.ceil(rectWidth * widthPct) : rectWidth);
            buyRectPoint.push(bottomY - topY);
            if (!rectPointsByColor.get(buyColorKey)) {
              rectPointsByColor.set(buyColorKey, buyRectPoint);
            }
            if (isShowFvg) {
              if (item.isSellFvg) {
                var sellUnBLPoint = unbalancedPointsByColor.get(sellFvgColor);
                sellUnBLPoint.push(isOverview ? leftX - 4 : leftX - 1);
                sellUnBLPoint.push(topY);
                sellUnBLPoint.push(-4);
                sellUnBLPoint.push(bottomY - topY);
              }
              if (item.isBuyFvg) {
                var buyUnBlPoint = unbalancedPointsByColor.get(buyFvgColor);
                buyUnBlPoint.push(isOverview ? leftX - 1 : leftX + rectWidth + 1);
                buyUnBlPoint.push(topY);
                buyUnBlPoint.push(isOverview ? -unbalancedWidth : unbalancedWidth);
                buyUnBlPoint.push(bottomY - topY);
              }
            }
            if (showText) {
              if (!rectHeight) {
                rectHeight = Math.abs(bottomY - topY);
              }
              var textColor = getContrastColor(buyColorKey);
              var text = isDelta ? item.buyVol - item.sellVol : item.buyVol + item.sellVol;
              var textY = (bottomY + topY) / 2;
              var textPoint = textPointsByColor.get(textColor) || new DynamicTypedArray(800);
              textPoint.push(isOverview ? leftX : leftX + textRectWidth);
              textPoint.push(textY);
              textPoint.push(text);
              textPoint.push(isOverview ? 1 : 0);
              if (isOverview) {
                textPoint.push(Math.ceil(rectWidth * widthPct));
              }
              if (!textPointsByColor.get(textColor)) {
                textPointsByColor.set(textColor, textPoint);
              }
            }
          }
        });
        if (showTotal) {
          if (isBuyAndSell || isLadder) {
            var buyTotalPoint = totalPointsByColor.get(buyVolColor) || new DynamicTypedArray(800);
            buyTotalPoint.push(buyX + textRectWidth / 2);
            buyTotalPoint.push(firstBottomY);
            buyTotalPoint.push(buySum);
            if (!totalPointsByColor.get(buyVolColor)) {
              totalPointsByColor.set(buyVolColor, buyTotalPoint);
            }
            var sellTotalPoint = totalPointsByColor.get(sellVolColor) || new DynamicTypedArray(800);
            sellTotalPoint.push(isOverview ? ocLowX - gapWidth - textRectWidth / 2 : sellX + textRectWidth / 2);
            sellTotalPoint.push(firstBottomY);
            sellTotalPoint.push(sellSum);
            if (!totalPointsByColor.get(sellVolColor)) {
              totalPointsByColor.set(sellVolColor, sellTotalPoint);
            }
            sumPoints.push(ocLowX - gapWidth - textRectWidth);
            sumPoints.push(firstBottomY);
            sumPoints.push(delta);
            sumPoints.push(total);
          } else {
            sumPoints.push(ocLowX - candleWidth / 2);
            sumPoints.push(firstBottomY);
            sumPoints.push(delta);
            sumPoints.push(total);
            sumPoints.push(buySum);
            sumPoints.push(sellSum);
          }
        }
        if (isShowVA) {
          var x1 = isBuyAndSellLadder ? ocLowX - gapWidth - textRectWidth : leftX;
          var x2 = isBuyAndSellLadder ? ocLowX + gapWidth + textRectWidth : leftX + textRectWidth * 2;
          var bottomY = Math.floor(yAxis.toGlobalCoord(yAxis.dataToCoord(vahPrice))) + 0.5;
          var topY = Math.floor(yAxis.toGlobalCoord(yAxis.dataToCoord(valPrice))) + 0.5;
          vaPoints.push(x1);
          vaPoints.push(x2);
          vaPoints.push(topY);
          vaPoints.push(bottomY);
        }
      }
      function getContrastColor(bg) {
        if (bg === void 0) {
          bg = '#fff';
        }
        if (textColorByBg.get(bg)) {
          return textColorByBg.get(bg);
        }
        var color = contrastColor(bg, lightweight);
        textColorByBg.set(bg, color);
        return color;
      }
      function addBodyEnd(ends, point, start) {
        var point1 = point.slice();
        var point2 = point.slice();
        // point1[cDimIdx] = subPixelOptimize(
        //     point1[cDimIdx] + candleWidth / 2, 1, false
        // );
        // point2[cDimIdx] = subPixelOptimize(
        //     point2[cDimIdx] - candleWidth / 2, 1, true
        // );
        point1[0] = point1[0] - Math.floor(candleWidth * 0.5);
        point2[0] = point1[0] + candleWidth;
        point1[1] += 0.5;
        point2[1] += 0.5;
        start ? ends.push(point1, point2) : ends.push(point2, point1);
      }
      function subPixelOptimizePoint(point) {
        point[cDimIdx] = subPixelOptimize(point[cDimIdx], 1);
        return point;
      }
    }
  }
};
/**
 * Get the sign of a single data.
 *
 * @returns 0 for doji with hasDojiColor: true,
 *          1 for positive,
 *          -1 for negative.
 */
function getSign(store, dataIndex, openVal, closeVal, closeDimI, hasDojiColor) {
  var sign;
  if (openVal > closeVal) {
    sign = -1;
  } else if (openVal < closeVal) {
    sign = 1;
  } else {
    sign = hasDojiColor
    // When doji color is set, use it instead of color/color0.
    ? 0 : dataIndex > 0
    // If close === open, compare with close of last record
    ? store.get(closeDimI, dataIndex - 1) <= closeVal ? 1 : -1
    // No record of previous, set to be positive
    : 1;
  }
  return sign;
}
export function calculateCandleWidth(seriesModel, data) {
  var baseAxis = seriesModel.getBaseAxis();
  var extent;
  var bandWidth = baseAxis.type === 'category' ? baseAxis.scale.barSpace : (extent = baseAxis.getExtent(), Math.abs(extent[1] - extent[0]) / data.count());
  var barWidth = Math.round(bandWidth * 0.15);
  var candleWidth = Math.max(1, barWidth % 2 === 0 ? barWidth : barWidth - 1);
  var textRectWidth = Math.round(bandWidth * 0.35);
  var gapWidth = Math.round(bandWidth * 0.1);
  return {
    candleWidth: candleWidth,
    textRectWidth: textRectWidth,
    gapWidth: gapWidth,
    bandWidth: bandWidth,
    totalWidth: textRectWidth * 2 + gapWidth * 2
  };
}
export default volPathLayout;