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 }) {
    const { qqVisible, callBack } = props
    let [visible, setVisible] = useState(false)
    let [loading, setLoading] = useState(false)
    let [codeUrl, setCodeUrl] = useState('')
    let [err, setErr] = useState({})
    let [data, setData] = useState({
        userId: localStorage.getItem('userId'),
        adAppType: 0,
        users: [],
        callbackPage: 'http%3A%2F%2Ferp.zanxiangnet.com%2FadCode',
        authorization: `Bearer ${sessionStorage.getItem('Admin-Token')}`
    })
    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
        }
        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
                time = setInterval(() => {
                    if (n < 60) {
                        n += 1
                        fetch(`${api}/qq/isOk?userId=${localStorage.getItem('userId')}`, {
                            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)
                    }

                }, 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}
    >
        <div>
            <Row>
                <Col span='24'>
                    <Row>
                        <Col span={3}><h3>平台选择：</h3></Col>
                        <Col span={20}>
                            <Radio.Group style={{ width: '100%' }} onChange={adAppIdonChange} defaultValue={data.adAppType}>
                                <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}>提交</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={200}
                onCancel={() => setVisible(false)}
                maskClosable={false}
            >
                <Image
                    style={{ width: 150 }}
                    src={codeUrl} />
            </Modal>
        </div>
    </Modal>

}
export default QQAuth