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 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 [showMyPrizePopup, setShowMyPrizePopup] = useState(false);

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

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

    const [branchName, setBranchName] = useState('');

    const [branchCode, setBranchCode] = useState('');

    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: branchCode || "",
            branchName: 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);
        }
    }

    async function getOrderInfo() {
        const res1 = await apis.common.queryUserOrder({productCode: '5'})
        if(!res1.ok) return
        const res2 = await apis.common.queryOrderInfo(res1.data.orderId)
        if(!res2.ok) return
        setBranchName(res2.data.orderDetail.branchName)
        setBranchCode(res2.data.orderDetail.branchCode)
    }


    useEffect(() => {
        document.title = "抽奖活动";
        getOrderInfo().then(() => {})
        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> 活动时间：2024/1/1—2024/3/31
                </div>
                <div className={styles.lotteryRuleItem}><span></span> 活动对象：闸北掌银注册客户。欢迎掌银新客，数币新客，信用卡新客，或财富
                    贵宾等客户积极参与。</div>
                <div className={styles.lotteryRuleItem}><span></span>活动规则：使用农行掌银扫活动二维码进入页面，活动礼品分为实物礼品和线上
                    礼券两类，活动期间内每人限参与其中1类，每类限参与1次，客户支付1元即表示参
                    与活动，参与成功后1元将原路退回。实物礼品以网点现场礼品为准，线上礼券为微
                    信立减金抽奖，立减金面额有2.22元、5.55元、8.88元、10元、58.88元，线上礼券
                    每月限量，每月1号刷新库存，当月礼券抽完活动即止。</div>
                <div className={styles.lotteryRuleItem}><span></span>重要提示：微信立减金兑换有效期为当月月底前，使用有效期为自兑换之日起7天内
                    （含兑换当日），过期不予补发。</div>
                <div className={styles.lotteryRuleItem}><span></span>凡参与本活动的客户，即视为同意接受本活动相关规则，活动期间用户不得使用
                    不正当手段以及其他破坏活动规则、违背活动公平原则的方式参加本次活动，否则
                    活动方有权取消用户参与资格，收回已经领取的权益。</div>
                <div className={styles.lotteryRuleItem}><span></span>本次活动页面服务由“艾普金服（北京）科技有限公司上海分公司”提供，如有活动
                    相关问题请咨询客服热线010-57256207（周一至周日8:00-16:00）。</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;
