import { setCookie } from "@/utils/cry"
import { Button, Form, Input, Menu, Modal, Image, Spin, message } from "antd"
import React, { useCallback, useState } from "react"
import { useEffect } from "react"
import { useModel } from "umi"
import style from './index.less'

type Props = {
    show?: boolean,
    onClose?: () => void,
    onChange?: () => void,
    isUpdataAcc?: boolean,  /** 是否是更新账户 */
}
export default function Warrant(props: Props) {
    let { show = false, onClose, onChange, isUpdataAcc = false } = props
    const [current, setCurrent] = useState<string>('wx')  // 菜单选中key
    const { loginAd, loginResult, uploadLoginAd } = useModel('useLaunch.useAdAuthorize')
    const userId = useModel('@@initialState',model=>model.initialState?.currentUser?.userId as string)
    const [code, setCode] = useState<string>('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMIAAADDCAYAAADQvc6UAAABRWlDQ1BJQ0MgUHJvZmlsZQAAKJFjYGASSSwoyGFhYGDIzSspCnJ3UoiIjFJgf8LAwSDCIMogwMCcmFxc4BgQ4ANUwgCjUcG3awyMIPqyLsis7PPOq3QdDFcvjV3jOD1boQVTPQrgSkktTgbSf4A4LbmgqISBgTEFyFYuLykAsTuAbJEioKOA7DkgdjqEvQHEToKwj4DVhAQ5A9k3gGyB5IxEoBmML4BsnSQk8XQkNtReEOBxcfXxUQg1Mjc0dyHgXNJBSWpFCYh2zi+oLMpMzyhRcASGUqqCZ16yno6CkYGRAQMDKMwhqj/fAIcloxgHQqxAjIHBEugw5sUIsSQpBobtQPdLciLEVJYzMPBHMDBsayhILEqEO4DxG0txmrERhM29nYGBddr//5/DGRjYNRkY/l7////39v///y4Dmn+LgeHANwDrkl1AuO+pmgAAADhlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAqACAAQAAAABAAAAwqADAAQAAAABAAAAwwAAAAD9b/HnAAAHlklEQVR4Ae3dP3PTWBSGcbGzM6GCKqlIBRV0dHRJFarQ0eUT8LH4BnRU0NHR0UEFVdIlFRV7TzRksomPY8uykTk/zewQfKw/9znv4yvJynLv4uLiV2dBoDiBf4qP3/ARuC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qFCBChULMNNSdAhJyNSiECRCjUbEPNCRAhZ6NSiAARCjXbUHMCRMjZqBQiQIRCzTbUnAARcjYqhQgQoVCzDTUnQIScjUohAkQo1GxDzQkQIWejUogAEQo121BzAkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiEC/wGgKKC4YMA4TAAAAABJRU5ErkJggg==') // 二维
    const [timer, setTimer] = useState<NodeJS.Timeout>()

    const [isSwitch, setIsSwitch] = useState<boolean>(true) // 是否可切换

    useEffect(() => {
        if (show) {
            if (current !== 'account') {
                timer && clearInterval(timer)
                if (isUpdataAcc) { // 更新账户密码
                    setCurrent('account')
                    // uploadLoginAd.run({scanCode: current}).then((res: any) => {
                    //     result(res?.data?.code)
                    // })
                } else {  // 首次授权
                    loginAd.run({ scanCode: current }).then((res: any) => {
                        result(res?.data?.code)
                        setCode(res?.data?.base64)
                    })
                }
                setIsSwitch(false)
                setTimeout(() => {
                    setIsSwitch(() => true)
                }, 5000)
            }
        }
    }, [show, current, isUpdataAcc])

    const result = (code: string) => {
        let timer: NodeJS.Timeout
        if (code) {
            timer = setInterval(() => {
                loginResult.run(code).then((res: any) => {
                    if (res?.data) {
                        message.success('扫码成功')
                        setCookie(userId, 'true', 10)
                        clearInterval(timer)
                        onClose && onClose()
                    }
                })
            }, 1000)
            timer && setTimer(timer)
        }
    }

    useEffect(() => {
        return () => {
            timer && clearInterval(timer)
        }
    }, [timer])

    /** 选择菜单 */
    const selectMenu = useCallback((e: any) => {
        if (isSwitch) {
            setCurrent(e?.key)
            setIsSwitch(false)
            setTimeout(() => {
                setIsSwitch(() => true)
            }, 5000)
        } else {
            message.error('等5秒后可切换！')
        }
    }, [current, isSwitch])

    /** 账户密码提交 */
    const submitForm = useCallback((values: any) => {
        if (isUpdataAcc) {
            uploadLoginAd.run({ ...values }).then((res: any) => {
                if (res?.data) {
                    message.success('更新成功')
                    onClose && onClose()
                }
            })
        } else {
            loginAd.run({ ...values }).then((res: any) => {
                if (res?.data) {
                    message.success('登录成功')
                    onClose && onClose()
                }
            })
        }
    }, [isUpdataAcc, loginAd, uploadLoginAd])
    return <Modal visible={show} title={isUpdataAcc ? '更新账号密码' : null} onCancel={() => { onClose && onClose() }} footer={null} maskClosable closable={false} width={500}>
        <Menu onClick={selectMenu} selectedKeys={[current]} mode="horizontal" style={{ marginBottom: 20, display: 'flex', justifyContent: 'center' }}>

            {!isUpdataAcc && <Menu.Item key="wx">
                微信扫码登录
            </Menu.Item>}
            <Menu.Item key="qq">
                QQ扫码登录
            </Menu.Item>
            <Menu.Item key="account">
                账户密码{isUpdataAcc ? '更新' : '登录'}
            </Menu.Item>
        </Menu>
        <div className={style.form}>
            {current === 'wx' || current === 'qq' ? <Spin spinning={loginAd?.loading}><Image width="100%" src={code} preview={false} /></Spin>
                : current === 'account' ? <Spin spinning={loginAd?.loading}>
                    <div className={style.account}>
                        <Form
                            layout="vertical"
                            onFinish={submitForm}
                        >
                            <Form.Item label="账号" name="user" rules={[{ required: true, message: '请输入账号' }]}>
                                <Input placeholder="请输入账号" autoComplete="new-password" />
                            </Form.Item>
                            <Form.Item label="密码" name="password" rules={[{ required: true, message: '请输入密码' }]}>
                                <Input.Password placeholder="请输入密码" autoComplete="new-password" />
                            </Form.Item>
                            <Form.Item className={style.submit}>
                                <Button type="primary" htmlType="submit" loading={uploadLoginAd?.loading || loginAd?.loading}>授权</Button>
                            </Form.Item>
                        </Form>
                    </div>
                </Spin> : null}
        </div>
    </Modal>
}