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

Page({
    data: {
        userLevel: 0,
        userLevelTag: '',
        currentExp: 0,
        maxExp: 1000,
        maxExp: 1000,
        nextLevelExp: 1000,
        showLevelsPopup: false,
        allLevels: [],

        badges: [
            { id: 1, name: '初级播种者', desc: '成功种植第一棵植物', iconName: 'flower', color: '#4CAF50', unlocked: true },
            { id: 2, name: '勤劳园丁', desc: '总养护次数达到10次', iconName: 'tools', color: '#2196F3', unlocked: true },
            { id: 3, name: '植物专家', desc: '成功识别50种植物', iconName: 'scan', color: '#9C27B0', unlocked: false, progress: '12/50' },
            { id: 4, name: '全勤奖', desc: '连续30天打卡', iconName: 'calendar', color: '#FF9800', unlocked: false, progress: '5/30' },
            { id: 5, name: '分享大师', desc: '发布10条动态', iconName: 'share', color: '#E91E63', unlocked: false, progress: '3/10' },
            { id: 6, name: '收藏家', desc: '收藏20个植物百科', iconName: 'star', color: '#FFC107', unlocked: false, progress: '8/20' }
        ]
    },

    onLoad() {
        this.fetchData();
    },

    async fetchData() {
        wx.showLoading({ title: '加载中...' });
        try {
            const [levelRes, profileRes] = await Promise.all([
                request.get('/plant/config/level/list'),
                request.get('/plant/profile/detail')
            ]);
            this.processData(levelRes, profileRes);
        } catch (e) {
            console.error('Fetch badges data failed', e);
            wx.showToast({ title: '加载失败', icon: 'none' });
        } finally {
            wx.hideLoading();
        }
    },

    processData(levelsData, profile) {
        const levelList = levelsData && levelsData.list ? levelsData.list : [];
        levelList.sort((a, b) => a.minSunlight - b.minSunlight); // Ensure sorted by threshold

        const totalSunlight = profile.totalSunlight || 0;

        // Find current level: highest level where minSunlight <= totalSunlight
        let currentLevelConfig = null;
        for (let i = levelList.length - 1; i >= 0; i--) {
            if (totalSunlight >= levelList[i].minSunlight) {
                currentLevelConfig = levelList[i];
                break;
            }
        }

        // Check if no level matched (e.g. 0 sunlight but level 1 starts at 0? Logic handles it if sorted)
        if (!currentLevelConfig && levelList.length > 0) {
            // Fallback to absolute lowest or specific logic
            // Assuming level 1 starts at 0, it should be caught.
            currentLevelConfig = levelList[0];
        }

        const currentLevelVal = currentLevelConfig ? currentLevelConfig.level : 0;

        // Find next level
        const nextLevelConfig = levelList.find(l => l.minSunlight > totalSunlight);

        let maxExp = 0;
        let nextPerk = '';

        if (nextLevelConfig) {
            maxExp = nextLevelConfig.minSunlight;
            nextPerk = nextLevelConfig.perks;
        } else {
            // Max level
            maxExp = totalSunlight > 0 ? totalSunlight : 100;
            nextPerk = '已达到最高等级';
        }

        // Sanity
        if (maxExp < totalSunlight) maxExp = totalSunlight;

        const tag = currentLevelConfig ? `Lv.${currentLevelVal} ${currentLevelConfig.title}` : 'Lv.0 园艺新手';

        this.setData({
            userLevel: currentLevelVal,
            userLevelTag: tag,
            currentExp: totalSunlight,
            maxExp: maxExp,
            nextLevelExp: Math.max(0, maxExp - totalSunlight),
            nextPerk: nextPerk,
            allLevels: levelList // Save for popup
        });
    },

    showLevelList() {
        wx.navigateTo({
            url: `/pages/profile/badges/level-detail/index?sunlight=${this.data.currentExp}`
        });
    },

    openBadgeWall() {
        wx.navigateTo({
            url: '/pages/profile/badges/badge-wall/index'
        });
    },
});
