<template>
	<view>

	</view>
</template>

<script setup>
	import { onLoad, onShow } from '@dcloudio/uni-app'
	import appConfig from '@/config/appConfig.js'
	import { setToken, setPageType, setLiteToken } from '@/util/jeepayTokenUtil.js'
	import { reactive } from 'vue'
	import { $getChannelUserId } from '@/http/apiManager.js'
	import { toErrPageFunc } from '@/util/toErrorPageUtil.js'
	import storageManage from '@/util/storageManage.js'
	// import { Base64 } from 'js-base64'
  import { navigateTo } from "@/util/member.js"
	onLoad((options) => {
		
		setPageType()
		
		if (appConfig.currentPageType == appConfig.PAGE_TYPE_ENUM.WECHAT_LITE) {
			getWxParams(options)
		} else if (appConfig.currentPageType == appConfig.PAGE_TYPE_ENUM.ALIPAY_LITE) {
			getAliParams(options)
		}
	})
	
	// 微信登录
	function getWxParams(options) {
	
		let query = options.q || ''
		setLiteToken(decodeURIComponent(query))
		
		uni.showLoading({title: '加载中...'})
		
		// 获取openId
		wx.login({
			success(res) {
				commonGetChannelUserIdFunc(appConfig.PAGE_TYPE_ENUM.WECHAT_LITE, res.code, { 'code': res.code })
			},
			fail() {
				uni.hideLoading()
				toErrPageFunc('登录失败')
			}
		})
	}
	
	// 支付宝登录
	function getAliParams(options) {
		
		// 首页扫码进入
		if (options && options.isNeedParseQrc) {
			let query = options.q || ''
			setLiteToken(decodeURIComponent(query))
		}
		
		uni.showLoading({title: '加载中...'})
		
		my.getAuthCode({
			success: (res) => {
				commonGetChannelUserIdFunc(appConfig.PAGE_TYPE_ENUM.ALIPAY_LITE, res.authCode, { 'auth_code': res.authCode })
			},
			fail: (res) => {
				uni.hideLoading()
				toErrPageFunc('登录失败')
			}
		})
	}
	
	
	function commonGetChannelUserIdFunc(pageType, authCode, reqParams){
		
		if (authCode) {
			
			// 缓存KEY: jeepayChannelUserId_pageType
			// 此处不再查询后端的缓存KEY, 不同小程序之间做了隔离， 与浏览器有区别。  所以此处不需要根据appID做区分。 
			// 此小程序内， 获取到的只能是此服务商该小程序APPID的openID 
			let channelUserIdCacheKey = 'jeepayChannelUserId_' + pageType;
			// let jeepayChannelUniIdKey = 'jeepayChannelUniId_' + pageType;
			// 存在缓存
			if(storageManage.channelUserId(channelUserIdCacheKey)){
        navigateTo(storageManage.channelUserId(channelUserIdCacheKey))
        uni.hideLoading()
				return 
			}
			// 传输是否为特约商户的小程序账号 
			if(reqParams){
				reqParams.isUseSubmchAccount = appConfig.isUseSubmchAccount
			}
			// 以下为不存在缓存数据
			$getChannelUserId(reqParams).then(({ bizData }) => {		
        console.log('channelUserId',bizData);
				// 放置 userID缓存。 
				if(bizData){
					storageManage.channelUserId(channelUserIdCacheKey, bizData)	
				}
        navigateTo(bizData)
				uni.hideLoading()
			
			}).catch(err => {
				uni.hideLoading()
				console.log(err);
			})
		} else {
			uni.hideLoading()
			return toErrPageFunc('登录失败')
		}
	}
	// 跳转至收银台
	function setChannelUserIdAndToPaywayPage() {
		uni.redirectTo({
			url: '/pages/payway/index',
			success() {
				uni.hideLoading()
			}
		})
	}
	

</script>

<style>

</style>
