import request from '../../../../utils/request';

Page({
    data: {
        levels: [],
        currentSunlight: 0,
        currentLevel: 0
    },

    onLoad(options) {
        let sunlight;
        if (options.sunlight !== undefined) {
            sunlight = parseInt(options.sunlight, 10);
            if (!isNaN(sunlight)) {
                this.setData({ currentSunlight: sunlight });
            } else {
                sunlight = undefined;
            }
        }

        this.fetchData(sunlight);
    },

    async fetchData(passedSunlight) {
        wx.showLoading({ title: '加载中...' });
        try {
            // Fetch levels
            const levelRes = await request.get('/plant/config/level/list');


            let list = [];
            if (levelRes) {
                if (Array.isArray(levelRes)) {
                    list = levelRes;
                } else if (Array.isArray(levelRes.list)) {
                    list = levelRes.list;
                } else if (levelRes.data && Array.isArray(levelRes.data.list)) {
                    list = levelRes.data.list;
                } else if (levelRes.data && Array.isArray(levelRes.data)) {
                    list = levelRes.data;
                }
            }


            list.sort((a, b) => a.minSunlight - b.minSunlight);

            // Fetch profile if sunlight not passed
            let currentSunlight = passedSunlight;
            if (currentSunlight === undefined) {
                const profileRes = await request.get('/plant/profile/detail');

                currentSunlight = profileRes.totalSunlight || 0;
                this.setData({ currentSunlight });
            }

            // Calculate current level
            let currentLevel = 0;
            // Iterate finding the highest level where minSunlight <= currentSunlight
            for (let i = list.length - 1; i >= 0; i--) {
                if (currentSunlight >= list[i].minSunlight) {
                    currentLevel = list[i].level;
                    break;
                }
            }



            this.setData({
                levels: list,
                currentLevel
            });
        } catch (e) {
            console.error('Fetch level detail failed', e);
            wx.showToast({ title: '数据加载失败', icon: 'none' });
        } finally {
            wx.hideLoading();
        }
    }
});
