import { API_OAUTH_LOGIN, API_REGISTER,API_LOGIN, API_LOGOUT, API_CLEAR_USER, API_USER_INFO,API_CHECK_UNIQUE } from './http/api'
import { request } from './http/request'
import { clearSuccess, getInfoSuccess, loginSuccess, logoutSuccess, registerSuccess, updateSuccess } from '@/store/user'


export const checkUnique = (username?: string,email?:string) => {
    return new Promise((resolve, reject) => {
        request({
            url: API_CHECK_UNIQUE, method: 'GET', data: { username:username,email:email }
        }).then(res => {
            resolve(res);
            console.log(res);
            // dispatch(loginSuccess(res));
        })
    })
    
}

export const login = (username: string, password: string) => (dispatch: any) => {
    request({
        url: API_LOGIN, method: 'POST', data: { username, password }
    }).then(res => {
        dispatch(loginSuccess(res));
    })
}

export const wxLogin = (code: string, encryptedData: string, iv: string) => (dispatch: any)=> {
    request({
        url: API_OAUTH_LOGIN, method: 'POST',
        data: {
            code: code,
            type: 'WX_MP',
            app_version: '1',
            client_version: '1',
            client_type: 'WX_MP',
            extra: {
                encryptedData: encryptedData,
                iv: iv
            }
        }
    }).then(res => {
        dispatch(loginSuccess(res));
    })
};

/*
export const wxLogin = (code: string) => (dispatch: any) => {
    
    request({
        url: API_OAUTH_LOGIN, method: 'POST', data: { code,type:'WX_MP',app_version:'1',client_version:'1',client_type:'WXP_MP' }
    }).then(res => {
        console.log(res);
        dispatch(loginSuccess(res));
    })
}*/

export const register = (name: string, email: string, password: string) => (dispatch: any) => {
    debugger
    request({
        url: API_REGISTER, method: 'POST', data: { client_type: 'IOS', username: name, email: email, password: password }
    }).then(res => {
        dispatch(registerSuccess(res));
    })
}

export const logout = () => (dispatch: any) => {
    debugger
    request({
        url: API_LOGOUT, method: 'GET', data: {}
    }).then(_ => {
        dispatch(logoutSuccess());
    })
}

export const clear = () => (dispatch: any) => {
    debugger
    request({
        url: API_CLEAR_USER, method: 'DELETE', data: {}
    }).then(_ => {
        dispatch(clearSuccess());
    })
}

export const getInfo = () => (dispatch: any) => {
    request({
        url: API_USER_INFO, method: 'GET', data: {}
    }).then(res => {
        dispatch(getInfoSuccess(res));
    })
}


export const update = () => (dispatch: any) => {
    request({
        url: API_USER_INFO, method: 'POST', data: {}
    }).then(res => {
        dispatch(updateSuccess(res));
    })
}

