import {invalidCode} from '@/common/setting'
import {nowDate} from '@/utils/util.js'
import {deepworkMode} from '@/api/biz/biz.js'

// 全局公共方法
const install = (Vue, vm) => {

	// 登录操作
	const login = (userInfo) => {
		vm.$u.vuex('userInfo', userInfo)
		vm.$u.vuex('accessToken', userInfo.access_token)
		vm.$u.vuex('isLogin', true)
		vm.$u.func.toHome()
	}
	
	//跳到首页。所有地方都不要写死这个页面的地址，统一由这个方法管理
	const toHome = () => {
		uni.switchTab({
			url: '/pages/yuecai/home/index'
		})
	}

	// 退出登录
	const logout = (noReLaunch) => {//支持不跳转
		vm.$u.vuex('userInfo', {
			avatar: '',
			nick_name: '游客',
			tenant_id: '暂无'
		})
		vm.$u.vuex('accessToken', '')
		vm.$u.vuex('isLogin', false)
		if (!noReLaunch) {//跳转
			uni.reLaunch({
				url: '/pages/index'
			})
		}
	}

	// 检查登录状态
	const checkLogin = (e = {}) => {
		if (!vm.isLogin || (new Date() > new Date(vm.userInfo.tokenExpire))) {
			return false
		}
		return true
	}

	// 跳转路由前检查登录状态
	const route = (url) => {
		if (!vm.isLogin) {
			uni.showToast({
				title: '请先登录',
				icon: 'none'
			})
			setTimeout(() => {
				uni.navigateTo({
					url: '/pages/index'
				})
			}, 500)
			return false
		}
		uni.navigateTo({
			url: url
		})
	}

	// URL参数转对象
	const paramsToObj = (url) => {
		if (url.indexOf('?') != -1) {
			let arr = url.split('?')[1]
		}
		let arr = url.split('&')
		let obj = {}
		for (let i of arr) {
			obj[i.split('=')[0]] = i.split('=')[1]
		}
		return obj
	}

	// 刷新当前页面
	const refreshPage = () => {
		const pages = getCurrentPages()
		const currentPage = pages[pages.length - 1]
		const path = '/' + currentPage.route + vm.$u.queryParams(currentPage.options)
		if (vm.$u.test.contains(currentPage.route, 'tabbar')) {
			uni.reLaunch({
				url: path,
				fail: (err) => {
					console.log(err)
				}
			})
		} else {
			uni.redirectTo({
				url: path,
				fail: (err) => {
					console.log(err)
				}
			})
		}
	}

	// 提示
	const showToast = (data = {}) => {
		if (typeof data == 'string') {
			uni.showToast({
				title: data,
				icon: 'none'
			})
		} else {
			uni.showToast({
				title: data.title,
				icon: data.icon || 'none',
				image: data.image || '',
				mask: data.mask || false,
				position: data.position || 'center',
				duration: data.duration || 1500,
				success: () => {
					setTimeout(() => {
						if (data.back) return uni.navigateBack()
						data.success && data.success()
					}, data.duration || 1500)
				}
			})
		}
	}

	//微信小程序获取wxcode静默登录,并获取token
	const wxLogin = () => {
		let that = vm
		uni.login({
			provider: 'weixin',
			success: function(loginRes) {
				console.log("$u.func.wxLogin()");
				if (loginRes.hasOwnProperty('code') && loginRes.code.length > 0) {
					let wxCode = loginRes.code
					//app.$uStore({ wxcode: wxCode})
					that.$u.api.wxUserLogin(wxCode).then(res => {
						let userInfo = res.data
						if (userInfo.error_code == invalidCode) {//登录请求返回200，但是还是登录失败就走这里
							uni.$u.toast(userInfo.error_description)
							setTimeout(() => {
								uni.reLaunch({
									url: '/pages/index'
								})
							}, 800)
							return
						}
						if (userInfo.hasOwnProperty('access_token')) {
							userInfo['accessToken'] = userInfo.access_token
							userInfo['isLogin'] = true
						}
						that.$u.vuex('userInfo', userInfo)
						that.$u.vuex('accessToken', userInfo.access_token)
						that.$u.vuex('isLogin', userInfo.isLogin)
						that.$u.vuex('tokenExpire', new Date().getTime() + userInfo.expires_in * 1000)
            // 登录结束跳转首页
            vm.$u.func.toHome()
					})
				}
			}
		})
	}
	
	//同步调用版本的微信小程序登录 外部调用时候使用 await wxLoginSync()
	const wxLoginSync = () => {
		return new Promise((resolve, reject) => {
			let that = vm
			uni.login({
				provider: 'weixin',
				success: async function(codeRes) {
					console.log("login in $u func...", codeRes);
					//let codeRes = codeRes
					if (codeRes.hasOwnProperty('code') && codeRes.code.length > 0) {
						console.log("use code to get token ...", codeRes)
						let wxCode = codeRes.code
						//app.$uStore({ wxcode: wxCode})
						let loginRes = await that.$u.api.wxUserLogin(wxCode)
						if (loginRes && loginRes.data && loginRes.data.hasOwnProperty(
								'access_token')) {
							let userInfo = loginRes.data
							if (userInfo.hasOwnProperty('access_token')) {
								userInfo['accessToken'] = userInfo.access_token
								userInfo['isLogin'] = true
							}
							await that.$u.vuex('userInfo', userInfo)
							await that.$u.vuex('accessToken', userInfo.access_token)
							await that.$u.vuex('isLogin', userInfo.isLogin)
							await that.$u.vuex('tokenExpire', new Date().getTime() +
								userInfo.expires_in * 1000)
						}
						
						resolve("ok")
					}
				}
			})
		})
	}

	// 发起支付请求
	const wxPayment = (option) => {
		const options = {
			timeStamp: '',
			nonceStr: '',
			prepay_id: '',
			packageValue: '',
			paySign: '',
			...option
		}
		return new Promise((resolve, reject) => {
			uni.requestPayment({
				provider: 'wxpay',
				timeStamp: options.timeStamp,
				nonceStr: options.nonceStr,
				'package': options.packageValue || `prepay_id=${options.prepay_id}`,
				signType: 'MD5',
				paySign: options.paySign,
				success: res => resolve(res),
				fail: res => reject(res)
			})
		})
	}

	//解析图片
	const baiduOCR = (type, url) => {
		let that = vm
		return new Promise((resolve, reject) => {
			let token = that.baiduAccessToken || null
			if (!token) {
				that.$u.api.getBaiduAccessToken().then(res => {
					token = res.access_token
					that.$u.vuex('baiduAccessToken', token)
					baiduOCRByToken(that, type, url, token, resolve, reject)
				})
			} else {
				baiduOCRByToken(that, type, url, token, resolve, reject)
			}
		})
	}

	const baiduOCRByToken = (that, type, url, token, resolve, reject) => {
		switch (type) {
			case 1: //身份证
				that.$u.api.baiduIdCard(token, url).then(rs => {
					resolve(rs.data)
				}).catch(rs => {
					resolve(rs.data)
				})
				break
			case 2: //营业执照
				that.$u.api.baiduBusinessLicense(token, url).then(rs => {
					resolve(rs.data)
				}).catch(rs => {
					resolve(rs.data)
				})
				break
			default:
				reject()
				break
		}
	}

	// 将定义的方法挂载，使用this.$u.func.xx调用
	Vue.prototype.$u.func = {
		login,
		toHome,
		logout,
		route,
		checkLogin,
		paramsToObj,
		refreshPage,
		showToast,
		wxLogin,
		wxPayment,
		baiduOCR,
		wxLoginSync,
		biz: {
			deepworkMode,
		}
	}
}
export default {
	install
}
