import store from '@/store'
// #ifdef H5
import jweixin from 'jweixin-module'
// #endif
// import { share } from '@/mixins'
import CONSTANT from '@/constant'
import UTIL from '@/utils/util'

import {
	getStaffApi,
	getUserApi,
	getShopUserApi
	// checkLogin,
} from '@/api/common'
import { postWxCode } from '@/api/mini'

import util from './util'
/**
 * 获取商城端用户信息
 * @parmas update为true时会重新触发请求，重置vuex的数据
 */
export async function getShopUser(update) {
	let userInfo = store.getters.getShopUser
	if (!UTIL.isEmpty(userInfo) && !update) {
	  return userInfo
	}
	await getShopUserApi().then((res) => {
		userInfo = res.data
		store.dispatch('setShopUser', userInfo)
	}).catch(() => {
		uni.removeStorageSync('token')
	})

	return userInfo
}

/**
 * 获取后台商户用户信息
 * @parmas update为true时会重新触发请求，重置vuex的数据
 */
export async function getUser(update) {
	let userInfo = store.getters.getUser
	if (!UTIL.isEmpty(userInfo) && !update) {
	  return userInfo
	}
	await getUserApi().then((res) => {
		userInfo = res.data
		store.dispatch('setUser', userInfo)
	}).catch(() => {
		uni.removeStorageSync('token')
	})

	return userInfo
}

/**
 * 获取登录员工的基本信息
 * @parmas update为true时会重新触发请求，重置vuex的数据
 */
export async function getSelfInfo(update) {
	let userInfo = store.getters.getSelfUser
	if (!util.isEmpty(userInfo) && !update) {
		return userInfo
	}
	await getStaffApi().then(res => {
		userInfo = res.data
		store.dispatch('setSelfInfo', userInfo)
	}).catch(() => {
		return false
	})

	return userInfo
}

/**
 * 微信小程序登陆
 * @parmas update为true时会重新触发请求，重置vuex的数据
 */
export async function wxLoginFn(update) {
	let dataInfo = null
	let loginInfo = store.state.login.loginInfo
	if (!util.isEmpty(loginInfo) && !update) {
		return loginInfo
	}

	let getObj = await new Promise(resolve => {
		uni.login({
			provider: 'weixin',
			success: res => {
				uni.setStorageSync('code', res.code)
				console.log(res.code, 'res.code')
				resolve(res)
			}
		})
	})

	await postWxCode({ code: getObj.code }).then(subRes => {
		if (UTIL.isEmpty(subRes)) return false
		uni.setStorageSync('token', subRes.data.token)
		store.commit('setLoginInfo', subRes.data.user)
	})

	return dataInfo
}

// export default {
// 	getSelfInfo,
// 	getUser,
// 	resetAllUser,
// 	getRoleReal
// }

