import apis from "@/apis";
import {type CreateOrderRequestData} from "@/apis/common";
import {type NavigateFunction} from "react-router-dom";

class OrderHelper {
    /**
     * 提交订单：
     *  1. 创建订单
     *  2. 查询支付地址
     *  3. 查询支付配置
     *  4. 唤起app支付
     * @param params CreateOrderRequestData
     */
    static async submitOrder(params: CreateOrderRequestData) {
        try {
            const createOrderRes = await apis.common.createOrder(params);
            if (!createOrderRes.data) {
                return;
            }

            const queryPayUrlRes = await apis.common.queryPayUrl({orderId: createOrderRes.data});
            if (!queryPayUrlRes.data) {
                return;
            }

            const tokenId = new URLSearchParams(new URL(queryPayUrlRes.data).search).get("TOKEN");

            if (!tokenId) {
                return;
            }

            const queryPayConfigRes = await apis.common.queryPayConfig<Record<"param", Record<string, string>>>();
            if (!queryPayConfigRes.data) {
                return;
            }

            const data = queryPayConfigRes.data;
            data.param.tokenId = tokenId;

            window.AlipayJSBridge.call("startApp", data, function (result: string) {
                console.log(result, "支付结果");
            });
        } catch (error) {
        }
    }


    /**
     * 获取用户的订单
     */
    static async queryUserOrder(navigate: NavigateFunction) {
        try {
            const res = await apis.common.queryUserOrder();
            if (!res.ok) {
                return;
            }

            const data = res.data;
            if (data?.lotteryOrderId) {
                navigate(`/lottery?lotteryOrderId=${data.lotteryOrderId}`, {
                    replace: true
                });
            } else if (data?.orderId) {
                navigate(`/orderDetail?orderId=${data.orderId}`, {
                    replace: true
                });
            }
        } catch (error) {
        }
    }

}

export default OrderHelper;
