import React, {useEffect, useState} from "react";
import styles from "./index.module.scss";
import {useNavigate, useSearchParams} from "react-router-dom";
import HomeBg from "@/pages/Home/components/HomeBg";
import HomeContent from "@/pages/Home/components/HomeContent";
import AuthUtil from "@/utils/auth";
import apis from "@/apis";

const Home: React.FC = () => {
    const [params] = useSearchParams();
    const navigate = useNavigate();
    const [isAuthed, setIsAuthed] = useState(false);
    const queryUserOrders = async () => {
        const [res1, res2] = await Promise.all([
            await apis.common.queryUserOrder({productCode: '4'}),
            await apis.common.queryUserOrder({productCode: '5'})
        ])
        if(res1.ok && res2.ok) {
            // 买了普通产品
            if(res1.data.orderId) {
                navigate(`/orderDetail?orderId=${res1.data.orderId}`,{replace: true})
            }

            // 买了抽奖，但是没抽 或者 抽过了
            if(res2.data.orderId || res2.data.lotteryOrderId) {
                navigate(`/lottery`,{replace: true})
            }
        }
    }

    const authenticateAndFetchOrders = async () => {
        try {
            const authResult = await AuthUtil.auth(params);
            await queryUserOrders()
            setIsAuthed(authResult);
        } catch (error) {
        }
    };

    useEffect(() => {
        setTimeout(authenticateAndFetchOrders, 400);
    }, []);

    return (
        <div className={styles.wrap}>
            {isAuthed && (
                <>
                    <HomeBg/>
                    <HomeContent queryUserOrders={queryUserOrders}/>
                </>
            )}
        </div>
    );
};

export default Home;
