<template>
  <div class="kline-wrapper" :style="{ height: height }">
    <div ref="chartContainer" class="kline-chart"></div>
  </div>
</template>

<script setup>
import { onMounted, onBeforeUnmount, ref, watch, nextTick, toRaw, defineExpose } from 'vue'
import * as klinecharts from 'klinecharts'

const emit = defineEmits(['load-more'])

const props = defineProps({
  data: { type: Array, default: () => [] },
  height: { type: String, default: '100%' },
  precision: { type: Object, default: () => ({ price: 2, volume: 2 }) },
  colors: {
    type: Object,
    default: () => ({
      up: '#2EBD85',
      down: '#F6465D',
      grid: '#F2F4F6',
      text: '#929AA5',
      targetLine: '#4A6EF5'
    })
  }
})

const chartContainer = ref(null)
let chartInstance = null

const initChart = () => {
  if (!chartContainer.value) return
  if (chartInstance) klinecharts.dispose(chartContainer.value)

  chartInstance = klinecharts.init(chartContainer.value)

  const { price, volume } = props.precision
  if (chartInstance.setPriceVolumePrecision) {
    chartInstance.setPriceVolumePrecision(price, volume)
  } else if (chartInstance.setPrecision) {
    chartInstance.setPrecision(price, volume)
  }

  const { up, down, grid, text } = props.colors
  chartInstance.setStyleOptions({
    grid: { show: true, horizontal: { show: true, size: 1, color: grid, style: 'dash', dashValue: [5, 5] }, vertical: { show: false } },
    candle: {
      type: 'candle_solid',
      bar: { upColor: up, downColor: down, noChangeColor: up },
      tooltip: { showRule: 'follow_cross', showType: 'rect', dataSource: 'none' }
    },
    xAxis: { axisLine: { show: false }, tickLine: { show: false }, tickText: { color: text, size: 10, paddingTop: 4 } },
    yAxis: { inside: true, axisLine: { show: false }, tickLine: { show: false }, tickText: { color: text, size: 10, paddingLeft: 4 } },
  })

  // 监听加载更多
  chartInstance.loadMore(timestamp => {
    emit('load-more', timestamp)
  })

  // 初始化指标
  chartInstance.createTechnicalIndicator('MA', false, { id: 'candle_pane' })
  chartInstance.createTechnicalIndicator('VOL', false, { id: 'pane_1', dragEnabled: false })
  chartInstance.createTechnicalIndicator('MACD', false, { id: 'pane_2', dragEnabled: false })

  chartInstance.setPaneOptions({ id: 'candle_pane', heightRatio: 8 })
  chartInstance.setPaneOptions({ id: 'pane_1', heightRatio: 1 })
  chartInstance.setPaneOptions({ id: 'pane_2', heightRatio: 1 })

  if (props.data && props.data.length > 0) {
    chartInstance.applyNewData(toRaw(props.data))
  }
}

const setMainIndicator = (name) => {
  if (!chartInstance) return
  const mains = ['MA', 'EMA', 'BOLL', 'SAR', 'AVL', 'TRIX']
  mains.forEach(m => chartInstance.removeTechnicalIndicator('candle_pane', m))
  if (name && name !== 'Hide') {
    chartInstance.createTechnicalIndicator(name, false, { id: 'candle_pane' })
  }
}

const setSubIndicators = (names) => {
  if (!chartInstance) return
  const paneIds = ['pane_1', 'pane_2', 'pane_3', 'pane_4', 'pane_5']
  const allSubs = ['VOL', 'MACD', 'KDJ', 'RSI', 'WR', 'CCI', 'OBV', 'AO', 'DMA', 'TRIX', 'BRAR', 'VR']

  paneIds.forEach(paneId => {
    allSubs.forEach(sub => chartInstance.removeTechnicalIndicator(paneId, sub))
  })

  const validNames = names.filter(n => n && n !== 'Hide')
  chartInstance.setPaneOptions({ id: 'candle_pane', heightRatio: 8 })

  validNames.forEach((name, index) => {
    const paneId = `pane_${index + 1}`
    chartInstance.createTechnicalIndicator(name, false, { id: paneId, dragEnabled: false })
    chartInstance.setPaneOptions({ id: paneId, heightRatio: 1 })
  })
}

// ---------------------------------------------------------
// 核心修复区域：applyHistoryData
// ---------------------------------------------------------
const applyHistoryData = (dataList, hasMore) => {
  if (!chartInstance) return

  // 1. 获取当前图表里【最左侧/最早】的一条数据
  const currentDataList = chartInstance.getDataList()
  const firstCurrentParams = currentDataList[0]

  // 2. 只有当图表已有数据，且新加载的数据不为空时，才进行去重检测
  if (firstCurrentParams && dataList.length > 0) {
    // 获取新历史数据的【最后一条】(因为传入的 dataList 是按时间升序排列的)
    // 这条数据是时间最晚的，最容易和 currentDataList[0] 重叠
    const lastHistoryParams = dataList[dataList.length - 1]

    // 3. 如果时间戳完全相等，说明重叠了
    if (lastHistoryParams.timestamp === firstCurrentParams.timestamp) {
      // 移除新加载数据中的最后一条 (保留图表中已有的那条)
      // 原因：通常图表里的数据可能已经被 WS 更新过，或者为了避免 UI 闪烁，不替换边界点
      dataList.pop()
    }
  }

  // 4. 将处理后的数据拼接到左侧
  chartInstance.applyMoreData(dataList, hasMore)
}

defineExpose({
  setMainIndicator,
  setSubIndicators,
  applyHistoryData
})

watch(() => props.data, (newData) => {
  if (!chartInstance) return
  const rawData = toRaw(newData)
  const currentList = chartInstance.getDataList()

  if (rawData.length === 0) {
    chartInstance.clearData();
    return
  }

  if (currentList.length === 0) {
    chartInstance.applyNewData(rawData);
    return
  }

  const firstOld = currentList[0]
  const firstNew = rawData[0]
  const lastOld = currentList[currentList.length - 1]
  const lastNew = rawData[rawData.length - 1]

  // 防止历史数据回弹 (Safety check)
  if (firstNew.timestamp < firstOld.timestamp) {
    return
  }

  // 切换 Symbol 或周期时的全量更新检测
  if (lastNew.timestamp !== lastOld.timestamp && rawData.length > 1) {
     const isUpdate = lastNew.timestamp > lastOld.timestamp && rawData.length === currentList.length + 1;
     if (!isUpdate) {
        chartInstance.applyNewData(rawData)
        return
     }
  }

  // WS 实时更新
  if (rawData.length > 0) {
    const lastData = rawData[rawData.length - 1]
    chartInstance.updateData(lastData)
  }
}, { deep: true })

watch(() => props.precision, (val) => {
  if (chartInstance) {
    const method = chartInstance.setPriceVolumePrecision || chartInstance.setPrecision
    if (method) method.call(chartInstance, val.price, val.volume)
  }
}, { deep: true })

onMounted(() => {
  nextTick(() => initChart())
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  if (chartInstance) {
    klinecharts.dispose(chartContainer.value)
    chartInstance = null
  }
})

const handleResize = () => {
  if (chartInstance) chartInstance.resize()
}
</script>

<style scoped>
.kline-wrapper { width: 100%; position: relative; background: #ffffff; }
.kline-chart { width: 100%; height: 100%; }
</style>