<template>
  <view v-if="!data || data.length === 0" class="trend-chart-empty">
    <text class="trend-chart-empty-text">暂无数据</text>
  </view>
  <view v-else class="trend-chart" :style="{ height: (height || 500) + 'rpx' }">
    <canvas type="2d" id="trend-chart-canvas" class="trend-canvas"
      :style="{ width: '100%', height: '100%' }" />
  </view>
</template>

<script setup lang="ts">
import { watch, onMounted, nextTick, ref } from 'vue'

const props = withDefaults(defineProps<{
  data: { date: string; value: number }[]
  referenceMin?: number
  referenceMax?: number
  unit?: string
  height?: number
}>(), {
  unit: '',
  height: 500,
})

const canvasReady = ref(false)

function drawLine(ctx: any, points: { x: number; y: number }[]) {
  if (points.length < 2) return
  ctx.beginPath()
  ctx.moveTo(points[0].x, points[0].y)
  for (let i = 1; i < points.length; i++) {
    const prev = points[i - 1]
    const curr = points[i]
    const cpx = (prev.x + curr.x) / 2
    ctx.bezierCurveTo(cpx, prev.y, cpx, curr.y, curr.x, curr.y)
  }
  ctx.stroke()
}

function draw() {
  if (!props.data || props.data.length === 0) return

  const query = uni.createSelectorQuery()
  query.select('#trend-chart-canvas').fields({ node: true, size: true }).exec((res) => {
    if (!res || !res[0] || !res[0].node) return
    const canvas = res[0].node
    const ctx = canvas.getContext('2d')
    const dpr = uni.getSystemInfoSync().pixelRatio || 2
    const w = res[0].width
    const h = res[0].height
    canvas.width = w * dpr
    canvas.height = h * dpr
    ctx.scale(dpr, dpr)

    const pad = { top: 20, right: 16, bottom: 32, left: 48 }
    const cw = w - pad.left - pad.right
    const ch = h - pad.top - pad.bottom

    const values = props.data.map(d => d.value)
    let yMin = Math.min(...values)
    let yMax = Math.max(...values)
    if (props.referenceMin !== undefined) yMin = Math.min(yMin, props.referenceMin)
    if (props.referenceMax !== undefined) yMax = Math.max(yMax, props.referenceMax)
    const yPad = (yMax - yMin) * 0.1 || 1
    yMin -= yPad
    yMax += yPad

    ctx.clearRect(0, 0, w, h)

    // Reference band
    if (props.referenceMin !== undefined && props.referenceMax !== undefined) {
      const ry1 = pad.top + ch * (1 - (props.referenceMax - yMin) / (yMax - yMin))
      const ry2 = pad.top + ch * (1 - (props.referenceMin - yMin) / (yMax - yMin))
      ctx.fillStyle = 'rgba(91, 122, 94, 0.1)'
      ctx.fillRect(pad.left, ry1, cw, ry2 - ry1)
    }

    // Grid lines
    ctx.strokeStyle = '#e5e5e5'
    ctx.lineWidth = 0.5
    for (let i = 0; i <= 4; i++) {
      const y = pad.top + (ch / 4) * i
      ctx.beginPath()
      ctx.moveTo(pad.left, y)
      ctx.lineTo(pad.left + cw, y)
      ctx.stroke()
      const val = yMax - ((yMax - yMin) / 4) * i
      ctx.fillStyle = '#78716C'
      ctx.font = '10px sans-serif'
      ctx.textAlign = 'right'
      ctx.fillText(val.toFixed(1), pad.left - 6, y + 3)
    }

    // X labels
    ctx.textAlign = 'center'
    ctx.fillStyle = '#78716C'
    ctx.font = '10px sans-serif'
    const step = Math.max(1, Math.floor(props.data.length / 6))
    for (let i = 0; i < props.data.length; i += step) {
      const x = pad.left + (cw / Math.max(1, props.data.length - 1)) * i
      ctx.fillText(props.data[i].date.slice(5), x, h - 8)
    }

    // Data points
    const points = props.data.map((d, i) => ({
      x: pad.left + (cw / Math.max(1, props.data.length - 1)) * i,
      y: pad.top + ch * (1 - (d.value - yMin) / (yMax - yMin)),
    }))

    // Area fill
    ctx.beginPath()
    ctx.moveTo(points[0].x, points[0].y)
    for (let i = 1; i < points.length; i++) {
      const cpx = (points[i - 1].x + points[i].x) / 2
      ctx.bezierCurveTo(cpx, points[i - 1].y, cpx, points[i].y, points[i].x, points[i].y)
    }
    ctx.lineTo(points[points.length - 1].x, pad.top + ch)
    ctx.lineTo(points[0].x, pad.top + ch)
    ctx.closePath()
    const grad = ctx.createLinearGradient(0, pad.top, 0, pad.top + ch)
    grad.addColorStop(0, 'rgba(196, 98, 58, 0.3)')
    grad.addColorStop(1, 'rgba(196, 98, 58, 0.02)')
    ctx.fillStyle = grad
    ctx.fill()

    // Line
    ctx.strokeStyle = '#C4623A'
    ctx.lineWidth = 2
    drawLine(ctx, points)

    // Dots
    for (let i = 0; i < points.length; i++) {
      const d = props.data[i]
      const outOfRange =
        (props.referenceMin !== undefined && d.value < props.referenceMin) ||
        (props.referenceMax !== undefined && d.value > props.referenceMax)
      ctx.beginPath()
      ctx.arc(points[i].x, points[i].y, outOfRange ? 5 : 3, 0, Math.PI * 2)
      ctx.fillStyle = outOfRange ? '#B54A4A' : '#C4623A'
      ctx.fill()
    }
  })
}

onMounted(() => {
  nextTick(() => { canvasReady.value = true; draw() })
})

watch(() => [props.data, props.referenceMin, props.referenceMax], () => {
  if (canvasReady.value) nextTick(draw)
})
</script>

<style lang="scss" scoped>
.trend-chart {
  background: $card;
  border-radius: $r;
  padding: 16px;
  box-shadow: $shadow-sm;
}

.trend-canvas {
  display: block;
}

.trend-chart-empty {
  @include flex-center;
  padding: 40px;
}

.trend-chart-empty-text {
  font-size: var(--tk-font-body-sm);
  color: $tx3;
}
</style>
