import { App, Empty } from "antd"
import React, { useContext, useEffect, useState } from "react"
import { getGameId, getToken, removeToken } from "../../utils/auth"
import AuthPop from "../authPop"
import BindPhone from "../bindPhone"
import FloatingWindow from "../../components/floatingWindow"
import { DispatchContext } from "../../App"
import UserManage from "./userManage"
import Modify from "../modify"
import { useAjax } from "../../hooks/useAjax"
import { gameRoleEscalationApi, getJsApiPayInfoApi, payPostResultApi, userLogoutApi } from "../../api"
import PayPop from "../payPop"
import { isOs, isWx } from "../../utils"
import WxpcQrCode from "../payPop/wxpcQrCode"
import LoadingPop from "../../components/loadingPop"
import showMessage from "../../components/showMessage"
import showModal from "../../components/showModal"

/**
 * 登录成功
 * @param param0 
 * @returns 
 */
const LoginSucc: React.FC = () => {

    /*************************************/
    const { dispatch, state: { initData: { h5GameUrl, h5SignShow }, userData, isBind, isAuth, orientation }, getDetails } = useContext(DispatchContext)!;
    const { userId, authentication, checkSwitch, bindPhone } = userData
    const [open, setOpen] = useState<boolean>(false)
    const [openPhone, setOpenPhone] = useState<boolean>(false)
    const [openAuth, setOpenAuth] = useState<boolean>(false)
    const [openModify, setOpenModify] = useState<boolean>(false)
    const [payConfig, setPayConfig] = useState<{ open: boolean, data: any }>({ open: false, data: {} })
    const [isClick, setIsClick] = useState<boolean>(false)
    const [timerInfo, setTimerInfo] = useState<any>({})
    const { message, modal } = App.useApp()
    const [htmlpay, setHtmlPay] = useState<string>('')
    const [wxPayInfo, setWxPayInfo] = useState<{ qrcode: string, amount: string, open: boolean, orderId: string }>({ qrcode: '', amount: '0.00', open: false, orderId: '' })
    const [isLoading, setIsLoading] = useState<boolean>(false)
    const [isVer, setIsVer] = useState<boolean>(false)

    const gameRoleEscalation = useAjax((params) => gameRoleEscalationApi(params))
    const payPostResult = useAjax((params) => payPostResultApi(params))
    const getJsApiPayInfo = useAjax((params) => getJsApiPayInfoApi(params))
    const userLogout = useAjax(() => userLogoutApi())
    /*************************************/

    useEffect(() => {
        let os = isOs()
        if (['ios', 'android'].includes(os) && orientation === 'VERTICAL') {
            setIsVer(true)
        } else {
            setIsVer(false)
        }
    }, [orientation])

    // 上报
    const escalation = (data: any) => {
        gameRoleEscalation.run(data).then(res => {
            if (+res.code === 200) {
                console.log('上报成功')
            } else {
                showMessage.error(res.msg || '上报失败', message)
            }
        })
    }

    // 登出
    const loginOut = () => {
        userLogout.run().then(res => {
            if (+res.code === 200) {
                removeToken();
                window.location.reload()
            } else {
                showMessage.error(res.msg, message)
            }
        })
    }

    useEffect(() => {
        const handleMessage = (event: MessageEvent) => {
            // 处理收到的消息
            let data = event.data
            switch (data.type) {
                case 'member.init':
                    (window.frames as any).gameFrame.postMessage({
                        type: "callback.init",
                        value: userData
                    }, "*")
                    break
                case 'member.tips'://弹窗提示
                    showModal.info({
                        title: '提示信息',
                        content: data.data,
                        modal
                    })
                    break
                case 'member.pay'://支付
                    setPayConfig({ open: true, data: data.data })
                    break
                case 'member.uprole': // 上报
                    escalation(data.data)
                    break
                case 'member.logout': // 登出
                    loginOut()
                    break
            }
        };
        window.addEventListener('message', handleMessage);
        return () => {
            window.removeEventListener('message', handleMessage);
        };
    }, [userData])

    useEffect(() => {
        if (authentication === 0 && !isAuth) {
            setOpenAuth(true)
            setIsClick(false)
        } else {
            // 是否首次进入弹绑定手机
            // if (bindPhone === 0 && !isBind) {
            //     setOpenPhone(true)
            // }
        }
    }, [bindPhone, authentication, isBind, isAuth])

    const setIsBind = () => {
        if (!isBind) {
            dispatch({ type: 'setIsBind', params: { isBind: true } })
        }
    }

    const setIsAuth = () => {
        if (!isAuth) {
            dispatch({ type: 'setIsAuth', params: { isAuth: true } })
        }
    }

    const handle = (type: 'BIND' | 'AUTH' | 'MODIFY' | 'LOGOUT') => {
        switch (type) {
            case 'AUTH':
                setIsClick(true)
                setOpenAuth(true)
                break
            case 'BIND':
                setOpenPhone(true)
                break
            case 'MODIFY':
                setOpenModify(true)
                break
            case 'LOGOUT':
                loginOut()
                break
        }
    }

    /**
     * 预下单成功
     * @param data 
     * @param payWay 
     */
    const preOrderSucc = (data: any, payWay: string, payInfo: any) => {
        setIsLoading(true)
        let orderId = data.orderId
        let os = isOs()
        payResult(orderId)
        if (os === 'windows' || os === 'mac') { // pc
            setIsLoading(false)
            if (payWay === '1') { // 支付宝
                document.querySelector('[name="punchout_form"]')?.remove();
                setHtmlPay(data.data.replace('<script>document.forms[0].submit();</script>'))
                setTimeout(() => {
                    document.querySelector('[name="punchout_form"]')?.setAttribute("target", "__blank");
                    (document.querySelector('[name="punchout_form"]') as any).submit();
                }, 100)
            } else { // 微信
                setWxPayInfo({ open: true, qrcode: data.data, orderId: data.orderId, amount: payInfo.amount })
            }
        } else if (isWx()) { // 微信jsApi支付
            setPayConfig({ open: false, data: {} })
            weChatPay(data.openId, data.orderId)
        } else {  // 
            setTimeout(() => { setIsLoading(false) }, 2000)
            setPayConfig({ open: false, data: {} })
            window.location.href = data.data
        }
    }

    // JSAPI支付
    const onBridgeReady = (payParam: any) => {
        if (payParam) {
            let { package: pack, nonceStr, paySign, signType, timeStamp, appId } = JSON.parse(payParam)
            // @ts-ignore
            WeixinJSBridge.invoke('getBrandWCPayRequest', {
                "appId": appId,                                   //公众号ID，由商户传入     -
                "timeStamp": timeStamp,                           //时间戳，自1970年以来的秒数     
                "nonceStr": nonceStr,                             //随机串    
                // @ts-ignore
                "package": `prepay_id=${pack.prepay_id}`,
                "signType": signType,                             //微信签名方式：     
                "paySign": paySign                                //微信签名 
            }, (res: any) => {
                if (res.err_msg == "get_brand_wcpay_request:ok") {
                    showModal.success({
                        title: '支付结果',
                        content: '支付成功',
                        modal
                    })
                } else if (res.err_msg == "get_brand_wcpay_request:fail") {
                    showModal.error({ title: '提示信息', content: '该订单已失效，请回复“2”或游戏内重新下单获取最新支付订单', modal });
                }
            });
        } else {
            showModal.error({ title: '提示信息', content: '订单异常，请联系客服重新下单', modal });
        }
    }

    // 客服支付
    const weChatPay = (openId: string, orderId: string) => {
        getJsApiPayInfo.run({ openId, orderId }).then(res => {
            setIsLoading(false)
            if (+res.code === 200 && res.data) {
                let { payParam } = res.data
                // @ts-ignore
                if (typeof WeixinJSBridge == "undefined") {
                    if (document.addEventListener) {
                        document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
                    } else if ((document as any).attachEvent) {
                        (document as any).attachEvent('WeixinJSBridgeReady', onBridgeReady);
                        (document as any).attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                    }
                } else {
                    onBridgeReady(payParam)
                }
            } else {
                showMessage.error(res.msg || '该订单已失效，请回复“2”或游戏内重新下单获取最新支付订单', message)
            }
        })
    }

    // 支付回调结果
    const payResult = (orderId: string) => {
        payPostResult.run({ orderId }).then(res => {
            if (+res.code === 200) {
                if (res.data) {
                    setPayConfig({ open: false, data: {} })
                    setWxPayInfo({ qrcode: '', amount: '0.00', open: false, orderId: '' })
                    showModal.success({
                        title: '支付结果',
                        content: '支付成功',
                        modal
                    });
                } else {
                    let newtimerInfo = timerInfo
                    if (newtimerInfo?.[orderId]) {
                        newtimerInfo[orderId] += 1
                    } else {
                        newtimerInfo[orderId] = 1
                    }
                    if (newtimerInfo?.[orderId] && newtimerInfo[orderId] < 200) { // 5分钟关闭
                        setTimeout(() => {
                            payResult(orderId)
                        }, 1500)
                    } else {
                        delete newtimerInfo[orderId]
                    }
                    setTimerInfo(newtimerInfo)
                }
            } else {
                showModal.error({ title: '支付结果', content: res.msg, modal });
            }
        })
    }


    if (h5GameUrl) {

        let gameUrl = h5GameUrl
        if (gameUrl?.indexOf('?') !== -1) {
            gameUrl = gameUrl + '&game_id=' + getGameId() + '&user_id=' + userId + '&token=' + getToken()
        } else {
            gameUrl = gameUrl + '?game_id=' + getGameId() + '&user_id=' + userId + '&token=' + getToken()
        }

        return <>
            {isLoading && <LoadingPop />}
            <iframe id="gameFrame" name="gameFrame" className='fullscreen' src={gameUrl}></iframe>
            {/* 抽屉侧边窗 */}
            {open && <UserManage isVer={isVer} open={open} onClose={() => setOpen(false)} handle={handle} />}
            {/* 实名认证 */}
            {openAuth && <AuthPop open={openAuth} isClick={isClick} onClose={() => { setOpenAuth(false); setIsAuth() }} checkSwitch={checkSwitch} onChange={() => { getDetails(); setIsAuth() }} />}
            {/* 绑定手机 */}
            {openPhone && <BindPhone onChange={() => { getDetails(); setIsBind() }} open={openPhone} onClose={() => { setOpenPhone(false); setIsBind() }} />}
            {/* 修改密码 */}
            {openModify && <Modify open={openModify} onClose={() => setOpenModify(false)} onChange={() => { getDetails(); setOpenModify(false) }} />}
            {/* 悬浮球 */}
            {h5SignShow !== 'SIGN_SHOW_NONE' && <>
                {(h5SignShow === 'SIGN_SHOW_ALL' || ((h5SignShow === 'SIGN_SHOW_WX_NONE' && !isWx()) || (isOs() === 'windows' || isOs() === 'mac')) || (h5SignShow === 'SIGN_SHOW_H5_NONE' && (isOs() === 'windows' || isOs() === 'mac'))) && <FloatingWindow isVer={isVer}  onClick={() => setOpen(true)} />}
            </>}
            {/* 支付选择组件 */}
            {payConfig.open && <PayPop isVer={isVer} {...payConfig} onClose={() => setPayConfig({ open: false, data: {} })} onChange={preOrderSucc} />}
            {/* 微信PC二维码弹窗 */}
            {wxPayInfo.open && <WxpcQrCode open={wxPayInfo.open} data={{ ...wxPayInfo }} onClose={() => setWxPayInfo({ qrcode: '', amount: '0.00', open: false, orderId: '' })} />}
            <div dangerouslySetInnerHTML={{ __html: htmlpay }}></div>
        </>
    } else {
        return <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="请先配置H5游戏地址" />
    }
}

export default React.memo(LoginSucc)