<template>
    <view class="bt-trend">
        <canvas
            :id="canvasId"
            :canvas-id="canvasId"
            type="2d"
            class="bt-trend__canvas"
            :style="{ width: width + 'px', height: height + 'px' }"
        />
    </view>
</template>

<script setup>
import { ref, watch, onMounted, nextTick } from 'vue'
import { drawTrendChart } from '@/common/memberInfo/bodyTestChart.js'

const props = defineProps({
    points: { type: Array, default: () => [] },
    unit: { type: String, default: '' },
    width: { type: Number, default: 300 },
    height: { type: Number, default: 160 }
})

const canvasId = ref(`bt-trend-${Math.random().toString(36).slice(2, 9)}`)

function renderChart() {
    nextTick(() => {
        const query = uni.createSelectorQuery().in(getCurrentInstance())
        query
            .select(`#${canvasId.value}`)
            .fields({ node: true, size: true })
            .exec((res) => {
                const node = res?.[0]?.node
                if (!node) return
                const dpr = uni.getSystemInfoSync().pixelRatio || 1
                drawTrendChart(node, {
                    width: props.width,
                    height: props.height,
                    points: props.points,
                    unit: props.unit,
                    dpr
                })
            })
    })
}

watch(() => props.points, () => {
    renderChart()
}, { deep: true })

onMounted(() => {
    renderChart()
})
</script>

<style lang="scss">
.bt-trend {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
}

.bt-trend__canvas {
    display: block;
}
</style>
