import { login, logout, getInfo, sendcode, register } from '@/api/user'
import { getToken, setToken, removeToken, getUsername } from '@/utils/auth'
import { resetRouter } from '@/router'


const getDefaultState = () => {
    return {
        token: getToken(),
        name: '',
        avatar: '',
        userId: ''
    }
}

const state = getDefaultState()

const mutations = {
    RESET_STATE: (state) => {
        Object.assign(state, getDefaultState())
    },
    SET_TOKEN: (state, token) => {
        state.token = token
    },
    SET_USERID: (state, userId) => {
        state.userId = userId
    },
    SET_NAME: (state, userName) => {
        state.name = userName
    },
    SET_AVATAR: (state, avatar) => {
        state.avatar = avatar
    }
}


const actions = {
    // 用户注册
    async register({ commit }, loginForm) {
        let data = new URLSearchParams()
        data.append("Phone", loginForm.Phone.trim())
        data.append("UserName", loginForm.UserName.trim())
        data.append('PassWord', loginForm.PassWord.trim())
        data.append('code', loginForm.verifycode.trim())
        let result = await register(data);
        if (result.status === 200) {
            return result;
        } else {
            return Promise.reject(new Error('fail'))
        }
    },
    async sendcode({ commit }, loginForm) {
        let data = new URLSearchParams()
        data.append("Phone", loginForm.Phone.trim())
        let result = await sendcode(data);
        if (result.status === 200) {
            return result;
        } else {
            return Promise.reject(new Error('fail'))
        }
    },
    // 用户登录
    // user login
    async login({ commit }, loginForm) {
        let data = new URLSearchParams()
        data.append("Phone", loginForm.Phone.trim())
        data.append('PassWord', loginForm.PassWord.trim())
        let result = await login(data);
        if (result.status === 200) {
            commit
            commit('SET_TOKEN', result.token)
            commit('SET_USERID', result.data)
            setToken(result.token);
            // 将userId存储到localstorage中
            window.localStorage.setItem('userId', result.data)
            return 'ok';
        } else {
            return Promise.reject(new Error('fail'))
        }
    },
    //获取用户信息
    getInfo({ commit, state }) {
        return new Promise((resolve, reject) => {
            let data = new URLSearchParams()
            data.append("userId", localStorage.getItem("userId"))
            getInfo(data).then(response => {
                const { data } = response
                if (!data) {
                    return reject('Verification failed, please Login again.')
                }
                const { userName, user_pic,avatar } = data[0]
                console.log(userName)
                console.log(user_pic)
                console.log(data)
                commit('SET_NAME', userName)
                    // 将userId存储到localstorage中
                window.localStorage.setItem('userName', userName)
                console.log(avatar)
                commit('SET_AVATAR', avatar)
                window.localStorage.setItem('avatar', avatar);
                resolve(data)
            }).catch(error => {
                reject(error)
            })
        })
    },
    logout({ commit }) {
        return new Promise((resolve) => {
            // 清空localstorage
            window.localStorage.clear();
            // 移除token
            removeToken();
            // 重置路由
            resetRouter();
            // 清空vuex
            commit('RESET_STATE');

            // 等待异步操作完成后再跳转到登录页面
            setTimeout(() => {
                resolve();
                next(`/login`);
            }, 1000);
        });
    },

    // remove token
    resetToken({ commit }) {
        return new Promise(resolve => {
            removeToken() // must remove  token  first
            commit('RESET_STATE')
            resolve()
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}