import { useCallback, useState } from "react"
import React from 'react'
import { Col, Row, Radio, Input, Button, message, Space, Image, Modal, Popconfirm } from "antd";
let name = {
    0: '小说账号失败列表：',
    1: '游戏账号失败列表：',
}
var time: any = null
let api = "http://47.99.157.216:8023"
// let api = "http://127.0.0.1:8023"
function QQAuth(props: { qqVisible: boolean, callBack: () => void, adAppType: 0 | 1, title: string, smType?: "QQ" | "WX", isOld?: boolean }) {
    const { qqVisible, callBack, adAppType, smType, title, isOld } = props
    let [visible, setVisible] = useState(false)
    let [loading, setLoading] = useState(false)
    let [codeUrl, setCodeUrl] = useState('')
    let [err, setErr] = useState({})
    let [outTime,setOutTime]=useState(0)
    let [data, setData] = useState({
        userId: localStorage.getItem('userId'),
        adAppType,
        users: [],
        callbackPage: 'http%3A%2F%2Ferp.zanxiangnet.com%2FadCode',
        authorization: `Bearer ${sessionStorage.getItem('Admin-Token')}`,
        smType: smType ? "WX" : "QQ",
        isOld
    })
    let adAppIdonChange = useCallback((checkedValue) => {
        let v = checkedValue.target.value
        console.log("checkedValue===>", v)
        setData({ ...data, adAppType: v })
    }, [data])
    let submit = useCallback(() => {
        if (data.users.some(user => isNaN(user))) {
            message.error('账号请使用数字！！！！！！')
            return
        }
        console.log(data)
        setLoading(true)
        fetch(api + '/qq/auth', {
            method: 'POST',
            headers: {
                "content-type": "application/json",
            },
            body: JSON.stringify(data)
        }).then(res => res.json()).then(r => {
            if (r?.data?.codeImgUrl) {
                setCodeUrl(r?.data?.codeImgUrl)
                setVisible(true)
                let n = 0
                let overTime = data.smType === 'QQ' ? 60 : 240
                time = setInterval(() => {
                    if ( n < overTime) {
                        n += 1
                        fetch(`${api}/qq/isOk?userId=${localStorage.getItem('userId')}&smType=${data.smType}`, {
                            method: 'GET'
                        }).then(res => res.json()).then(r => {
                            if (r.data) {
                                setVisible(false)
                                setCodeUrl("")
                                clearInterval(time)
                                setLoading(false)
                            }
                        })
                    } else {
                        message.error('扫码超时请重新扫码！')
                        setVisible(false)
                        setCodeUrl("")
                        clearInterval(time)
                        setLoading(false)
                    }
                    setOutTime(overTime-n)
                }, 1000)
            } else {
                message.success('已经开始授权，稍后自行查看结果！如遇到问题请点击清除账号状态按钮重试！')
                setLoading(false)
            }
            console.log(r)
        })
    }, [data])
    let query = () => {
        fetch(`${api}/qq/queryErr?userId=${localStorage.getItem('userId')}`, {
            method: 'GET'
        }).then(res => res.json()).then(r => {
            console.log(r)
            setErr(r.data)
        })
    }
    let del = () => {
        fetch(`${api}/qq/delCookie?userId=${localStorage.getItem('userId')}`, {
            method: 'GET'
        }).then(res => res.json()).then(r => {
            console.log(r)
            message.success('清理成功！！！！请重新扫码授权登录！！！')
        })
    }
    let userIdChange = useCallback((e) => {
        let value = e.target.value
        let arr = value.split(/,|，/)
        let newArr = arr?.map((str: string) => Number(str.replace(/\s/ig, '')))
        setData({ ...data, users: newArr })
    }, [data])
    return <Modal
        open={qqVisible}
        footer={null}
        width={800}
        onCancel={callBack}
        maskClosable={false}
        title={<>{title}<span style={{ color: 'red' }}>（如需更换手机扫码请先点击清除账号状态）</span></>}
    >
        <div>
            <Row>
                <Col span='24'>
                    <Row>
                        <Col span={3}><h3>扫码渠道：</h3></Col>
                        <Col span={20}>
                            <Radio.Group style={{ width: '100%' }} onChange={(e) => {
                                setData({ ...data, smType: e.target.value })
                            }} defaultValue={data.smType}>
                                <Radio value={"QQ"}>QQ</Radio>
                                {!isOld && <Radio value={"WX"}>微信</Radio>}
                            </Radio.Group>
                        </Col>
                    </Row>
                </Col>
                <Col span='24'>
                    <Row>
                        <Col span={3}><h3>平台选择：</h3></Col>
                        <Col span={20}>
                            <Radio.Group style={{ width: '100%' }} onChange={adAppIdonChange} defaultValue={data.adAppType}>
                                {adAppType === 0 ? <Radio value={0}>小说</Radio> : <Radio value={1}>游戏</Radio>}
                            </Radio.Group>
                        </Col>
                    </Row>
                </Col>
                <Col span='24'>
                    <Row>
                        <Col span={3}><h3>账号ID：</h3></Col>
                        <Col span={20}> <Input.TextArea placeholder='多个账号请以,号隔开例：123456,222333,444444' rows={5} onChange={userIdChange} allowClear></Input.TextArea></Col>
                    </Row>
                </Col>
            </Row>
            <Row style={{ display: 'flex', justifyContent: 'center', marginTop: 20 }}>
                <Space>
                    <Button type='primary' onClick={submit} loading={loading} disabled={data.users.length === 0}>提交</Button>
                    <Button type='default' onClick={query} >查询授权失败账号</Button>
                    <Popconfirm title={'清除账号状态将清除所有失败记录，并清空上一次扫码授权状态！'} onConfirm={del} >
                        <Button type='primary' danger >清除账号状态</Button>
                    </Popconfirm>

                </Space>
            </Row>
            <Row>
                {
                    Object.keys(err).map((key, i) => {
                        return <Col key={i} span={24}>
                            <div>
                                <h4>{name[key]}</h4>
                                <p>{err[key]?.join()}</p>
                            </div>
                        </Col>
                    })
                }
            </Row>
            <Modal
                open={visible}
                footer={null}
                width={250}
                onCancel={() => { setVisible(false); location.reload() }}
                maskClosable={false}
                title={<>{data?.smType === 'QQ' ? "QQ扫码" : "微信扫码"}</>}
            >
                <div style={{ display: 'flex', justifyItems: "center", alignItems: 'center',flexFlow:'column' }}>
                    <Image
                        style={{ width: 150 }}
                        src={codeUrl} />
                    <strong style={{ color: 'red', width: '100%', textAlign: 'center' }}>扫码成功后或超时自动关闭窗口</strong>
                    <strong style={{ color: 'red', width: '100%', textAlign: 'center' }}>{outTime > 0 ? outTime : ""}</strong>
                </div>
            </Modal>
        </div>
    </Modal>

}
export default QQAuth