import Taro from "@tarojs/taro";
import { getUserInfo } from "./login";
import { getRechargeTemplate } from "../index/index";
import { requestPayment, showToast } from '@src/utils/compatibility';

type PublicData = {
    bookId: number,//小说ID
    bookParagraphId: number,//章节ID
    orderCondition: string,//支付场景
}
/**现金购买-预下单*/
export function cashBuy(data: PublicData, callbackFn?: (b: boolean) => void) {
    return new Promise(async (resolve, reject) => {
        try {
            // 初始化
            Taro.request({
                url: '/app/pay/buyout',
                method: 'POST',
                data,
                success: async (res) => {
                    let r = await whcatPay(res.data?.data?.wechatMchPayInfo, res.data?.data?.orderNo)
                    console.log("支付操作完成！！", r)
                    callbackFn?.(true)
                    resolve(r)
                },
                fail: (err) => {
                    reject(err);
                }
            })
        } catch (error) {
            reject(error);
        }
    })
}
/**书币购买*/
export function virtualBuy(data: PublicData, callbackFn?: (b: boolean) => void) {
    return new Promise(async (resolve, reject) => {
        try {
            // 初始化
            Taro.request({
                url: '/app/pay/buyChapterOfCoin',
                method: 'POST',
                data,
                success: async (res) => {
                    await getUserInfo()//刷新个人信息
                    callbackFn?.(true)
                    resolve(res)
                },
                fail: (err) => {
                    reject(err);
                }
            })
        } catch (error) {
            reject(error);
        }
    })
}
interface Data extends PublicData {
    rechargeTemplateId: number,//支付模板ID
    templateIndex: number,//下标
}
/**模板购买-预下单*/
export function templateBuy(data: Data, callbackFn?: (b: boolean) => void) {
    return new Promise(async (resolve, reject) => {
        try {
            // 初始化
            Taro.request({
                url: '/app/pay/buyOfTemplate',
                method: 'POST',
                data,
                success: async (res) => {
                    let r = await whcatPay(res.data?.data?.wechatMchPayInfo, res.data?.data?.orderNo)
                    console.log("支付操作完成！！", r)
                    await getUserInfo()//刷新个人信息
                    await getRechargeTemplate()//刷新模板
                    callbackFn?.(true)
                    resolve(r)
                },
                fail: (err) => {
                    reject(err);
                }
            })
        } catch (error) {
            reject(error);
        }
    })
}

/**微信支付*/
type WhcatPay = {
    timeStamp: string,//时间戳，从 1970 年 1 月 1 日 00:00:00 至今的秒数，即当前的时间
    nonceStr: string,//随机字符串，长度为32个字符以下
    package: string,//统一下单接口返回的 prepay_id 参数值，提交格式如：prepay_id=***
    signType: any,//签名算法
    paySign: string,//签名
}
export function whcatPay(params: WhcatPay, orderNo: string) {
    console.log("微信支付:", params, { orderNo })
    let time: any = null
    let num = 0
    return new Promise(async (resolve, reject) => {
        try {
            // 初始化
            requestPayment({
                ...params,
                success: (res) => {
                    console.log("支付成功:", res)
                    showToast({
                        title: '支付成功！',
                        icon: 'success'
                    });
                    if (time) {
                        clearInterval(time)
                    }
                    time = setInterval(async () => {
                        let data: any = await queryOrder(orderNo)
                        if (data && data?.orderStatus === 2) {
                            resolve(true)
                            clearInterval(time)
                            num = 0
                        }
                        num += 1
                        if (num > 10) {
                            resolve(true)
                            clearInterval(time)
                            num = 0
                        }
                    }, 1000)
                },
                fail: (err) => {
                    console.log("支付失败:", err)
                    if (err.errMsg === 'requestPayment:fail cancel') {
                        showToast({
                            title: '支付已取消！',
                            icon: 'error'
                        });
                    } else {
                        showToast({
                            title: '支付失败，请重试！',
                            icon: 'error'
                        });
                    }
                    resolve(false)
                }
            })
        } catch (error) {
            reject(error);
        }
    })
}
/**查询订单结果*/
export function queryOrder(orderNo) {
    return new Promise(async (resolve, reject) => {
        try {
            // 初始化
            Taro.request({
                url: `/app/pay/orderInfo/${orderNo}`,
                method: 'GET',
                success: (res) => {
                    resolve(res.data?.data)
                },
                fail: (err) => {
                    reject(err);
                }
            })
        } catch (error) {
            reject(error);
        }
    })
}