import store from '@/store/index.js'
import authorize from '@/common/config/authorize.js'
import ajaxService from '@/services/ajax.service.js'
import UserService from '@/services/user.service'

const newUserService = new UserService(ajaxService)

// 根据微信的code获取用户登录状态:1已登录过 -1未登录过
const wxLoginAuthorize = async function(){
    const wechatCode = await authorize.getCode('weixin')// 根据微信的code获取用户登录状态:1已登录过 -1未登录过
    const getUserInfo = await authorize.getUserInfo('weixin')
    newUserService.UserLoginAuthApplets({ 
        code:wechatCode,
        encryptedData:getUserInfo.encryptedData,
        iv:getUserInfo.iv
    })
        .then(response =>{
            store.commit('updateStatus',response.data)
            store.commit('login',response.data)
            uni.setStorageSync('token',response.data.token)
            uni.setStorageSync('unionId',response.data.unionId)
        })
        .catch(error =>{
            uni.setStorageSync('unionId',error.data.unionId)
            store.commit('logout',error.data)
            store.commit('updateStatus',error.data)
        })
}
const wxLoginQuick = async function(){// 根据微信的code获取用户登录状态:1已登录过 -1未登录过跳转
    const wechatCode = await authorize.getCode('weixin')// 根据微信的code获取用户登录状态:1已登录过 -1未登录过
    const getUserInfo = await authorize.getUserInfo('weixin')
    newUserService.UserLoginAuthApplets({ 
        code:wechatCode,
        encryptedData:getUserInfo.encryptedData,
        iv:getUserInfo.iv
    })
        .then(response =>{
            console.log(response)
            store.commit('updateStatus',response.data)
            store.commit('login',response.data)
            uni.setStorageSync('token',response.data.token)
            uni.setStorageSync('unionId',response.data.unionId)
            if(response.data.userIdentity ==1){
                uni.navigateTo({url:'/pages/seller/index/index'})
            }else if(response.data.userIdentity === 3){
                uni.navigateTo({url:'/pages/supplier/index/index'})
            }else{
                uni.switchTab({url:'/pages/tabBar/user/user'})
            }
        })
        .catch(error =>{
            uni.setStorageSync('unionId',error.data.unionId)
            store.commit('logout',error.data)
            store.commit('updateStatus',error.data)
        })
}
export default{
    wxLoginAuthorize,
    wxLoginQuick
}
