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

Page({
    data: {
        records: [],
        loading: true,
        page: 1,
        pageSize: 20,
        total: 0,
        hasMore: true,
        expandedId: '', // Track which card is expanded
    },

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

    async loadRecords() {
        this.setData({ loading: true });
        try {
            const res = await request.post('/plant/classify/myClassifyLog', {
                page: this.data.page,
                pageSize: this.data.pageSize,
            });
            const list = (res.list || []).map(item => this._transformRecord(item));
            this.setData({
                records: this.data.page === 1 ? list : [...this.data.records, ...list],
                total: res.total || 0,
                hasMore: list.length >= this.data.pageSize,
                loading: false,
            });
        } catch (err) {
            console.error('Load identify history failed', err);
            this.setData({ loading: false });
            wx.showToast({ title: '加载失败', icon: 'none' });
        }
    },

    _transformRecord(item) {
        const allResults = item.allResults || [];
        const topResult = allResults[0] || {};
        const otherResults = allResults.slice(1);

        return {
            id: item.id,
            time: this._formatTime(item.createdAt),
            dateStr: item.createdAtStr || '',
            topName: topResult.name || '未知植物',
            topScore: topResult.score ? Math.round(topResult.score * 100) : 0,
            topImage: topResult.baike_info?.image_url || '',
            topDesc: topResult.baike_info?.description || '',
            topBaikeUrl: topResult.baike_info?.baike_url || '',
            otherResults: otherResults.map(r => ({
                name: r.name || '未知',
                score: r.score ? Math.round(r.score * 100) : 0,
                hasInfo: !!r.baike_info,
            })),
        };
    },

    toggleExpand(e) {
        const id = e.currentTarget.dataset.id;
        this.setData({
            expandedId: this.data.expandedId === id ? '' : id,
        });
    },

    onReachBottom() {
        if (!this.data.hasMore || this.data.loading) return;
        this.setData({ page: this.data.page + 1 }, () => {
            this.loadRecords();
        });
    },

    onPullDownRefresh() {
        this.setData({ page: 1, hasMore: true }, () => {
            this.loadRecords().then(() => {
                wx.stopPullDownRefresh();
            });
        });
    },

    deleteLog(e) {
        const id = e.currentTarget.dataset.id;
        wx.showModal({
            title: '提示',
            content: '确定要删除这条识别记录吗？',
            confirmColor: '#EF5350',
            success: (res) => {
                if (res.confirm) {
                    wx.showLoading({ title: '删除中' });
                    request.post('/plant/classify/deleteClassifyLog', { ids: [id] }).then(() => {
                        wx.hideLoading();
                        wx.showToast({ title: '删除成功', icon: 'success' });
                        const newRecords = this.data.records.filter(r => r.id !== id);
                        this.setData({ records: newRecords });
                    }).catch(err => {
                        wx.hideLoading();
                        console.error('Delete log failed', err);
                        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');
        const hour = d.getHours().toString().padStart(2, '0');
        const min = d.getMinutes().toString().padStart(2, '0');
        return `${month}-${day} ${hour}:${min}`;
    },
});
