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

const STATUS_MAP = {
    1: { text: '待处理', theme: 'warning' },
    2: { text: '处理中', theme: 'primary' },
    3: { text: '已发货', theme: 'primary' },
    4: { text: '已完成', theme: 'success' },
    5: { text: '已取消', theme: 'default' }
};

Page({
    data: {
        orders: [],
        isLoading: true,
        hasMore: true,
        current: 1,
        pageSize: 10,
        activeStatus: 0,
        statusTabs: [
            { key: 0, label: '全部' },
            { key: 1, label: '待处理' },
            { key: 4, label: '已完成' },
            { key: 5, label: '已取消' }
        ]
    },

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

    onShow() {
        this.fetchOrders();
    },

    async fetchOrders(append = false) {
        if (!append) {
            this.setData({ isLoading: true, current: 1, orders: [] });
        }
        try {
            const params = {
                current: this.data.current,
                pageSize: this.data.pageSize
            };
            if (this.data.activeStatus) {
                params.status = this.data.activeStatus;
            }
            const res = await request.get('/plant/exchange/orders', params);
            let list = (res && res.list) ? res.list : [];
            const total = (res && res.total) ? res.total : 0;

            // Enrich with status display info
            list = list.map(order => ({
                ...order,
                statusInfo: STATUS_MAP[order.status] || { text: '未知', theme: 'default' }
            }));

            this.setData({
                orders: append ? [...this.data.orders, ...list] : list,
                hasMore: this.data.orders.length + list.length < total
            });
        } catch (e) {
            console.error('Fetch orders failed', e);
        } finally {
            this.setData({ isLoading: false });
        }
    },

    switchStatus(e) {
        const key = e.currentTarget.dataset.key;
        if (key === this.data.activeStatus) return;
        this.setData({ activeStatus: key });
        this.fetchOrders();
    },

    onReachBottom() {
        if (!this.data.hasMore || this.data.isLoading) return;
        this.setData({ current: this.data.current + 1 });
        this.fetchOrders(true);
    }
});
