
/*
* 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 { __assign, __extends } from "tslib";
import ComponentView from '../../view/Component.js';
import { createHashMap, each, isGradientObject } from 'tvrender/lib/core/util.js';
import { getBoundingRect } from 'tvrender/lib/contain/text.js';
import { makeInner } from '../../util/model.js';
import { contrastColor, removeTransparency, getGradientColorByY } from '../../util/color.js';
import * as formatUtil from '../../util/format.js';
import * as graphicUtil from '../../util/graphic.js';
import { getFont } from '../../label/labelStyle.js';
import Group from 'tvrender/lib/graphic/Group.js';
import { isCandle, isPlot } from '../../util/seriesType.js';
import { positiveColorQuery, negativeColorQuery, positiveBorderColorQuery, negativeBorderColorQuery } from '../../chart/candlestick/candlestickVisual.js';
import { getLeftTextX, formatSeconds } from '../../util/axisLabel.js';
var DefaultColor = 'rgb(41,98,255)';
var formatTextColor = function (color, height) {
  if (color && isGradientObject(color) && !color.global && color.type === 'linear') {
    return __assign(__assign({}, color), {
      global: true,
      y2: height
    });
  }
  return color;
};
var linePlotTypes = ["linesPlot", "line"];
var markerTypeCalculator = {
  dataMin: function (item, seriesModel, height, backgroundColor) {
    var seriesData = seriesModel.getData();
    return {
      value: seriesData.getDataExtent(item.valueDim)[0]
    };
  },
  dataMax: function (item, seriesModel, height, backgroundColor) {
    var seriesData = seriesModel.getData();
    return {
      value: seriesData.getDataExtent(item.valueDim)[1]
    };
  },
  min: function (item, seriesModel, height, backgroundColor) {
    var seriesData = seriesModel.getData();
    return {
      value: seriesData.getDataExtent(item.valueDim, true)[0]
    };
  },
  max: function (item, seriesModel, height, backgroundColor) {
    var seriesData = seriesModel.getData();
    return {
      value: seriesData.getDataExtent(item.valueDim, true)[1]
    };
  },
  rawLast: function (item, seriesModel, height, backgroundColor) {
    var _a;
    var seriesData = seriesModel.getData();
    var lastIndex = seriesData.count(true) - 1;
    var itemFill = item.textStyle.fill;
    if (item.customColor && itemFill) {
      return {
        value: seriesData.getByRawIndex(item.valueDim, lastIndex),
        labelTextStyle: {
          fill: typeof itemFill === 'string' ? contrastColor(itemFill) : '#ffffff',
          // stroke: fill,
          backgroundColor: removeTransparency(itemFill),
          // borderColor: fill,
          borderWidth: 0
        }
      };
    }
    var fill = (_a = seriesData.getItemVisual(lastIndex, 'style')) === null || _a === void 0 ? void 0 : _a.fill;
    if (isCandle(seriesModel.subType)) {
      var dataItem = seriesData.getItemModel(lastIndex, true);
      var sign = 1;
      if (seriesModel.get('signByPrev') && lastIndex) {
        var openValue = seriesData.getByRawIndex('close', lastIndex - 1);
        var closeValue = seriesData.getByRawIndex('close', lastIndex);
        sign = openValue > closeValue ? -1 : 1;
      } else {
        var closeValue = seriesData.getByRawIndex('close', lastIndex);
        var openValue = seriesData.getByRawIndex('open', lastIndex);
        sign = openValue > closeValue ? -1 : 1;
      }
      // const closeValue = seriesData.getByRawIndex('close', lastIndex);
      // const openValue = seriesData.getByRawIndex('open', lastIndex);
      fill = dataItem.get(sign > 0 ? positiveColorQuery : negativeColorQuery);
      if (fill === 'none') {
        fill = dataItem.get(sign > 0 ? positiveBorderColorQuery : negativeBorderColorQuery);
      }
    } else if (isPlot(seriesModel.subType)) {
      var isLinesPlot = linePlotTypes.includes(seriesModel.subType);
      var dataItem = seriesData.getItemModel(lastIndex, true);
      fill = formatTextColor(dataItem.get([isLinesPlot ? 'lineStyle' : 'itemStyle', 'color']), height);
    }
    return {
      value: seriesData.getByRawIndex(item.valueDim, lastIndex),
      labelTextStyle: {
        fill: typeof fill === 'string' ? contrastColor(fill) : '#ffffff',
        // stroke: fill,
        backgroundColor: fill && isGradientObject(fill) ? fill : fill ? removeTransparency(fill) : DefaultColor,
        // borderColor: fill,
        borderWidth: 0
      }
    };
  },
  last: function (item, seriesModel, height, backgroundColor) {
    var _a;
    var seriesData = seriesModel.getData();
    var count = seriesData.count(true);
    var axisModel = seriesModel.getBaseAxis();
    var extent = axisModel.scale.getExtent();
    var offset = seriesModel.get('offset') || 0;
    var lastIndex = extent[1] + offset;
    if (lastIndex >= count || lastIndex < 0) {
      return null;
    }
    var lastItem = seriesData.count() - 1;
    var fill = (_a = seriesData.getItemVisual(lastItem, 'style')) === null || _a === void 0 ? void 0 : _a.fill;
    if (isPlot(seriesModel.subType)) {
      var isLinesPlot = linePlotTypes.includes(seriesModel.subType);
      var dataItem = seriesData.getItemModel(lastItem);
      fill = formatTextColor(dataItem.get([isLinesPlot ? 'lineStyle' : 'itemStyle', 'color']), height);
    } else if (isCandle(seriesModel.subType)) {
      var dataItem = seriesData.getItemModel(lastItem);
      var sign = 1;
      if (seriesModel.get('signByPrev') && lastIndex) {
        var openValue = seriesData.get('close', lastItem - 1);
        var closeValue = seriesData.get('close', lastItem);
        sign = openValue > closeValue ? -1 : 1;
      } else {
        var closeValue = seriesData.get('close', lastItem);
        var openValue = seriesData.get('open', lastItem);
        sign = openValue > closeValue ? -1 : 1;
      }
      fill = dataItem.get(sign > 0 ? positiveColorQuery : negativeColorQuery);
      if (fill === 'none') {
        fill = dataItem.get(sign > 0 ? positiveBorderColorQuery : negativeBorderColorQuery);
      }
    }
    return {
      value: seriesData.getByRawIndex(item.valueDim, lastIndex),
      labelTextStyle: {
        fill: fill || DefaultColor,
        // stroke: fill,
        backgroundColor: backgroundColor,
        borderColor: fill || DefaultColor,
        borderWidth: 1
      }
    };
  },
  allLast: function (item, seriesModel, height, backgroundColor) {
    var seriesData = seriesModel.getData();
    var count = seriesData.count(true);
    var axisModel = seriesModel.getBaseAxis();
    var extent = axisModel.scale.getExtent();
    var offset = seriesModel.get('offset') || 0;
    var lastIndex = extent[1] + offset;
    if (lastIndex >= count || lastIndex < 0) {
      return markerTypeCalculator.rawLast(item, seriesModel, height, backgroundColor);
    }
    return markerTypeCalculator.last(item, seriesModel, height, backgroundColor);
  }
};
var inner = makeInner();
var MarkLabelView = /** @class */function (_super) {
  __extends(MarkLabelView, _super);
  function MarkLabelView() {
    var _this = _super !== null && _super.apply(this, arguments) || this;
    _this.type = MarkLabelView.type;
    return _this;
  }
  MarkLabelView.prototype.init = function () {
    this.markerGroupMapBySeries = createHashMap();
    this._timerMap = createHashMap();
    this._graphicLabelElMap = createHashMap();
    this._graphLabelGroup = new Group();
    this.group.add(this._graphLabelGroup);
  };
  MarkLabelView.prototype.render = function (markerModel, ecModel, api, payload) {
    var isAvoidOverlap = markerModel.get('isAvoidOverlap');
    var type = payload === null || payload === void 0 ? void 0 : payload.type;
    if (type !== 'updateComOption') {
      this.updateMarkLabels(markerModel, ecModel, api);
    }
    // this.graphicLabelsResize(ecModel);
    this.updateGraphicLabels(ecModel);
    var isUpdateGraphic = (payload === null || payload === void 0 ? void 0 : payload.type) ? ['dataZoom', 'resize'].includes(payload.type) : Object.keys(ecModel.getNewBaseOption()).some(function (key) {
      return ['grid', 'yAxis', 'xAxis'].includes(key);
    });
    if (isUpdateGraphic) {
      this.graphicLabelsResize(ecModel);
    }
    // this.updatePlaybackOrderLabel(ecModel);
    this.avoidOverlap(isAvoidOverlap, ecModel, api);
  };
  MarkLabelView.prototype.updateMarkLabels = function (markerModel, ecModel, api) {
    var _this = this;
    var markerGroupMapBySeries = this.markerGroupMapBySeries;
    var timerMap = this._timerMap;
    var labelMap = markerModel.labelMap;
    var updatedSeriesByName = {};
    var height = api.getHeight();
    var backgroundColor = ecModel.get('backgroundColor');
    if (backgroundColor && isGradientObject(backgroundColor) && !backgroundColor.global && backgroundColor.type === 'linear') {
      backgroundColor = __assign(__assign({}, backgroundColor), {
        global: true,
        y2: height
      });
    }
    ecModel.eachSeries(function (seriesModel) {
      var _a;
      var priceScaleInvisible = seriesModel.get('priceScaleInvisible');
      var invisible = seriesModel.get('invisible');
      if (priceScaleInvisible || invisible) {
        return;
      }
      var seriesName = seriesModel.name;
      var markerGroupMap = (_a = markerGroupMapBySeries.get(seriesName)) !== null && _a !== void 0 ? _a : createHashMap();
      var markLabelData = labelMap.get(seriesName);
      if (!markLabelData) {
        return;
      }
      var coordSys = seriesModel.coordinateSystem;
      if (!coordSys || !coordSys.master) {
        return;
      }
      var gridRect = coordSys.master.getRect();
      var yAxisModel = coordSys.getAxis('y');
      var offset = yAxisModel.model.get('offset') || 0;
      var formatter = seriesModel.get('formatter') || yAxisModel.model.get(['axisLabel', 'formatter']);
      var x = yAxisModel.position === 'right' ? gridRect.x + gridRect.width + offset : gridRect.x - offset;
      updatedSeriesByName[seriesName] = 1;
      each(markLabelData, function (item) {
        // const data = markerHelper.dataTransform(seriesModel, item);
        var el = markerGroupMap.get(item.name);
        if (item.$action === 'remove') {
          delete markLabelData[item.name];
          if (!el) {
            return;
          }
          markerGroupMap.removeKey(item.name);
          _this.group.remove(el);
          return;
        }
        var yCalcFn = markerTypeCalculator[item.type];
        var _a = yCalcFn ? yCalcFn(item, seriesModel, height, backgroundColor) || {} : {
            value: item.value
          },
          value = _a.value,
          labelTextStyle = _a.labelTextStyle;
        if (!value) {
          if (el) {
            el.ignore = true;
          }
          return;
        }
        var baseValue = coordSys.getBaseValue();
        item.text = ['last', 'allLast'].includes(item.type) && yAxisModel.scale.type === 'percentage' ? yAxisModel.scale.getLabel({
          value: value
        }, {
          precision: item.precision,
          baseValue: baseValue
        }) : formatter ? formatter(value) : value.toFixed(item.precision);
        var y = coordSys.dataToPoint([0, value])[1];
        var fontSize = yAxisModel.getLabelModel().option.fontSize;
        if (el) {
          updateLabel({
            el: el,
            x: x,
            y: y,
            gridRect: gridRect,
            labelData: item,
            markerModel: markerModel,
            position: yAxisModel.position,
            labelTextStyle: labelTextStyle,
            fontSize: fontSize
          });
        } else {
          el = createLabel({
            x: x,
            y: y,
            gridRect: gridRect,
            labelData: item,
            markerModel: markerModel,
            position: yAxisModel.position,
            labelTextStyle: labelTextStyle,
            fontSize: fontSize
          });
          markerGroupMap.set(item.name, el);
          _this.group.add(el);
        }
        var showCountDown = item.countDown && item.countDown.show && item.countDown.value > 0;
        if (showCountDown) {
          var key = seriesName + item.name;
          if (!timerMap.get(key)) {
            var countDownTextEl = el.childAt(3);
            _this._labelCountDown(item, countDownTextEl, key);
          }
        }
        inner(el).yAxisIndex = yAxisModel.index;
        inner(el).isSort = item.showName || showCountDown;
      });
      markerGroupMapBySeries.set(seriesName, markerGroupMap);
    });
    // 删除不存在的系列中的标签
    markerGroupMapBySeries.each(function (markerGroupMap, seriesName) {
      var markLabelData = labelMap.get(seriesName);
      if (updatedSeriesByName[seriesName]) {
        // 检查标签是否在数据中
        markerGroupMap.each(function (el, key) {
          if (!markLabelData[key]) {
            markerGroupMap.removeKey(key);
            _this.group.remove(el);
          }
        });
        return;
      }
      each(markLabelData, function (item) {
        // const data = markerHelper.dataTransform(seriesModel, item);
        var el = markerGroupMap.get(item.name);
        delete markLabelData[item.name];
        if (!el) {
          return;
        }
        markerGroupMap.removeKey(item.name);
        var downKey = seriesName + item.name;
        // 系列移除时清除倒计时
        if (timerMap.get(downKey)) {
          clearTimeout(timerMap.get(downKey));
          timerMap.removeKey(downKey);
        }
        _this.group.remove(el);
      });
      markerGroupMapBySeries.removeKey(seriesName);
    });
  };
  MarkLabelView.prototype.updateGraphicLabels = function (ecModel) {
    var _this = this;
    var graphicModel = ecModel.getComponent('graphic');
    if (!graphicModel) {
      return;
    }
    if (!graphicModel.option.elements || graphicModel.option.elements.length === 0) {
      this._graphicLabelElMap = createHashMap();
      this._graphLabelGroup.removeAll();
      return;
    }
    var labelOptions = graphicModel.useIncludeLabelOptionsToUpdate();
    if (!labelOptions) {
      return;
    }
    var defaultSeries = ecModel.getComponent('series');
    var labelsBySeriesId = {};
    each(labelOptions, function (item) {
      var label = item.getElementLabels();
      if (item.$action === 'remove' || item.labelVisible === false) {
        _this.removeGraphicLabels(label);
        return;
      }
      if (!label || !item.labelVisible) {
        return;
      }
      var seriesId = item.seriesId || defaultSeries.id;
      var seriesLabels = labelsBySeriesId[seriesId] || [];
      seriesLabels.push(label);
      labelsBySeriesId[seriesId] = seriesLabels;
    });
    var graphicLabelElMap = this._graphicLabelElMap;
    var graphLabelGroup = this._graphLabelGroup;
    ecModel.eachSeries(function (seriesModel) {
      var labels = labelsBySeriesId[seriesModel.id];
      if (!labels) {
        return;
      }
      var coordSys = seriesModel.coordinateSystem;
      if (!coordSys || !coordSys.master) {
        return;
      }
      var gridRect = coordSys.master.getRect();
      var yAxisModel = coordSys.getAxis('y');
      var position = yAxisModel.position;
      var offset = yAxisModel.model.get('offset') || 0;
      var formatter = yAxisModel.model.get(['axisLabel', 'formatter']);
      each(labels, function (label) {
        if (!label.children) {
          return;
        }
        each(label.children, function (item) {
          var option = item;
          var el = graphicLabelElMap.get(option.id);
          var y = yAxisModel.toGlobalCoord(yAxisModel.dataToCoord(option.y));
          var style = option.style;
          if (yAxisModel.scale.type === 'percentage') {
            var formatLabel = yAxisModel.scale.getLabel({
              value: +option.style.text
            });
            option.style = Object.assign({}, option.style, {
              text: formatLabel
            });
          } else if (formatter) {
            option.style = Object.assign({}, option.style, {
              text: formatter(+option.style.text)
            });
          }
          var fontSize = yAxisModel.getLabelModel().option.fontSize;
          if (el) {
            updateText({
              el: el,
              gridRect: gridRect,
              position: position,
              option: option,
              ecModel: ecModel,
              y: y,
              offset: offset,
              fontSize: fontSize
            });
          } else {
            el = createText({
              gridRect: gridRect,
              position: position,
              option: option,
              ecModel: ecModel,
              y: y,
              offset: offset,
              fontSize: fontSize
            });
            graphLabelGroup.add(el);
            graphicLabelElMap.set(option.id, el);
            inner(el).yAxisIndex = yAxisModel.index;
          }
          inner(el).originalValue = option.y;
          inner(el).isSort = true;
          inner(el).style = style;
        });
      });
    });
  };
  MarkLabelView.prototype.graphicLabelsResize = function (ecModel) {
    var graphicLabelElMap = this._graphicLabelElMap;
    var yAxisModels = ecModel.queryComponents({
      mainType: 'yAxis'
    });
    graphicLabelElMap.each(function (el) {
      var yAxisModel = yAxisModels[inner(el).yAxisIndex].axis;
      if (!yAxisModel) {
        return;
      }
      var gridRect = yAxisModel.grid.getRect();
      var position = yAxisModel.position;
      var y = yAxisModel.toGlobalCoord(yAxisModel.dataToCoord(inner(el).originalValue));
      var offset = yAxisModel.model.get('offset') || 0;
      var formatter = yAxisModel.model.get(['axisLabel', 'formatter']);
      var style = inner(el).style;
      if (yAxisModel.scale.type === 'percentage') {
        var formatLabel = yAxisModel.scale.getLabel({
          value: +style.text
        });
        style = Object.assign({}, style, {
          text: formatLabel
        });
      } else if (formatter) {
        style = Object.assign({}, style, {
          text: formatter(+style.text)
        });
      }
      updateText({
        el: el,
        gridRect: gridRect,
        position: position,
        option: {
          style: style
        },
        ecModel: ecModel,
        y: y,
        offset: offset
      });
      // console.log('%c [ yAxisModel ]-239', 'font-size:13px; background:pink; color:#bf2c9f;', yAxisModel)
    });
  };

  MarkLabelView.prototype.removeGraphicLabels = function (labelOption) {
    var graphicLabelElMap = this._graphicLabelElMap;
    var graphLabelGroup = this._graphLabelGroup;
    each(labelOption.children, function (option) {
      var el = graphicLabelElMap.get(option.id);
      if (!el) {
        return;
      }
      graphLabelGroup.remove(el);
      graphicLabelElMap.removeKey(option.id);
    });
  };
  MarkLabelView.prototype._labelCountDown = function (item, el, key) {
    var _this = this;
    var timerMap = this._timerMap;
    var timer = setTimeout(function () {
      if (item.countDown.nextTime) {
        var current_time = Date.now() + (item.countDown.dataTimeDiff || 0) * 1000;
        var countDown = Math.round(item.countDown.nextTime - current_time / 1000);
        item.countDown.value = countDown;
      } else {
        item.countDown.value = item.countDown.value - 1;
      }
      var text = formatSeconds(item.countDown.value);
      el.attr('style', {
        text: text
      });
      if (item.countDown.value > 0 && item.countDown.show) {
        _this._labelCountDown(item, el, key);
      } else {
        el.ignore = true;
        // inner(el).parentHeight = 0;
        clearTimeout(timerMap.get(key));
        timerMap.removeKey(key);
      }
    }, 1000);
    timerMap.set(key, timer);
  };
  MarkLabelView.prototype.avoidOverlap = function (isAvoidOverlap, ecModel, api) {
    var labelsByYAxisId = {};
    var markerGroupMapBySeries = this.markerGroupMapBySeries;
    markerGroupMapBySeries.each(function (markerGroupMap) {
      markerGroupMap.each(function (item) {
        var yAxisId = inner(item).yAxisIndex;
        var isSort = inner(item).isSort;
        if (item.ignore || !isSort) {
          return;
        }
        var labels = labelsByYAxisId[yAxisId] || [];
        labels.push(item);
        labelsByYAxisId[yAxisId] = labels;
      });
    });
    // this.markerGroupMap.each(item => {
    //     const yAxisId = inner(item).yAxisIndex;
    //     const isSort = inner(item).isSort;
    //     if (item.ignore || !isSort) {
    //         return;
    //     }
    //     const labels = labelsByYAxisId[yAxisId] || [];
    //     labels.push(item);
    //     labelsByYAxisId[yAxisId] = labels;
    // });
    this._graphicLabelElMap.each(function (item) {
      var yAxisId = inner(item).yAxisIndex;
      var isSort = inner(item).isSort;
      if (item.ignore || !isSort) {
        return;
      }
      var labels = labelsByYAxisId[yAxisId] || [];
      labels.push(item);
      labelsByYAxisId[yAxisId] = labels;
    });
    var playbackModel = ecModel.getComponent('playbackOrder');
    if (playbackModel) {
      var view = api.getComponentView(playbackModel.__viewId);
      if (view && view.labels) {
        var yAxisId = view.yAxisModel.index;
        var labels_1 = labelsByYAxisId[yAxisId] || [];
        each(view.labels, function (item) {
          inner(item).y = item.y + 9;
          labels_1.push(item);
        });
        labelsByYAxisId[yAxisId] = labels_1;
      }
    }
    each(labelsByYAxisId, function (labels) {
      labelAvoidOverlap(labels, isAvoidOverlap);
    });
  };
  MarkLabelView.type = 'markLabel';
  return MarkLabelView;
}(ComponentView);
function textYChange(label, y, height) {
  if (label.type === 'text') {
    label.y = y;
  } else {
    each(label.children(), function (item) {
      if (item.type === 'text') {
        if (inner(item).labelType === 'countDown') {
          // item.style.y = y + inner(item).parentHeight;
          item.attr('style', {
            y: y + inner(item).parentHeight
          });
          return;
        }
        // item.style.y = y;
        item.attr('style', {
          y: y
        });
      }
    });
  }
}
function labelAvoidOverlap(labels, isAvoidOverlap, marginTop) {
  var _a;
  if (marginTop === void 0) {
    marginTop = 0;
  }
  if (labels.length === 0) {
    return;
  }
  // // 根据标签的顶部位置对标签进行排序
  labels.sort(function (a, b) {
    return inner(a).y - inner(b).y;
  });
  var height = labels[0].isGroup ? labels[0].children().find(function (item) {
    return item.type === 'text';
  }).getBoundingRect().height : labels[0].getBoundingRect().height;
  var sortYbyId = {};
  var offestY = height / 2;
  for (var i = 0; i < labels.length; i++) {
    var currentLabel = labels[i];
    var currentLabelY = inner(currentLabel).y;
    if (i === 0 || !isAvoidOverlap) {
      textYChange(currentLabel, currentLabelY - offestY, height);
      continue;
    }
    var prevLabel = labels[i - 1];
    var prevLabelY = (_a = sortYbyId[prevLabel.id]) !== null && _a !== void 0 ? _a : inner(prevLabel).y;
    // 计算前一个标签的底部位置
    var prevHeight = inner(prevLabel).showCountDown ? height * 2 + marginTop - 1 : height + marginTop;
    // 如果当前标签的顶部位置小于等于前一个标签的底部位置，则需要调整当前标签的位置
    if (prevLabelY > currentLabelY || Math.abs(currentLabelY - prevLabelY) < prevHeight) {
      // 将当前标签的顶部位置设置为前一个标签的底部位置加上间距
      currentLabelY = prevLabelY + prevHeight;
    }
    sortYbyId[currentLabel.id] = currentLabelY;
    textYChange(currentLabel, currentLabelY - offestY, height);
  }
}
function getPaddingByStyle(fontsize, borderWidth) {
  if (borderWidth === void 0) {
    borderWidth = 0;
  }
  var _a = [4, 6, 2, 8],
    top = _a[0],
    right = _a[1],
    bottom = _a[2],
    left = _a[3];
  var diff = fontsize - 12;
  var xLength = diff - borderWidth;
  var yLength = diff * 0.25;
  return [top + yLength, right + xLength, bottom + yLength, left + xLength];
}
function createText(_a) {
  var option = _a.option,
    gridRect = _a.gridRect,
    position = _a.position,
    ecModel = _a.ecModel,
    y = _a.y,
    offset = _a.offset,
    fontSize = _a.fontSize;
  var isLeft = position === 'left';
  var style = option.style,
    zlevel = option.zlevel;
  var startX = isLeft ? gridRect.x - offset : gridRect.x + gridRect.width + offset;
  var x = isLeft ? getLeftTextX(startX, style.text, style, ecModel) : startX;
  var textEl = new graphicUtil.Text({
    x: x,
    y: y,
    style: Object.assign(style, {
      fontSize: fontSize,
      padding: getPaddingByStyle(fontSize, style.borderWidth)
    }),
    z: 101,
    zlevel: zlevel
  });
  inner(textEl).y = y;
  return textEl;
}
function updateText(_a) {
  var option = _a.option,
    gridRect = _a.gridRect,
    position = _a.position,
    ecModel = _a.ecModel,
    el = _a.el,
    y = _a.y,
    offset = _a.offset,
    fontSize = _a.fontSize;
  var isLeft = position === 'left';
  var startX = isLeft ? gridRect.x - offset : gridRect.x + gridRect.width + offset;
  var style = option.style;
  var x = isLeft ? getLeftTextX(startX, style.text, style, ecModel) : startX;
  el.x = x;
  el.y = y;
  el.attr('style', fontSize ? Object.assign(style, {
    fontSize: fontSize,
    padding: getPaddingByStyle(fontSize, style.borderWidth)
  }) : style);
  inner(el).y = y;
}
var mistake = 0;
function createLabel(_a) {
  var _b;
  var x = _a.x,
    y = _a.y,
    labelData = _a.labelData,
    markerModel = _a.markerModel,
    gridRect = _a.gridRect,
    position = _a.position,
    _c = _a.labelTextStyle,
    labelTextStyle = _c === void 0 ? {} : _c,
    fontSize = _a.fontSize;
  var zlevel = markerModel.option.zlevel;
  var lineStyle = labelData.lineStyle,
    showLine = labelData.showLine,
    showName = labelData.showName,
    showTitle = labelData.showTitle,
    title = labelData.title,
    countDown = labelData.countDown;
  var textStyle = Object.assign(__assign({}, labelData.textStyle), {
    fontSize: fontSize,
    padding: getPaddingByStyle(fontSize, labelTextStyle.borderWidth)
  }, labelTextStyle);
  var text = labelData.text;
  var labelTitle = title || labelData.name;
  var isLeft = position === 'left';
  var group = new graphicUtil.Group();
  var labelY = y;
  var borderWidth = (_b = textStyle.borderWidth) !== null && _b !== void 0 ? _b : 0;
  var font = getFont(textStyle, markerModel.ecModel);
  var countDownText = countDown && countDown.show && formatSeconds(countDown.value) || '';
  var renderText = countDownText.length > text.length ? countDownText : text;
  var textRect = getBoundingRect(renderText, font);
  var paddings = formatUtil.normalizeCssArray(textStyle.padding || 0);
  var textElWidth = textRect.width + paddings[1] + paddings[3];
  var textElx = isLeft ? x - textElWidth - borderWidth - 1 : x + borderWidth;
  var formatLabelFill = getGradientColorByY(textStyle.fill, labelY);
  var textEl = new graphicUtil.Text({
    // x: textElx,
    // y: labelY,
    style: Object.assign({
      text: text,
      width: textRect.width,
      x: textElx,
      y: labelY
    }, textStyle, {
      fill: formatLabelFill
    }),
    z: 101,
    zlevel: zlevel,
    ignore: !showName
  });
  var textNameEl = new graphicUtil.Text({
    // x: isLeft
    //     ? gridRect.x - borderWidth
    //     : getLeftTextX(gridRect.x + gridRect.width, labelTitle, textStyle, markerModel.ecModel) + borderWidth,
    // y: labelY,
    style: Object.assign({
      text: labelTitle,
      x: isLeft ? gridRect.x - borderWidth : getLeftTextX(gridRect.x + gridRect.width, labelTitle, textStyle, markerModel.ecModel) + borderWidth,
      y: labelY
    }, textStyle, {
      fill: formatLabelFill
    }),
    z: 101,
    zlevel: zlevel,
    ignore: !showTitle
  });
  var lineY = lineStyle.lineWidth % 2 === 1 ? Math.floor(y) + 0.5 : y;
  var lineEl = new graphicUtil.Line({
    style: Object.assign(lineStyle, labelTextStyle.backgroundColor ? {
      stroke: labelTextStyle.backgroundColor
    } : {}),
    shape: {
      x1: showTitle && isLeft ? gridRect.x + 2 : gridRect.x,
      y1: lineY,
      x2: showTitle && !isLeft ? gridRect.x + gridRect.width - 2 : gridRect.x + gridRect.width,
      y2: lineY
    },
    z: 100,
    // zlevel,
    ignore: !showLine
  });
  inner(lineEl).labelType = 'line';
  inner(textNameEl).labelType = 'nameLabel';
  inner(textEl).labelType = 'textLabel';
  inner(group).y = labelY;
  group.add(lineEl);
  group.add(textEl);
  group.add(textNameEl);
  if (countDown) {
    var show = countDown.show && countDown.value > 0;
    var offsetY = showName && show ? textRect.height + paddings[0] + paddings[2] - 1 : 0;
    var fill = textStyle.fill === '#ffffff' ? 'rgba(255,255,255,0.8)' : 'rgba(0,0,0,0.8)';
    var countDownEl = new graphicUtil.Text({
      // x: textElx,
      // y: labelY + offsetY,
      style: Object.assign({
        text: countDownText,
        width: textRect.width,
        x: textElx,
        y: labelY + offsetY
      }, textStyle, {
        fill: fill
      }),
      z: 101,
      zlevel: zlevel,
      ignore: !show
    });
    inner(group).showCountDown = show;
    inner(countDownEl).labelType = 'countDown';
    inner(countDownEl).parentHeight = offsetY;
    group.add(countDownEl);
  }
  return group;
}
function updateLabel(_a) {
  var _b;
  var x = _a.x,
    y = _a.y,
    labelData = _a.labelData,
    markerModel = _a.markerModel,
    gridRect = _a.gridRect,
    position = _a.position,
    el = _a.el,
    _c = _a.labelTextStyle,
    labelTextStyle = _c === void 0 ? {} : _c,
    fontSize = _a.fontSize;
  var lineStyle = labelData.lineStyle,
    showLine = labelData.showLine,
    showName = labelData.showName,
    showTitle = labelData.showTitle,
    title = labelData.title,
    countDown = labelData.countDown;
  // const lineStyle = Object.assign({}, labelData.lineStyle);
  // const textStyle = Object.assign(defaultLabelStyle, labelData.textStyle);
  var textStyle = Object.assign(__assign({}, labelData.textStyle), {
    fontSize: fontSize,
    padding: getPaddingByStyle(fontSize, labelTextStyle.borderWidth)
  }, labelTextStyle);
  var borderWidth = (_b = textStyle.borderWidth) !== null && _b !== void 0 ? _b : 0;
  var isLeft = position === 'left';
  if (el.ignore) {
    el.ignore = false;
  }
  var text = labelData.text;
  var countDownText = countDown && countDown.show && countDown.value > 0 && formatSeconds(countDown.value) || '';
  var renderText = countDownText.length > text.length ? countDownText : text;
  var font = getFont(textStyle, markerModel.ecModel);
  var textRect = getBoundingRect(renderText, font);
  var paddings = formatUtil.normalizeCssArray(textStyle.padding || 0);
  var textElWidth = textRect.width + paddings[1] + paddings[3];
  var textElx = isLeft ? x - textElWidth - borderWidth - 1 : x + borderWidth;
  var labelY = y;
  var formatLabelFill = getGradientColorByY(textStyle.fill, labelY);
  inner(el).y = labelY;
  each(el.children(), function (element) {
    var labelType = inner(element).labelType;
    switch (labelType) {
      case 'line':
        if (!showLine) {
          element.ignore = true;
          return;
        }
        var lineY = lineStyle.lineWidth % 2 === 1 ? Math.floor(y) + 0.5 : y;
        element.attr({
          shape: {
            x1: showTitle && isLeft ? gridRect.x + 2 : gridRect.x,
            y1: lineY,
            x2: showTitle && !isLeft ? gridRect.x + gridRect.width - 2 : gridRect.x + gridRect.width,
            y2: lineY
          },
          style: Object.assign(lineStyle, labelTextStyle.backgroundColor ? {
            stroke: labelTextStyle.backgroundColor
          } : {})
        });
        element.ignore = false;
        // element.style = lineStyle;
        break;
      case 'textLabel':
        if (!showName) {
          element.ignore = true;
          return;
        }
        var textLabel = labelData.text;
        // element.x = textElx;
        // element.y = labelY;
        element.attr('style', Object.assign({
          text: textLabel,
          width: textRect.width,
          x: textElx,
          y: labelY
        }, textStyle, {
          fill: formatLabelFill
        }));
        element.ignore = false;
        break;
      case 'nameLabel':
        if (!showTitle) {
          element.ignore = true;
          return;
        }
        var labelTitle = title || labelData.name;
        var nameX = isLeft ? gridRect.x : getLeftTextX(gridRect.x + gridRect.width, labelTitle, textStyle, markerModel.ecModel);
        // element.x = nameX;
        // element.y = labelY;
        element.attr('style', Object.assign({
          text: labelTitle,
          x: nameX,
          y: labelY
        }, textStyle, {
          fill: formatLabelFill
        }));
        element.ignore = false;
        break;
      case 'countDown':
        if (!countDown.show || countDown.value <= 0) {
          element.ignore = true;
          inner(el).showCountDown = false;
          inner(element).parentHeight = 0;
          return;
        }
        var offsetY = showName ? textRect.height + paddings[0] + paddings[2] - 1 : 0;
        inner(el).showCountDown = true;
        inner(element).parentHeight = offsetY;
        var fill = textStyle.fill === '#ffffff' ? 'rgba(255,255,255,0.8)' : 'rgba(0,0,0,0.8)';
        // element.x = textElx;
        // element.y = labelY + offsetY;
        element.attr('style', Object.assign({
          text: countDownText,
          width: textRect.width,
          x: textElx,
          y: labelY + offsetY
        }, textStyle, {
          fill: fill
        }));
        element.ignore = false;
        break;
    }
  });
}
export default MarkLabelView;