
/*
* 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.
*/
/* global Float32Array */
import createRenderPlanner from '../helper/createRenderPlanner.js';
import { map, each, trim } from 'tvrender/lib/core/util.js';
import { getSymbolLabelFontSize, getSymbolSize } from '../../util/symbolSize.js';
import { getLineHeight, getWidth } from 'tvrender/lib/contain/text.js';
// import { createFloat32Array } from '../../util/vendor.js';
function getYByLocation(seriesModel) {
  var location = seriesModel.get('location');
  if (!['bottom', 'top'].includes(location)) {
    return null;
  }
  var yAxis = seriesModel.coordinateSystem.getAxis('y');
  var scale = yAxis.scale;
  var _a = yAxis.getExtent(),
    end = _a[1];
  var _b = scale.rawExtentInfo.getBoundaryGapInner(),
    boundaryGapX = _b[0],
    boundaryGapY = _b[1];
  return Math.floor(location === 'top' ? end * boundaryGapX : end * (1 - boundaryGapY));
}
var labelSymbols = ['labelDown', 'labelUp', 'labelLeft', 'labelRight', 'labelLowerLeft', 'labelLowerRight', 'labelUpperLeft', 'labelUpperRight', 'labelCenter'];
var upSymbols = ['labelUp', 'labelUpperLeft', 'labelUpperRight'];
var labelSymbolByType = {};
// const belowbarNotSymbol: Record<string, number> = {
//     labelLeft: 1,
//     labelRight: 1,
//     labelCenter: 1
// };
each(labelSymbols, function (type) {
  labelSymbolByType[type] = 1;
});
// const lineSymbols = ['xCross', 'lCross'];
var VPadding = 10;
var HPadding = 8;
function changeLabelOffsetBySymbol(symbol, symbolRect, shape, oldOffset) {
  var offsetX = oldOffset[0],
    offsetY = oldOffset[1];
  switch (symbol) {
    case 'labelDown':
      return [offsetX, offsetY - shape.triangleWidth];
    case 'labelUp':
      return [offsetX, offsetY + shape.triangleWidth];
    case 'labelLeft':
      return [offsetX + shape.triangleWidth + symbolRect[0] / 2, offsetY + symbolRect[1] / 2];
    case 'labelRight':
      return [offsetX - shape.triangleWidth - symbolRect[0] / 2, offsetY + symbolRect[1] / 2];
    case 'labelLowerLeft':
      return [offsetX + shape.offsetX / 2 + symbolRect[0] / 2, offsetY - shape.offsetY];
    case 'labelLowerRight':
      return [offsetX - shape.offsetX - symbolRect[0] / 2, offsetY - shape.offsetY];
    case 'labelUpperLeft':
      return [offsetX + shape.offsetX + symbolRect[0] / 2, offsetY + shape.offsetY];
    case 'labelUpperRight':
      return [offsetX - shape.offsetX - symbolRect[0] / 2, offsetY + shape.offsetY];
    // case 'labelCenter':
    //     return [offsetX, offsetY + symbolRect[1]];
  }

  return oldOffset;
}
// const computedText = new graphic.Text();
var getTextRect = function (text, font) {
  if (text === void 0) {
    text = '';
  }
  var width = 0;
  var height = 0;
  text.split('\n').forEach(function (item) {
    height = height + getLineHeight(font);
    width = Math.max(width, getWidth(item, font));
  });
  return {
    width: width,
    height: height
  };
};
var defaultOffset = [0, 0];
var defaultLabel = {};
var labelsLayout = {
  seriesType: 'labels',
  plan: createRenderPlanner(),
  reset: function (seriesModel, ecModel) {
    var data = seriesModel.getData();
    var coordSys = seriesModel.coordinateSystem;
    // const pipelineContext = seriesModel.pipelineContext;
    if (!coordSys) {
      return;
    }
    var bandWidth = Math.max(1, Math.round(coordSys.getAxesByScale('ordinal')[0].scale.barSpace * 0.8));
    // const bandWidth = getBandWidth(seriesModel, data);
    var location = seriesModel.get('location');
    var isShape = seriesModel.get('isShape');
    var dims = map(coordSys.dimensions, function (dim) {
      return data.mapDimension(dim);
    }).slice(0, 2);
    // const dimLen = dims.length;
    var store = data.getStore();
    var dimIdx0 = data.getDimensionIndex(dims[0]);
    var dimIdx1 = data.getDimensionIndex(dims[1]);
    var xOffset = seriesModel.get('offset') || 0;
    var price = getYByLocation(seriesModel);
    var showLast = seriesModel.get('showLast');
    var gTextStyleModel = ecModel.getModel('textStyle');
    // const fontStyle = gTextStyleModel && gTextStyleModel.getShallow('fontStyle') || '';
    // const fontWeight = gTextStyleModel && gTextStyleModel.getShallow('fontWeight') || '';
    var gfontSize = gTextStyleModel && (gTextStyleModel.getShallow('fontSize') || 12) + 'px';
    var gfontFamily = gTextStyleModel && gTextStyleModel.getShallow('fontFamily') || 'sans-serif';
    return {
      progress: function (params, labelsData) {
        var _a;
        // const segCount = params.end - params.start;
        // const points = createFloat32Array(segCount * dimLen);
        var symbolStyleMap = {};
        var tooltipSymbols = [];
        var textList = [];
        var tmpIn = [];
        var lastIndex = data.count(true) - 1;
        for (var i = params.start; i < params.end; i++) {
          if (showLast && lastIndex - data.getRawIndex(i) >= showLast) {
            continue;
          }
          tmpIn[0] = store.get(dimIdx0, i) + xOffset;
          tmpIn[1] = store.get(dimIdx1, i);
          // Let coordinate system to handle the NaN data.
          var point = coordSys.dataToPoint(tmpIn);
          if (isNaN(point[1])) {
            continue;
          }
          var itemModel = data.getItemModel(i);
          var yloc = itemModel.get('yloc');
          var symbol = itemModel.get('symbol');
          var symbolSize = itemModel.get('symbolSize');
          // let symbolRotate = itemModel.getShallow('symbolRotate');
          var symbolOffset = itemModel.get('symbolOffset') || defaultOffset;
          var symbolShape = {};
          // const style = itemModel.getModel('itemStyle').getItemStyle();
          var labelModel = itemModel.option.label || defaultLabel;
          var oldOffset = labelModel.offset || defaultOffset;
          var align = labelModel.align;
          var size = (_a = itemModel.get('size')) !== null && _a !== void 0 ? _a : 'normal';
          var text = labelModel.formatter;
          var isLabel = labelSymbolByType[symbol];
          var textShow = labelModel.show;
          var fontSize = labelModel.fontSize;
          var position = labelModel.position || 'top';
          var fontStyle = labelModel.fontStyle;
          var fontWeight = labelModel.fontWeight;
          // const isBelowbar = yloc === 'belowbar';
          // if (isBelowbar) {
          //     position = 'bottom';
          // }
          if (location === 'top' || location === 'belowbar') {
            position = 'bottom';
          }
          if (isLabel || symbol === 'textOutline') {
            position = 'inside';
          }
          if (textShow) {
            labelModel.fontSize = fontSize = getSymbolLabelFontSize(size, bandWidth);
          }
          var textRect = void 0;
          if (textShow) {
            // textRect = labelModel.getTextRect(text);
            // computedText.useStyle({
            //     text,
            //     font: labelModel.getFont(),
            // });
            // textRect = computedText.getBoundingRect();
            var textSize = fontSize ? fontSize + 'px' : gfontSize;
            var font = trim([
            // FIXME in node-canvas fontWeight is before fontStyle
            fontStyle || '', fontWeight || '', textSize, labelModel.fontFamily || gfontFamily].join(' '));
            textRect = getTextRect(text, font);
            if (isLabel) {
              symbolSize = [textRect.width + HPadding, textRect.height + VPadding];
            }
            var align_1 = labelModel.align;
            if (align_1 === 'left') {
              oldOffset = [-textRect.width / 2, 0];
            } else if (align_1 === 'right') {
              oldOffset = [textRect.width / 2, 0];
            }
          }
          // 根据size获取高宽
          var _b = getSymbolSize(symbol, size, bandWidth, isShape),
            w = _b.w,
            h = _b.h,
            shape = _b.shape;
          if (isLabel ? !textShow || !text : true) {
            symbolSize = [w, h];
          }
          var symbolRect = Array.isArray(symbolSize) ? symbolSize : [symbolSize, symbolSize];
          if (shape) {
            symbolShape = shape;
            if (textShow) {
              oldOffset = changeLabelOffsetBySymbol(symbol, symbolRect, shape, oldOffset);
            }
          }
          var symbolPoint = [point[0], price || point[1]];
          if (location === 'top') {
            symbolPoint[1] = symbolPoint[1] + symbolRect[1];
          }
          var ylocIsBottom = yloc ? yloc === 'belowbar' || yloc === 'price' : true;
          // y轴位置靠下时
          if (ylocIsBottom && upSymbols.includes(symbol)) {
            symbolPoint[1] = symbolPoint[1] + symbolRect[1];
          }
          // 为居中label时特殊处理
          if (symbol === 'labelCenter') {
            symbolPoint[1] = symbolPoint[1] + symbolRect[1] / 2;
          }
          if (symbol !== 'none' && itemModel.option.itemStyle.color) {
            var tooltip = itemModel.get('tooltipText');
            if (tooltip) {
              tooltipSymbols.push({
                point: symbolPoint,
                size: symbolRect,
                offset: symbolOffset,
                color: itemModel.option.itemStyle.color,
                shape: symbolShape,
                index: i,
                symbol: symbol
              });
            } else {
              var symbolStyles = symbolStyleMap[symbol] || [];
              symbolStyles.push({
                point: symbolPoint,
                size: symbolRect,
                offset: symbolOffset,
                color: itemModel.option.itemStyle.color,
                shape: symbolShape
              });
              symbolStyleMap[symbol] = symbolStyles;
            }
          }
          if (textShow) {
            var labelPoint = symbolPoint.slice();
            if (position === 'inside') {
              labelPoint[1] = labelPoint[1] - textRect.height / 2 - symbolRect[1] / 2;
            } else if (position === 'top') {
              labelPoint[1] = labelPoint[1] - symbolRect[1] - textRect.height / 2 - 10;
            } else {
              labelPoint[1] = labelPoint[1] + symbolRect[1] - textRect.height / 2 + 10;
            }
            textList.push({
              text: text,
              align: align || 'center',
              point: labelPoint,
              fontSize: fontSize,
              textColor: labelModel.color,
              fontFamily: labelModel.fontFamily,
              offset: [oldOffset[0] + symbolOffset[0], oldOffset[1] + symbolOffset[1]],
              textBorderColor: labelModel.textBorderColor,
              textBorderWidth: labelModel.textBorderWidth,
              fontStyle: fontStyle,
              fontWeight: fontWeight
            });
          }
          // labelsData.setItemLayout(i, [point[0], price ?? point[1]]);
        }

        labelsData.setLayout({
          symbolStyleMap: symbolStyleMap,
          textList: textList,
          tooltipSymbols: tooltipSymbols
        });
        // console.log('%c [ points ]-83', 'font-size:13px; background:pink; color:#bf2c9f;', points)
      }
    };
  }
};

export default labelsLayout;