import request from '@/utils/request'

const baseUrl = 'http://192.168.8.213:8080/zzjs-admin';

//微信小程序登录code
function unilogin() {
	return new Promise((reslove, err) => {
		uni.login({
			provider: 'weixin',
			success: (res) => {
				reslove(res)
			}
		});
	})
}

//微信小程序获取用户信息
function unigetUserInfo() {
	return new Promise((reslove, err) => {
		uni.getSetting({
			success(res) {
				if (res.authSetting['scope.userInfo']) {
					// 已经授权，可以直接调用 getUserInfo 获取头像昵称
					uni.getUserInfo({
						provider: 'weixin',
						success: (res) => {
							reslove(res)
						}
					});
				} else {
					//未授权
					reslove({
						code: 400,
						msg: '用户未授权'
					})
				}

			}
		})



	})
}

// 登录方法
export async function login() {
	let res = await unilogin();
	return request({
		url: baseUrl + '/login/jscode',
		method: 'post',
		params: {
			jscode: res.code
		},
		header: {
			isLogin: true
		}
	})
}

// 获取用户详细信息
export async function getInfo() {
	let res = await unigetUserInfo()
	if (res.code !== 400) {
		//更新用户头像
		let userInfo = await request({
			url: baseUrl + '/getInfo',
			method: 'get'
		})
		if (userInfo.data.student.nickName != res.userInfo.nickName || userInfo.data.student.headImage != res.userInfo.avatarUrl) {
			userInfo.data.student.nickName = res.userInfo.nickName
			userInfo.data.student.headImage = res.userInfo.avatarUrl
			await request({
				url: baseUrl + '/student/user/info',
				method: 'post',
				data: {
					nickName: res.userInfo.nickName,
					headImage: res.userInfo.avatarUrl
				}
			})
		}
		return userInfo
	} else {
		//用户拒绝授权
		console.log(wxuserinfo)
	}

	return request({
		url: baseUrl + '/getInfo',
		method: 'get'
	})
}

// 退出方法
export function logout() {
	return request({
		url: '/logout',
		method: 'post'
	})
}

// 绑定用户身份证信息
export function bindUserCard(data) {
	return request({
		url: baseUrl + '/gzpt/userInfo/bind',
		method: 'put',
		data
	})
}
