import { http } from '@/utils';
import { encrypt } from '@/components/passport/encryption';
import jsCookie from 'js-cookie'


const accountLogin = user => dispatch => {
    return http.post(`${API['passport-api']}/user_login`, {
        user_name: user.username,
        password: encrypt(user.password),
        is_encrypt: 1,
        redirect: encodeURIComponent(user.redirect)
    }).then(res => {
        return storeUser(res, dispatch)
    })
}

const quickLogin = user => dispatch => {
    return http.post(`${API['passport-api']}/quick_login`, {
        ...user,
        plat: 5
    }).then(res => {
        return storeUser(res, dispatch)
    })
}

const storeUser = (res, dispatch) => {
    const data = res.data
    let payload
    if (data.errno === 0) {
        const {user_name: username, avatar_file: avatar,is_vip: isVIP, ...rest} = data.data.user_info
        payload = {
            hasError: false,
            msg: data.msg,
            data: {username, avatar,isVIP, ...rest}
        }
    } else {
        payload = {
            hasError: true,
            msg: data.msg,
            data: {}
        }
    }
    dispatch(setCurrentUser(payload))
    return payload

}


const SET_CURRENT_USER = 'SET_CURRENT_USER'
const setCurrentUser = payload => ({
    type: SET_CURRENT_USER,
    payload: {...payload, isFetching: false}
})


const LOGOUT = 'LOGOUT'
const logout = () => dispatch => {
    jsCookie.remove('token', {path: '/', domain: '.julyedu.com'})
    jsCookie.remove('uid', {path: '/', domain: '.julyedu.com'})
    dispatch(setCurrentUser({hasError: true}))
}


const UPDATE_USER = 'UPDATE_USER'
const updateUser = payload => ({
    type: UPDATE_USER,
    payload
})

const START_FETCH_USER = 'START_FETCH_USER'
const startFetchUser = () => ({
    type: START_FETCH_USER
})


export {
    accountLogin,
    SET_CURRENT_USER,
    setCurrentUser,
    quickLogin,
    logout,
    UPDATE_USER,
    updateUser,
    START_FETCH_USER,
    startFetchUser,
}
