import { useModel } from "umi";
import { setCookie } from "@/utils/cry";
import { Modal, Image, message } from "antd";
import React, { useCallback, useEffect, useState } from "react";

/**
 * 登录过期重新登录
 */

type Props = {
    data?: { base64: string, code: string }
    show?: boolean,
    onClose?: () => void,
    onChange?: () => void
}
let timer: NodeJS.Timeout
function AuthLogin(props: Props) {
    let { show = false, onClose, data, onChange } = props
    const { loginResult } = useModel('useLaunch.useAdAuthorize')
    const userId = useModel('@@initialState', model => model.initialState?.currentUser?.userId as string)
    const [count, setCount] = useState<number>(45)

    useEffect(() => {
        if (JSON.stringify(data) !== '{}') {
            if (data?.code) {
                timer = setInterval(() => {
                    setCount(() => count - 1)
                    if (count <= 0) {
                        timer && clearInterval(timer)
                        onClose && onClose()
                    }
                    loginResult.run(data?.code).then((res: any) => {
                        if (res?.data) {
                            message.success('扫码成功')
                            setCookie(userId, 'true', 10)
                            timer && clearInterval(timer)
                            onChange && onChange()
                            console.log('已授权2', res)
                            setCookie('mpLogin'+userId, 'true', 1)
                        }
                    })
                }, 1000)
            }
        } else {
            onClose && onClose()
        }
        return () => {
            timer && clearInterval(timer)
        }
    }, [data, count])

    const close = useCallback(() => {
        onClose && onClose()
    }, [])

    return <Modal
        title='授权登录'
        visible={show}
        footer={null}
        onCancel={close}
        maskClosable
        closable={false}
        width={380}
    >
        <Image width="100%" src={data?.base64} preview={false} />
        <div style={{ fontSize: 12, marginTop: 10, textAlign: 'center' }}>{count}s将关闭扫码弹窗，请尽快扫码确认</div>
    </Modal>
}

export default React.memo(AuthLogin)