import { api } from 'common/api'
import { token } from 'common/token'
//import { encryptByDES, decryptByDES } from 'util/des'
import { encryptByRSA } from 'util/rsa'
import { removeGlobal, RSA_PUBLIC_KEY } from 'util/global'
import { message as Message } from 'antd'
import { Redirect } from 'react-router-dom'

const doLogin = (args) => {
    return new Promise((resolve, reject) => {
        let { account, password } = args
        password = encryptByRSA(password, RSA_PUBLIC_KEY)
        api.login({ account, password }).then(({ success, data, message }) => {
            if (success) {
                token.value = data
                Message.success('登录成功')
                // if (app.$route.query.return) {
                //     const r = decryptByDES(app.$route.query.return)
                //     app.$router.replace(r)
                // } else {
                //     app.$router.replace('/')
                // }
                return <Redirect to="/" push={false} />
            } else {
                Message.error(message)
                reject()
            }
        }).catch(({ message }) => {
            if (typeof message === 'object' && message[0]) {
                Message.error(message[0].messages[0])
            }
            reject()
        })
    })
}

const doLogout = () => {
    return new Promise((resolve, reject) => {
        api.logout().then(({ success, message }) => {
            if (success) {
                removeGlobal()
                token.value = ''
                // if (app.$route.path === '/') {
                //     app.$router.replace('/login')
                // } else {
                //     app.$router.replace({
                //         path: '/login',
                //         query: {
                //             return: decodeURIComponent(encryptByDES(app.$route.path))
                //         }
                //     })
                // }
                resolve()
            } else {
                message.error(message)
                reject()
            }
        })
    })
}

export {
    doLogin,
    doLogout,
}