<script setup lang="ts">
import dayjs from 'dayjs'
import * as WeatherAPI from '@/api/model/weather'
import { Echarts, useEcharts } from '@/components/Echarts'
import { getDayLabelValue, getWeatherIcon } from '@/utils/weather'

// 逐 7 天预报图表
const [register7Forecast, Forecast7Chart] = useEcharts()
const model = reactive({
    days: 15,
    updateTime: '-',
})

onLoad(async () => {
    const location = uni.getStorageSync('location')
    const forecasts = await WeatherAPI.forecast(`${location.lon},${location.lat}`, model.days).then((res) => {
        model.updateTime = dayjs(res.data.updateTime).format('YYYY-MM-DD HH:mm')
        return res.data.daily
    })
    console.log('forecasts', forecasts)

    // 逐 7 天预报数据
    const _7DayForecastData = forecasts.map((item, index) => {
        return {
            minTem: item.tempMin,
            maxTem: item.tempMax,
            textDay: item.textDay,
            textNight: item.textNight,
            dayWeather: item.iconDay,
            nightWeather: item.iconNight,
            fxDate: item.fxDate,
            ...getDayLabelValue(index),
        }
    })
    const _7DayForecastMaxTemValue = Math.max(..._7DayForecastData.map((item) => Number(item.maxTem)))

    // 设置逐 7 天预报图表参数
    Forecast7Chart.setOption({
        tooltip: {
            show: true,
            trigger: 'axis',
            axisPointer: {
                type: 'shadow',
            },
            formatter: (params) => {
                // 过滤掉星期标签、日期标签和天气图标
                const filteredParams = params.filter(param => {
                    return param.seriesName !== '星期标签' && 
                           param.seriesName !== '日期标签' && 
                           param.seriesName !== '天气图标';
                });
                if (filteredParams.length === 0) return '';
                
                let result = '';
                filteredParams.forEach(param => {
                    // 只显示有意义的数值信息
                    if (param.seriesName === '最高温度' || param.seriesName === '最低温度') {
                        result += `${param.seriesName}: ${param.value}°<br/>`;
                    }
                });
                return result;
            }
        },
        grid: {
            top: '5%',
            bottom: '10%',
            left: '0',
            right: '3%',
        },
        xAxis: {
            type: 'category',
            data: _7DayForecastData.map((item) => item.textNight),
            axisLine: {
                show: false,
            },
            axisTick: {
                show: false,
            },
            axisLabel: {
                show: true, // 隐藏x轴标签
                interval: 0,
                color: '#999',
                fontSize: 11,
            },
        },
        yAxis: {
            type: 'value',
            splitLine: {
                show: false,
            },
            axisLabel: {
                show: false,
            },
        },
        series: [
            // 顶部星期标签（今天、明天、周X）- 第一行
            {
                name: '星期标签',
                type: 'scatter',
                data: _7DayForecastData.map((item, index) => {
                    return {
                        value: [index, Number(_7DayForecastMaxTemValue) + 13],
                        symbolSize: 0,
                        label: {
                            show: true,
                            position: 'top',
                            formatter: item.label,
                            fontSize: 14,
                            color: '#333333',
                            fontWeight: 'bold',
                        },
                    }
                }),
            },
            // 顶部日期标签（09/10）- 第二行
            {
                name: '日期标签',
                type: 'scatter',
                data: _7DayForecastData.map((item, index) => {
                    return {
                        value: [index, Number(_7DayForecastMaxTemValue) + 10],
                        symbolSize: 0,
                        label: {
                            show: true,
                            position: 'top',
                            formatter: `${item.value}`,
                            fontSize: 12,
                            color: '#666666',
                        },
                    }
                }),
            },
            {
                name: '日期标签',
                type: 'scatter',
                data: _7DayForecastData.map((item, index) => {
                    return {
                        value: [index, Number(_7DayForecastMaxTemValue) + 7],
                        symbolSize: 0,
                        label: {
                            show: true,
                            position: 'top',
                            formatter: `${item.textDay}`,
                            fontSize: 12,
                            color: '#666666',
                        },
                    }
                }),
            },
            // 天气图标 - 第三行
            {
                name: '天气图标',
                type: 'scatter',
                data: _7DayForecastData.map((item, index) => {
                    return {
                        value: [index, Number(_7DayForecastMaxTemValue) + 5],
                        symbol: `image://${getWeatherIcon(String(item.dayWeather))}`,
                        symbolSize: [28, 28],
                    }
                }),
            },
            
            // 最高温度线
            {
                name: '最高温度',
                type: 'line',
                data: _7DayForecastData.map((item) => item.maxTem),
                smooth: true,
                color: '#F79D80',
                symbolSize: 6,
                label: {
                    show: true,
                    position: 'top',
                    formatter: '{c}°',
                    color: '#F79D80',
                    fontSize: 11,
                },
            },
            // 最低温度线
            {
                name: '最低温度',
                type: 'line',
                data: _7DayForecastData.map((item) => item.minTem),
                smooth: true,
                color: '#52C41A',
                symbolSize: 6,
                label: {
                    show: true,
                    position: 'bottom',
                    formatter: '{c}°',
                    color: '#52C41A',
                    fontSize: 11,
                },
            },
        ],
    })
})
</script>

<template>
    <view class="wrap pb-3">
        <!-- 逐 7 天预报图表 -->
        <view class="rain-forecast mt-2rpx bg-#fff rd-1.5 shadow flex flex-col px-2">
            <view class="flex items-center justify-between pt-3 px-2">
                <view class="text-32 font-600">{{ model.days }}天预报</view>
                <!-- <view class="text-24">发布时间：{{ model.updateTime }}</view> -->
            </view>
            <scroll-view class="flex-1" scroll-x="true">
                <Echarts @register="register7Forecast" class="w-1400 h-600" />
            </scroll-view>
        </view>
    </view>
</template>

<style lang="scss" scoped>
//
</style>
