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

Page({
    data: {
        dimensions: [],
        achievedMap: {},
        isLoading: true,
        selectedBadge: null,
        showDetail: false,
        activeTab: 0
    },

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

    switchTab(e) {
        const index = e.currentTarget.dataset.index;
        if (index !== undefined) {
            this.setData({ activeTab: index });
        }
    },

    async fetchData() {
        this.setData({ isLoading: true });
        wx.showLoading({ title: '加载中...' });
        try {
            // Parallel Fetch: Config Tree & User Badges
            const [treeRes, userBadgesRes] = await Promise.all([
                request.get('/plant/config/badge/tree'),
                request.get('/plant/profile/badge')
            ]);

            const list = Array.isArray(treeRes) ? treeRes : (treeRes.data || []);

            // Extract user badge list from response structure { list: [...] }
            let userBadgeList = [];
            if (Array.isArray(userBadgesRes)) {
                userBadgeList = userBadgesRes;
            } else if (userBadgesRes && Array.isArray(userBadgesRes.list)) {
                userBadgeList = userBadgesRes.list;
            } else if (userBadgesRes && userBadgesRes.data) {
                userBadgeList = userBadgesRes.data || [];
            }

            // Populate Achieved Map using Badge ID (not Record ID)
            let achievedMap = {};
            userBadgeList.forEach(b => {
                const badgeId = b.badgeId || (b.badge ? b.badge.id : null);
                if (badgeId) {
                    achievedMap[badgeId] = b;
                }
            });

            this.setData({
                dimensions: list,
                achievedMap
            });
        } catch (e) {
            console.error('Fetch badge data failed', e);
            wx.showToast({ title: '加载失败', icon: 'none' });
        } finally {
            this.setData({ isLoading: false });
            wx.hideLoading();
        }
    },

    onBadgeTap(e) {
        const badge = e.currentTarget.dataset.badge;
        this.setData({
            selectedBadge: badge,
            showDetail: true
        });
    },

    closeDetail() {
        this.setData({ showDetail: false });
    },

    noop() { }
});
