<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>
import { drawTrendChart } from '@/common/memberInfo/bodyTestChart.js'

export default {
    options: {
        virtualHost: false,
        styleIsolation: 'apply-shared'
    },
    props: {
        points: { type: Array, default: () => [] },
        unit: { type: String, default: '' },
        width: { type: Number, default: 300 },
        height: { type: Number, default: 160 }
    },
    data() {
        return {
            canvasId: `bt-trend-${Math.random().toString(36).slice(2, 9)}`
        }
    },
    watch: {
        points: {
            deep: true,
            handler() {
                this.renderChart()
            }
        }
    },
    mounted() {
        this.renderChart()
    },
    methods: {
        renderChart() {
            this.$nextTick(() => {
                const query = uni.createSelectorQuery().in(this)
                query
                    .select(`#${this.canvasId}`)
                    .fields({ node: true, size: true })
                    .exec((res) => {
                        const node = res?.[0]?.node
                        if (!node) return
                        const dpr = uni.getSystemInfoSync().pixelRatio || 1
                        drawTrendChart(node, {
                            width: this.width,
                            height: this.height,
                            points: this.points,
                            unit: this.unit,
                            dpr
                        })
                    })
            })
        }
    }
}
</script>

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

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