/**
 * 将底座图片宽度/左偏移与 ECharts grid 绘图区对齐（左右 Y 轴之间）。
 */
export const syncChartBaseToGrid = (chartInstance, baseEl) => {
  if (!chartInstance || !baseEl) {
    return
  }

  const gridModel = chartInstance.getModel()?.getComponent('grid', 0)
  const rect = gridModel?.coordinateSystem?.getRect?.()
  if (!rect?.width) {
    return
  }

  baseEl.style.width = `${Math.round(rect.width)}px`
  baseEl.style.marginLeft = `${Math.round(rect.x)}px`
}

export const bindChartBaseSync = (chartInstance, baseEl) => {
  if (!chartInstance || !baseEl) {
    return () => {}
  }

  const sync = () => {
    requestAnimationFrame(() => {
      syncChartBaseToGrid(chartInstance, baseEl)
    })
  }

  chartInstance.on('finished', sync)
  sync()

  return () => {
    chartInstance.off('finished', sync)
  }
}
