import React, {useEffect, useState} from "react";
import lotteryWrapBgImg from "@/assets/images/lotteryWrapBg.png";
import lotteryPrizeImg from "@/assets/images/lotteryPrize.png";
import lotteryButtonBgImg from "@/assets/images/lotteryButtonBg.png";
import lotteryRuleTitleBgImg from "@/assets/images/lotteryRuleTitleBg.png";
import lotteryMyPrizeEmptyImg from "@/assets/images/myPrizeEmpty.png";
import styles from "./index.module.scss";
import MyPrizeItem from "@/pages/Lottery/components/MyPrizeItem";
import {Popup, Overlay} from "@nutui/nutui-react";
import {type SubmitDrawResponse, type QueryMyPrizeListResponse} from "@/apis/common";
import {Toast} from "@nutui/nutui-react";
import {useSearchParams} from "react-router-dom";
import apis from "@/apis";

const LOTTERY_ACTIVE_CODE = "100001";

interface LotteryConfig {
    prizeCount: number;
    drawCount: number;
    drawIndex: number;
    rotating: number;
    round: number;
    duration: number;
    running: boolean;
}

const Lottery: React.FC = () => {
    const [params] = useSearchParams();

    const [showMyPrizePopup, setShowMyPrizePopup] = useState(false);

    const [visible, setVisible] = useState(false);

    const [lotteryDrawInfo, setLotteryDrawInfo] = useState<SubmitDrawResponse>();

    let isLotteryed = false;

    const [lotteryConfig, setLotteryConfig] = useState<LotteryConfig>({
        prizeCount: 5, // 商品个数 - 服务端获取商品数量
        drawCount: 1, // 第几次抽奖 - 从第一次开始
        drawIndex: 0, // 中奖索引 - 顺时针排序 - 服务端获取获奖索引
        rotating: 0, // 动画旋转角度
        round: 5, // 旋转圈数
        duration: 3000, // 动画持续时间
        running: false // 锁定抽奖状态
    });

    const [lotteryStyle, setLotteryStyle] = useState({
        transform: "",
        transition: "",
        WebkitTransform: "",
        WebkitTransition: ""
    });

    const [myPrizeList, setMyPrizeList] = useState<QueryMyPrizeListResponse[]>([]);

    /**
     * 设置转盘的running状态
     * @param running
     */
    function setLotteryRunningStatus(running: boolean) {
        setLotteryConfig(prev => ({...prev, running: running}));
    }

    /**
     * 点击抽奖
     */
    async function onClickLotteryButton() {
        if (lotteryConfig.running) return;
        setLotteryRunningStatus(true);
        const res = await apis.common.submitDraw({
            activityCode: LOTTERY_ACTIVE_CODE,
            branchCode: params.get("branchCode") || "",
            branchName: params.get("branchName") || ""
        });
        if (res.ok) {
            isLotteryed = true;
            setLotteryDrawInfo(res.data);
            setLotteryConfig(prev => {
                const drawCount = prev.drawCount + 1;
                const drawIndex = res.data.showOrder - 1;
                history.pushState(null, "", document.URL);
                const rotating = prev.round * 360 * prev.drawCount - (drawIndex + 1) * (360 / prev.prizeCount) + 35;
                const newConfig = {
                    ...prev,
                    drawIndex,
                    drawCount,
                    rotating,
                } as LotteryConfig;

                // 更新旋转样式
                setLotteryStyle({
                    transform: `rotate(${newConfig.rotating}deg)`,
                    transition: `transform ${newConfig.duration}ms ease-in-out`,
                    WebkitTransform: `rotate(${newConfig.rotating}deg)`,
                    WebkitTransition: `transform ${newConfig.duration}ms ease-in-out`
                });

                // 在动画结束后解锁
                setTimeout(() => {
                    setLotteryRunningStatus(false);
                    setVisible(true);
                }, newConfig.duration);
                return newConfig;
            });
        } else {
            Toast.show(res.msg);
            setLotteryRunningStatus(false);
        }
    }


    /**
     * 点击我的奖品
     */
    async function onClickLotteryMyPrizeButton() {
        setShowMyPrizePopup(true);
        const res = await apis.common.queryMyPrizeList({
            pageNum: 1,
            pageSize: 10000,
            activityCode: LOTTERY_ACTIVE_CODE
        });
        if (res.ok) {
            setMyPrizeList(res.data.records);
        }
    }

    /**
     * 领奖
     * @param orderId
     */
    async function onReceivePrize(orderId: string | undefined) {
        if (!orderId) return;
        setVisible(false);
        setShowMyPrizePopup(false);
        const res = await apis.common.receivePrize({orderId});
        if (res.ok) {
            window.AlipayJSBridge.call("abcShare", res.data);
        }
    }


    useEffect(() => {
        const handleBackButtonEvent = (e: PopStateEvent) => {
            e.preventDefault();

            if (isLotteryed) {
                history.pushState(null, "", document.URL);
                window.AlipayJSBridge.call("abcExitWebAndBackToHome");
            }
        };

        window.addEventListener("popstate", handleBackButtonEvent);

        return () => {
            window.removeEventListener("popstate", handleBackButtonEvent);
        };
    }, []);

    return (
        <div className={styles.wrap}>
            <div className={styles.lotteryWrap}>
                <img className={styles.lotteryWrapBgImg} src={lotteryWrapBgImg} alt=""/>
                <img style={lotteryStyle} className={styles.lotteryPrizeBgImg} src={lotteryPrizeImg} alt=""/>
                <img className={styles.lotteryButtonBgImg} onClick={onClickLotteryButton} src={lotteryButtonBgImg}
                     alt=""/>
                <div className={styles.lotteryMyPrizeButton} onClick={onClickLotteryMyPrizeButton}>我的奖品</div>
            </div>
            <img className={styles.lotteryRuleTitleBg} src={lotteryRuleTitleBgImg} alt=""/>
            <div className={styles.lotteryRuleContent}>
                <div className={styles.lotteryRuleItem}><span></span> 该活动仅供掌银新客选择（线下礼品、线上微信立减金抽奖二选一），
                </div>
                <div className={styles.lotteryRuleItem}><span></span> 每季度每个客户号仅可参与其中一项。</div>
            </div>

            {/*我的奖品*/}
            <Popup
                closeable
                visible={showMyPrizePopup}
                style={{height: "454px"}}
                position="bottom"
                round
                onClose={() => {
                    setShowMyPrizePopup(false);
                }}
            >
                <div className={styles.myPrizePopupWrap}>
                    <div className={styles.myPrizePopupTitle}>我的奖品</div>
                    {myPrizeList.length > 0 && <div className={styles.myPrizePopupContent}>
                        {myPrizeList.map((item, index) => {
                            return (
                                <MyPrizeItem item={item} key={index} onReceivePrize={onReceivePrize}/>
                            );
                        })}
                    </div>}
                    {myPrizeList.length <= 0 && <div className={styles.myPrizePopupEmpty}>
                        <img src={lotteryMyPrizeEmptyImg} alt=""/>
                        <p>您还未抽奖，快去参加抽奖吧~</p>
                    </div>}
                </div>
            </Popup>
            {/*我的奖品*/}


            {/*中奖弹窗*/}
            <Overlay visible={visible} closeOnOverlayClick={false}>
                <div className={styles.winningLotteryWrap}>
                    <div className={styles.winningLotteryInner}>
                        <div className={styles.winningLotteryTitle}>您获得 <span>{lotteryDrawInfo?.prizeName}</span>
                        </div>
                        <img src={lotteryDrawInfo?.iconUrl} alt=""/>
                        <div
                            className={styles.winningLotteryTime}>请于{lotteryDrawInfo?.receiveDeadlineTime}前完成领取
                        </div>
                        <div className={styles.winningLotteryClose} onClick={() => setVisible(false)}></div>
                        <div className={styles.winningLotteryConfirm}
                             onClick={() => onReceivePrize(lotteryDrawInfo?.orderId)}></div>
                    </div>
                </div>
            </Overlay>
            {/*中奖弹窗*/}
        </div>
    );
};
export default Lottery;
