// pages/common/red/red.ts
import { wxLogin } from '../../../utils/wx-api'
import { request } from '../../../utils/request'
const app = getApp<IAppOption>()
const defaultAvatarUrl =
    'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

    const formatDate = (isoString: string): string => {
        const date = new Date(isoString);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}`;
    };

const getState = (state: number) => {
    switch (state) {
        case 40:
            return '领取成功'
        case 50:
            return '红包已过期'
        default:
            return '正在发放中'
    }
}
Page({
    data: {
        list: [] as any[],
        defaultAvatarUrl: defaultAvatarUrl,
        safeBottom: app.globalData.safeBottom,
        safeTop: app.globalData.safeTop
    },

    async onLoad(options: { state: string }) {
        // const bool = await app.login('red');
        // if (!bool) return;
        try {
            const code = await wxLogin();
            let res;

            const loginRes = await request({
                options: {
                    url: '/operation/vdo-red/auth-resultV1',   //领取红包
                    method: "GET",
                    data: {
                        code: code.code,
                        state: options.state
                    }
                },
                needLogin:false
            })

            res = await request({
                options: {
                    url: '/operation/vdo-red/result',    //查询红包
                    data: {
                        openId: loginRes,
                        state: options.state
                    }
                },
                needLogin:false
            })
            const list = res.data.map((item: any) => ({
                ...item,
                date: formatDate(item.createdTime),
                stateText: getState(item.state)
            }))
            this.setData({ list })
            // res = {  //mock
            //     data: [
            //         {
            //             avatar: defaultAvatarUrl,
            //             nickname: 'x5',
            //             amount: 13343,
            //             date: '2025-11-21 09:11',
            //             state: 40
            //         }
            //     ]
            // }
        } catch (e) {
            wx.redirectTo({
                url: '/pages/error/error?msg=请求错误'
            })
            return
        }

    },
})
