<template>
    <view class="scroll-container theme-light">
        <view class="bt-page">
            <MemberInfoSubNav title="趋势分析" @back="onBack" />
            <view class="bt-tabs">
                <view
                    v-for="tab in tabs"
                    :key="tab.key"
                    class="bt-tab"
                    :class="{ 'bt-tab--active': activeMetric === tab.key }"
                    hover-class="mi-tap-tab--hover"
                    :hover-stay-time="150"
                    @tap="switchMetric(tab.key)"
                >
                    <text class="bt-tab__text">{{ tab.label }}</text>
                </view>
            </view>
            <view class="bt-page__body">
                <view class="bt-card">
                    <text class="bt-card__title">{{ activeLabel }}变化趋势</text>
                    <text class="bt-card__desc">基于最近 {{ trendPoints.length }} 次体测数据</text>
                    <BodyTestTrendChart
                        :points="trendPoints"
                        :unit="activeUnit"
                        :width="chartWidth"
                        :height="200"
                    />
                </view>

                <view class="bt-card">
                    <text class="bt-card__title">数据明细</text>
                    <view
                        v-for="(pt, idx) in trendPointsReversed"
                        :key="pt.id"
                        class="bt-compare-row"
                    >
                        <text class="bt-compare-row__label">{{ pt.date }}</text>
                        <text class="bt-compare-row__val">{{ pt.value }}{{ activeUnit }}</text>
                        <text
                            v-if="idx < trendPointsReversed.length - 1"
                            class="bt-compare-row__diff"
                            :style="{ color: rowDiffColor(pt, trendPointsReversed[idx + 1]) }"
                        >
                            {{ rowDiffText(pt, trendPointsReversed[idx + 1]) }}
                        </text>
                        <text v-else class="bt-compare-row__diff">--</text>
                    </view>
                </view>

                <view v-if="summaryText" class="bt-card">
                    <text class="bt-card__title">趋势解读</text>
                    <text class="bt-card__desc">{{ summaryText }}</text>
                </view>
            </view>
        </view>
    </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import MemberInfoSubNav from '@/components/memberInfo/MemberInfoSubNav.vue'
import BodyTestTrendChart from '@/components/memberInfo/BodyTestTrendChart.vue'
import { PAGE, goBackOrTab } from '@/common/constants/routes.js'
import { loadMemberStore } from '@/common/memberInfo/store.js'
import { getBodyTestTrendData } from '@/common/memberInfo/bodyTestStore.js'

const tabs = ref([
    { key: 'weight', label: '体重' },
    { key: 'bodyFat', label: '体脂率' },
    { key: 'muscleMass', label: '肌肉量' },
    { key: 'bmi', label: 'BMI' }
])
const activeMetric = ref('weight')
const trendPoints = ref([])
const chartWidth = ref(300)

const units = {
    weight: 'kg',
    bodyFat: '%',
    muscleMass: 'kg',
    bmi: ''
}

const activeLabel = computed(() => {
    return tabs.value.find((t) => t.key === activeMetric.value)?.label || ''
})

const activeUnit = computed(() => {
    return units[activeMetric.value] || ''
})

const trendPointsReversed = computed(() => {
    return [...trendPoints.value].reverse()
})

const summaryText = computed(() => {
    if (trendPoints.value.length < 2) return ''
    const first = trendPoints.value[0].value
    const last = trendPoints.value[trendPoints.value.length - 1].value
    const diff = Math.round((last - first) * 10) / 10
    const sign = diff > 0 ? '上升' : diff < 0 ? '下降' : '持平'
    const abs = Math.abs(diff)
    const lowerBetter = ['weight', 'bodyFat'].includes(activeMetric.value)
    let advice = ''
    if (diff !== 0) {
        const good = lowerBetter ? diff < 0 : diff > 0
        advice = good ? '，变化方向符合健康目标' : '，建议关注饮食与训练计划'
    }
    return `期间${activeLabel.value}${sign} ${abs}${activeUnit.value}${advice}`
})

function onBack() {
    goBackOrTab(PAGE.BODY_TEST_HOME)
}

function switchMetric(key) {
    activeMetric.value = key
    loadTrend()
}

function loadTrend() {
    const store = loadMemberStore()
    trendPoints.value = getBodyTestTrendData(store, activeMetric.value, 6)
}

function rowDiffText(current, older) {
    const diff = Math.round((current.value - older.value) * 10) / 10
    const sign = diff > 0 ? '+' : ''
    return `${sign}${diff}${activeUnit.value}`
}

function rowDiffColor(current, older) {
    const diff = current.value - older.value
    if (diff === 0) return '#8A99B4'
    const lowerBetter = ['weight', 'bodyFat'].includes(activeMetric.value)
    const good = lowerBetter ? diff < 0 : diff > 0
    return good ? '#2ECC71' : '#F39C12'
}

onMounted(() => {
    const pages = getCurrentPages()
    const currentPage = pages[pages.length - 1]
    const options = currentPage?.options || {}
    if (options?.metric) {
        activeMetric.value = options.metric
    }
    chartWidth.value = uni.getSystemInfoSync().windowWidth - 64
    loadTrend()
})
</script>

<style lang="scss">
@import '@/common/style/base.css';
@import '@/common/style/memberInfo/pages/page-reset.css';
@import '@/common/style/memberInfo/pages/sub-page-base.css';
@import '@/common/style/memberInfo/member-info-component-reset.css';
@import '@/common/style/memberInfo/member-info-sub-nav.css';
@import '@/common/style/memberInfo/member-info-tap.css';
@import '@/common/style/memberInfo/pages/body-test-common.css';
</style>
