import React from 'react';
import { observer } from 'mobx-react';
import './MyPrize.less';
import { Button, Toast } from "@grace/ui";
import { _asyncThrottle, dateFormatter, miniGoUrl } from "@/utils/utils.ts";
import API from "@/api";
import { PageCtrl } from "@/core/ctrls/PageCtrl.tsx";

@observer
class MyPrize extends React.Component<any, any> {

    state = {
        list: [],
        time: 0
    }

    componentDidMount() {
        this.initList();
    }

    async initList() {
        const { success, data, timeStamp } = await API.records({
            ignoreSp: true,
        });
        if (!success) return;
        this.setState({
            list: data,
            time: timeStamp
        });
    }

    clickBack = () => {
        PageCtrl.backPage();
    }

    clickItem = async (item) => {
        const { id, url } = item
        if (url) {
            location.href = url
        } else {
            if (item.extra.refType === 'virtual') {

                // 商家自冲奖品类型配置 {"prizeId":"奖品ID","type":"类型(1-专项特惠2-积分商城奖品3-积分奖品)"}
                // 注意：旧的奖品没有type字段 需兼容
                if (item?.type == 1) {
                    return miniGoUrl(CFG.isNewMiniVersion ? "/packages/user/exclusiveOffer?source=duiba" : "/pagesNews/user/userRed")
                } else if (item?.type == 3) {
                    return miniGoUrl('/packages/user/points?source=duiba')
                }
                const res = await API.queryOrder({
                    recordId: item.id,
                    projectId: CFG.projectId
                });
                if (res?.data?.orderNo) {
                    // 线上正式用这个
                    wx.miniProgram.reLaunch({
                        url:
                            (CFG.isNewMiniVersion ? "/pages/index?source=duiba&orderNo=" : "/pages/index/index?orderNo=")
                            + id
                            + "&activityId=" + (res?.activityId) + "&uid=" + (res?.uid) + "&activityUrl=" + encodeURIComponent(location.origin + "/projectx/" + CFG.projectId + '/index.html?jumpFlag=1') + '&uid=' + res?.uid
                    })
                } else {
                    Toast.show('请稍后再试～')
                }
            } else {
                location.href = `/aaw/projectx/takePrize?projectOrderNo=${id}`
            }
        }
    }

    handleMeidaoshijian = _asyncThrottle(() => {
        Toast.show("未到补发时间")
    })

    handleShijianguole = _asyncThrottle(() => {
        Toast.show("补发已过时效")
    })

    handleKeyibufa = _asyncThrottle(async (item) => {
        await API.redpacket({
            prizeRecordId: item.id,
        });
        this.initList();
    }
    );

    render() {

        const { list } = this.state;
        const { time } = this.state;


        return <div className="MyPrize">
            <div className="MyPrizeBg" />
            <div className="MyPrizeTitle" />
            <div className="prizeList">
                {
                    list.length > 0 ? list.map((item, index) => {

                        const remainingTime = item.moneyCanReissueEndTimestamp - time;
                        const days = Math.floor(remainingTime / (24 * 60 * 60 * 1000));
                        const hours = Math.floor((remainingTime % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000));

                        let ProgressText;
                        if (days === 0 && hours === 0) {
                            ProgressText = '剩余1小时'; 
                        } else {
                            ProgressText = `剩余${days}天${hours}小时`; 
                        }

                        return (
                            <div className="prizeItem" key={index}>
                                <img className="prizeImg" src={item.extra.icon} />
                                <div className="prizeName">{item.extra.name}</div>
                                <div className="getTime">{item?.gmtCreate ? dateFormatter(item.gmtCreate, "yyyy.MM.dd") : ""}</div>

                                {item.type == 4 ? (
                                    <>
                                        {item.moneyStatus === 1 && <Button className="yifafang">已发放</Button>}
                                        {item.moneyStatus === 2 && <Button className="shibai">发放失败</Button>}
                                        {item.moneyStatus === 11 && <Button className="fafangzhong">发放中</Button>}
                                        {item.moneyStatus === 10 && (
                                            <>
                                                {/* 1. 未到可补发时 */}
                                                {item.moneyCanReissueStartTimestamp > time && (
                                                    <Button className="meidaoshijian" onClick={this.handleMeidaoshijian}>
                                                        补发红包
                                                    </Button>
                                                )}

                                                {/* 2. 已过可补发时间 */}
                                                {time > item.moneyCanReissueEndTimestamp && (
                                                    <Button className="shijianguole" onClick={this.handleShijianguole}>
                                                        补发失败
                                                    </Button>
                                                )}

                                                {/* 3. 可补发 */}
                                                {time < item.moneyCanReissueEndTimestamp &&
                                                    time > item.moneyCanReissueStartTimestamp && (
                                                        <>
                                                            <Button className="keyibufa" onClick={() => this.handleKeyibufa(item)}>
                                                                补发红包
                                                            </Button>
                                                            <span className="remian">{ProgressText}</span>
                                                        </>
                                                    )}
                                            </>
                                        )}
                                    </>
                                ) : (
                                    <Button className="use" onClick={() => this.clickItem(item)} />
                                )}
                            </div>
                        )
                        // }) : <div className="nothing"/>
                    }) : null
                }
            </div>

            <Button className="MyPrizeBack" onClick={this.clickBack} />
            <div className="ditu"></div>

        </div>;
    }
}

export default MyPrize;
