const api = require('../../../utils/api')
const util = require('../../../utils/util')

Page({
    data: {
        userInfo: null,
        list: [],
        page: 1,
        pageSize: 20,
        hasMore: true,
        loading: false
    },

    onLoad(options) {
        if (options.userInfo) {
            try {
                const userInfo = JSON.parse(decodeURIComponent(options.userInfo))
                this.setData({ userInfo })
                wx.setNavigationBarTitle({
                    title: `${userInfo.name}的订单`
                })
            } catch (e) {
                console.error('解析用户信息失败', e)
            }
        }

        this.loadOrders()
    },

    onPullDownRefresh() {
        this.setData({
            page: 1,
            hasMore: true,
            list: []
        }, () => {
            this.loadOrders().then(() => {
                wx.stopPullDownRefresh()
            })
        })
    },

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

    async loadOrders() {
        if (this.data.loading) return

        this.setData({ loading: true })

        try {
            const res = await api.commission.getRecords({
                page: this.data.page,
                pageSize: this.data.pageSize,
                fromUserId: this.data.userInfo?.userId
            })

            if (res.success) {
                const newList = res.data.list.map(item => ({
                    ...item,
                    orderTypeText: this.getOrderTypeText(item.orderType),
                    statusText: this.getStatusText(item.status),
                    statusClass: item.status,
                    createdAtFormatted: util.formatTime(new Date(item.createdAt))
                }))

                this.setData({
                    list: this.data.page === 1 ? newList : [...this.data.list, ...newList],
                    hasMore: newList.length === this.data.pageSize
                })
            }
        } catch (err) {
            console.error('加载订单失败', err)
            wx.showToast({
                title: '加载失败',
                icon: 'none'
            })
        } finally {
            this.setData({ loading: false })
        }
    },

    getOrderTypeText(type) {
        const map = {
            'recharge': '充值',
            'vip': 'VIP会员',
            'identity_card': '身份卡',
            'agent_purchase': '智能体购买',
            'companion_chat': '陪聊'
        }
        return map[type] || type
    },

    getStatusText(status) {
        const map = {
            'pending': '待结算',
            'settled': '已结算',
            'cancelled': '已取消'
        }
        return map[status] || status
    }
})
