// pages/garden/index.js
import request from '../../utils/request';
import { calculateDaysSince } from '../../utils/dateUtil';

Page({
    data: {
        plants: [],
        dateString: '',
        greeting: '',
        bannerList: [],
        currentBanner: 0,

        // Pagination
        currentPage: 1,
        pageSize: 6,
        total: 0,
        isLastPage: false,
        isLoading: false,
        isRefreshing: false,
        scrollTop: 0
    },

    onLoad(options) {
        this.initTime();
        this.loadPlants(true);
        this.loadBanners();
    },

    onShow() {
        if (typeof this.getTabBar === 'function' &&
            this.getTabBar()) {
            this.getTabBar().setData({
                selected: 0
            })
        }
        // Refresh list on show to ensure data is up-to-date
        // We use reset=true to reload from page 1
        this.loadPlants(true);
    },

    // Pull to refresh (page-level)
    onPullDownRefresh() {
        this.loadPlants(true).then(() => {
            wx.stopPullDownRefresh();
        });
    },

    // Pull to refresh (scroll-view)
    onRefresh() {
        this.setData({ isRefreshing: true });
        this.loadPlants(true).then(() => {
            this.setData({ isRefreshing: false });
        }).catch(() => {
            this.setData({ isRefreshing: false });
        });
    },

    // Infinite scroll
    onReachBottom() {
        if (!this.data.isLastPage && !this.data.isLoading) {
            this.loadPlants(false);
        }
    },

    loadPlants(reset = false) {
        if (this.data.isLoading) return Promise.resolve();

        this.setData({ isLoading: true });

        const page = reset ? 1 : this.data.currentPage + 1;
        const payload = {
            current: page,
            pageSize: this.data.pageSize,
            keyword: ''
        };

        return request.post('/plant/page', payload).then(res => {
            const list = res.list || [];
            const total = res.total || 0;

            // Map backend data to UI structure: 1. Map imgList to images array with path resolution
            const mappedList = list.map(item => {
                let imageUrl = '';
                if (item.imgList && item.imgList.length > 0) {
                    imageUrl = item.imgList[0].url || '';
                }

                // Calculate days
                const days = calculateDaysSince(item.plantTime);

                return { ...item, images: [imageUrl], daysPlanted: days };
            });

            this.setData({
                plants: reset ? mappedList : [...this.data.plants, ...mappedList],
                currentPage: page,
                total: total,
                isLastPage: (reset ? mappedList.length : this.data.plants.length + mappedList.length) >= total,
                isLoading: false
            });
        }).catch(err => {
            console.error('Load plants failed', err);
            this.setData({ isLoading: false });
            wx.showToast({ title: '加载失败', icon: 'none' });
        });
    },

    async loadBanners() {
        try {
            const res = await request.get('/plant/banner/activeList');
            const list = (res.list || []).map(item => item.imageUrl || '');
            this.setData({ bannerList: list.filter(Boolean) });
        } catch (err) {
            console.error('Load banners failed', err);
        }
    },

    initTime() {
        const updateTime = () => {
            const now = new Date();
            const hour = now.getHours();

            let greet = '晚上好';
            if (hour >= 5 && hour < 12) greet = '上午好';
            else if (hour >= 12 && hour < 14) greet = '中午好';
            else if (hour >= 14 && hour < 19) greet = '下午好';

            const month = now.getMonth() + 1;
            const day = now.getDate();
            const weekDays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
            const weekDay = weekDays[now.getDay()];

            this.setData({
                greeting: greet,
                dateString: `${month}月${day}日 ${weekDay}`
            });
        };

        updateTime();
    },

    onBannerChange(e) {
        this.setData({ currentBanner: e.detail.current });
    },

    navigateToDetail(e) {
        const { id } = e.currentTarget.dataset;
        wx.navigateTo({
            url: `/pages/plant-detail/index?id=${id}`,
        });
    },

    navigateToAdd() {
        wx.navigateTo({
            url: '/pages/garden/add/index'
        });
    },

    onScrollLower() {
        if (!this.data.isLastPage && !this.data.isLoading) {
            this.loadPlants(false);
        }
    },

    onShareAppMessage() {
        return {
            title: '我的私人花园 - 植趣',
            path: '/pages/garden/index'
        };
    },

    onShareTimeline() {
        return {
            title: '我的私人花园 - 植趣'
        };
    },

    onTabItemTap() {
        // Reset scroll when switching to this tab
        // Use random small value to force data change detection
        this.setData({ scrollTop: Math.random() * 0.01 });
    }
})
