<template>
  <div class="kline-wrapper">
    <!-- 时间周期 -->
    <div class="chart-header">
      <div class="time-intervals">
        <span class="active">15分</span>
        <span>1小时</span>
        <span>4小时</span>
        <span>日线</span>
      </div>
    </div>

    <div ref="chartContainer" class="chart-container"></div>

    <!-- 指标切换 -->
    <div class="chart-footer">
      <span class="indicator-btn" @click="setMainIndicator('MA')">MA</span>
      <span class="indicator-btn" @click="setMainIndicator('BOLL')">BOLL</span>
      <span class="divider">|</span>
      <span class="indicator-btn" @click="setSubIndicator('VOL')">VOL</span>
      <span class="indicator-btn" @click="setSubIndicator('MACD')">MACD</span>
      <span class="indicator-btn" @click="setSubIndicator('KDJ')">KDJ</span>
    </div>
  </div>
</template>

<script setup>
import { onMounted, onUnmounted, ref } from 'vue'
import { init, dispose } from 'klinecharts'

const chartContainer = ref(null)
let chartObj = null

// 生成 mock 数据
function getMockDataList() {
  const dataList = []
  let ts = Date.now()
  let price = 40000

  for (let i = 0; i < 500; i++) {
    const timestamp = ts - (500 - i) * 60 * 1000 * 15
    const random = (Math.random() - 0.5) * 200
    const open = price
    const close = price + random
    const high = Math.max(open, close) + Math.random() * 50
    const low = Math.min(open, close) - Math.random() * 50
    const volume = Math.random() * 1000 + 500

    dataList.push({ timestamp, open, high, low, close, volume })
    price = close
  }

  return dataList
}

onMounted(() => {
  if (!chartContainer.value) {
    console.error('找不到图表容器')
    return
  }

  // 初始化 v8 图表
  chartObj = init(chartContainer.value)

  console.log('chartObj 实例：', chartObj)

  if (!chartObj) {
    console.error('图表初始化失败')
    return
  }

  // 设置主图 & 副图指标（v8 用 createIndicator）
  chartObj.createIndicator('MA', false, { id: 'candle_pane' })
  chartObj.createIndicator('VOL', false, { id: 'pane_1' })

  // v8 的方法是 applyNewData（不是 applyData）
  const data = getMockDataList()
  chartObj.applyNewData(data)
})

onUnmounted(() => {
  if (chartObj) dispose(chartContainer.value)
})

// 切换主图指标
function setMainIndicator(name) {
  chartObj.createIndicator(name, false, { id: 'candle_pane' })
}

// 切换副图指标
function setSubIndicator(name) {
  chartObj.createIndicator(name, false, { id: 'pane_1' })
}
</script>

<style scoped>
.kline-wrapper {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.chart-header, .chart-footer {
  display: flex;
  padding: 10px 15px;
  background: #fff;
}

.time-intervals span, .indicator-btn {
  font-size: 12px;
  color: #666;
  margin-right: 15px;
  cursor: pointer;
}

.time-intervals span.active {
  font-weight: bold;
  color: #333;
}

.chart-container {
  width: 100%;
  height: 450px;
  background: #fff;
}
</style>
