import { api } from '@/common/api'
import { token } from '@/common/token'
import { GLOBAL_INFO_KEY } from '@/common/storage'
import { encryptByDES, decryptByDES } from '@/util/des'
import app from '@/main'

const setGlobal = (info) => {
    app.$set(app.global, 'info', info)
    window.sessionStorage.setItem(GLOBAL_INFO_KEY, encryptByDES(JSON.stringify(info)))
}

const removeGlobal = () => {
    app.$set(app.global, 'info', undefined)
    window.sessionStorage.removeItem(GLOBAL_INFO_KEY)
}

const getGlobal = () => {
    return JSON.parse(decryptByDES(window.sessionStorage.getItem(GLOBAL_INFO_KEY)))
}

const doLogin = (args) => {
    return new Promise((resolve, reject) => {
        api.login(args).then(({ success, data, message }) => {
            if (success) {
                token.value = data
                app.$message.success('登录成功')
                if (app.$route.query.return) {
                    const r = decryptByDES(app.$route.query.return)
                    app.$router.replace(r)
                } else {
                    app.$router.replace('/')
                }
                resolve()
            } else {
                app.$message.error(message)
                reject()
            }
        }).catch(({ message }) => {
            if (typeof message === 'object' && message[0]) {
                app.$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 {
                app.$message.error(message)
                reject()
            }
        })
    })
}

const doCheck = () => {
    return new Promise((resolve, reject) => {
        api.checkLogin().then(({ result }) => {
            setGlobal(result)
            resolve()
        }).catch(() => {
            reject()
        })
    })
}

export {
    doLogin,
    doLogout,
    doCheck,

    setGlobal,
    getGlobal
}