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

Page({
    data: {
        myPublishedPosts: [],
        current: 1,
        pageSize: 10,
        hasMore: true,
        isLoading: false,
        isRefreshing: false
    },

    onLoad() {
        this.loadMyPosts(true);
    },

    onPullDownRefresh() {
        if (this.data.isLoading) return;
        this.setData({ isRefreshing: true });
        this.loadMyPosts(true).then(() => {
            this.setData({ isRefreshing: false });
        });
    },

    onReachBottom() {
        if (this.data.hasMore && !this.data.isLoading) {
            this.loadMyPosts(false);
        }
    },

    async loadMyPosts(reset = false) {
        if (this.data.isLoading) return;
        this.setData({ isLoading: true });

        const current = reset ? 1 : this.data.current;
        const { pageSize } = this.data;

        try {
            const res = await request.post('/plant/post/myPost', {
                current,
                pageSize
            });

            const data = res.data || res || {};
            const records = data.records || data.list || [];

            const posts = records.map(item => {
                const imgList = item.imgList || [];
                return {
                    id: item.id,
                    content: item.content || '',
                    time: this._formatTime(item.createdAt || item.createTime),
                    images: imgList.map(img => img.url),
                    likes: item.likeList || [],
                    comments: item.commentList || [],
                    hasReviewed: item.hasReviewed
                };
            });

            if (reset) {
                this.setData({
                    myPublishedPosts: posts,
                    current: current + 1,
                    hasMore: posts.length >= pageSize,
                    isLoading: false
                });
            } else {
                this.setData({
                    myPublishedPosts: [...this.data.myPublishedPosts, ...posts],
                    current: current + 1,
                    hasMore: posts.length >= pageSize,
                    isLoading: false
                });
            }
        } catch (err) {
            console.error('Load my posts failed', err);
            this.setData({ isLoading: false });
            wx.showToast({ title: '加载失败', icon: 'none' });
        }
    },

    _formatTime(dateStr) {
        if (!dateStr) return '';
        const d = new Date(dateStr);
        const now = new Date();
        const diffMs = now - d;
        const diffMin = Math.floor(diffMs / 60000);
        if (diffMin < 1) return '刚刚';
        if (diffMin < 60) return diffMin + '分钟前';
        const diffHour = Math.floor(diffMin / 60);
        if (diffHour < 24) return diffHour + '小时前';
        const diffDay = Math.floor(diffHour / 24);
        if (diffDay < 7) return diffDay + '天前';
        const month = (d.getMonth() + 1).toString().padStart(2, '0');
        const day = d.getDate().toString().padStart(2, '0');
        return `${month}-${day}`;
    },

    deletePost(e) {
        const postId = e.currentTarget.dataset.id;
        wx.showModal({
            title: '删除动态',
            content: '确定要删除这条动态吗？',
            confirmColor: '#EF5350',
            success: (res) => {
                if (!res.confirm) return;
                wx.showLoading({ title: '删除中...' });

                // Use new API: POST /post/delete with ids array
                request.post('/plant/post/delete', { ids: [postId] }).then(() => {
                    wx.hideLoading();
                    wx.showToast({ title: '已删除', icon: 'success' });
                    // Remove from list locally
                    const newList = this.data.myPublishedPosts.filter(p => p.id !== postId);
                    this.setData({ myPublishedPosts: newList });
                }).catch(() => {
                    wx.hideLoading();
                    wx.showToast({ title: '删除失败', icon: 'none' });
                });
            }
        });
    }
});
