<template>
	<div class="whole">
		<!-- <div class="logo">
			<up-image width="100px" height="100px"
				src="https://ct-upimg.yx090.com/ju8hn6/shop/image/2024/04/07/bmDw3PJZUjNQptxAhkrB50YzxQvmKEbWRucj7kab.png" />
		</div> -->
		
		<div class="tipsBox">
			<div class="title">温馨提示</div>
			<div class="txt">首次登录请点击下方“使用完整服务”完成头像、昵称授权后进入页面</div>
		</div>
		
		<!-- <div class="twoBox">
			<div class="row">
				<up-input placeholder="请输入手机号码" border="bottom" v-model="mobile" prefixIcon="phone-fill"></up-input>
				<up-input placeholder="请输入登录密码" type="password" border="bottom" v-model="password" prefixIcon="lock-fill"></up-input>
			</div>
			<div class="btn" @click="pwdLogin">登录</div>
		</div> -->
		
		<up-popup :show="showChoose" :round="10" mode="bottom" :closeOnClickOverlay="false">
			<view class="topTitle">选择店铺</view>
			<view class="listbox">
				<up-cell-group>
					<up-cell v-for="it in shopList" :key="it.id" :isLink="true" :title="it.name" @click="chooseShop(it)"></up-cell>
				</up-cell-group>
			</view>
		</up-popup>
	</div>
</template>

<script>
	import { reactive, toRefs } from 'vue'
	import { get, post } from '@/Api/request.js'
	import { showToast, getShopInfo } from '@/components/common.js'

	export default {
		setup() {
			const data = reactive({
				mobile: '',
				password: '',
				shopList: [],
				showChoose: false
			})

			function pwdLogin() {
				if (!data.mobile) {
					return showToast('请输入手机号码')
				} else if (!data.password) {
					return showToast('请输入登录密码')
				}
				uni.showLoading({
					title: '正在登录...',
				})
				let params = {
					mobile: data.mobile,
					password: data.password
				}
				post('/api/app/login/mobile/loginByPwd', params).then(async (res) => {
					if (res.data.login_code == 0) { // 已经注册过小程序
						await unionidLogin('abcdefg', 1, res.data.unionid_open)
						uni.hideLoading()
					} else {
						showToast('账号不存在')
					}
				}).catch((err) => {
					showToast('账号密码错误')
				})
			}

			async function unionidLogin(code, shop_id, unionid_open) {
				console.log(unionid_open)
				let params = {
					code: code,
					from: 'mini-app',
					shop_id: shop_id,
					unionid_open: unionid_open
				}
				await post('/api/v1/auth/login', params).then(async (res) => {
					if (res.access_token) {
						let token = res.token_type + ' ' + res.access_token
						uni.setStorageSync('token', token)
						uni.setStorageSync('avatar', res.avatar)
						uni.setStorageSync('nickname', res.nickname)
						uni.setStorageSync('sessionKey', res.session_key)
						uni.setStorageSync('saveTime', Date.now())
						uni.setStorageSync('expires_in', res.expires_in * 1000)
						uni.switchTab({
							url: '/pages/index/index'
						})
					}
				}).catch((err) => {
					console.log('auth/login', err)
				})
			}

			function toRedirect() {
				let access_token = uni.getStorageSync('token')
				let saveTime = Number(uni.getStorageSync('saveTime'))
				let expires_in = Number(uni.getStorageSync('expires_in'))
				
				if (access_token && saveTime && expires_in && (Date.now() < saveTime + expires_in)) {
					uni.switchTab({
						url: '/index/index'
					})
				} else {
					let url = window.location.href.split('?')
					let Param = new URLSearchParams(url[1])
					if (Param.get('code')) {
						uni.showLoading({
							title: '正在登录...',
						})
						let live_id = 0
						let page = uni.getStorageSync('from_page1')
						if(page) {
							let url1 = page.split('?')
							let Param1 = new URLSearchParams(url1[1])
							live_id = Param1.get('live_id')
						}
						
						post('/api/v1/auth/login', {
							code: Param.get('code'),
							from: 'h5',
							live_id: live_id
						}).then((res) => {
							let token = res.token_type + ' ' + res.access_token
							uni.setStorageSync('token', token)
							uni.setStorageSync('avatar', res.avatar)
							uni.setStorageSync('nickname', res.nickname)
							uni.setStorageSync('sessionKey', res.session_key)
							uni.setStorageSync('saveTime', Date.now())
							uni.setStorageSync('expires_in', res.expires_in * 1000)
							
							
							uni.removeStorageSync('from_page')
							uni.removeStorageSync('from_page1')
							if (page) {
								uni.hideLoading()
								getShopInfo()
								window.location.href = page
							} else {
								uni.hideLoading()
								getShopInfo()
								uni.switchTab({
									url: '/index/index'
								})
							}
						})
					} else {
						let page = uni.getStorageSync('from_page')
						uni.setStorageSync('from_page1', page)
						let params = {
							shop_id: uni.getStorageSync('shop_id'),
							redirect_url: window.location.href
						}
						console.log(params)
						get('/api/v1/login/weChat/webRedirectUrl', params).then((res) => {
							console.log(res)
							window.location.href = res.url
						})
					}
				}
			}
			
			async function judgeShopId() {
				let orgin_shop_id = (uni.getStorageSync('orgin_shop_id') || 0) * 1
				let shopId = (uni.getStorageSync('shop_id') || 0) * 1
				let appId = uni.getStorageSync('appId')
				
				let saveTime = uni.getStorageSync('saveTime')
				let expires_in = uni.getStorageSync('expires_in')
				let token = uni.getStorageSync('token')
				
				if(shopId) {
					if(orgin_shop_id) {
						if(orgin_shop_id !== shopId) {
							console.log(orgin_shop_id)
							uni.setStorageSync('shop_id', orgin_shop_id)
							uni.request({
								url: '/api/v1/live/shop',
								data: {id: orgin_shop_id},
								method: 'GET',
								header: {
									Authorization: '',
									accept: "application/json"
								},
								success: res => {
									uni.setStorageSync('appId', res.data.data[0].appid)
									
									uni.removeStorageSync('token')
									uni.removeStorageSync('saveTime')
									uni.removeStorageSync('expires_in')
									
									toRedirect()
								}
							})
						} else {
							if(!appId) {
								uni.request({
									url: '/api/v1/live/shop',
									data: {id: orgin_shop_id},
									method: 'GET',
									header: {
										Authorization: '',
										accept: "application/json"
									},
									success: res => {
										uni.setStorageSync('appId', res.data.data[0].appid)
										
										uni.removeStorageSync('token')
										uni.removeStorageSync('saveTime')
										uni.removeStorageSync('expires_in')
										
										toRedirect()
									}
								})
							} else {
								if((saveTime && expires_in && Date.now() > saveTime + expires_in) || !expires_in || !saveTime || !token) {
									toRedirect()
								} else {
									uni.switchTab({
										url: '/pages/index/index'
									})
								}
							}
						}
					} else {
						if(!appId) {
							uni.request({
								url: '/api/v1/live/shop',
								data: {id: orgin_shop_id},
								method: 'GET',
								header: {
									Authorization: '',
									accept: "application/json"
								},
								success: res => {
									uni.setStorageSync('appId', res.data.data[0].appid)
									
									uni.removeStorageSync('token')
									uni.removeStorageSync('saveTime')
									uni.removeStorageSync('expires_in')
									
									toRedirect()
								}
							})
						} else {
							if((saveTime && expires_in && Date.now() > saveTime + expires_in) || !expires_in || !saveTime || !token) {
								toRedirect()
							} else {
								uni.switchTab({
									url: '/pages/index/index'
								})
							}
						}
					}
				} else {
					if(orgin_shop_id) {
						uni.setStorageSync('shop_id', orgin_shop_id)
						uni.request({
							url: '/api/v1/live/shop',
							data: {id: orgin_shop_id},
							method: 'GET',
							header: {
								Authorization: '',
								accept: "application/json"
							},
							success: res => {
								uni.setStorageSync('appId', res.data.data[0].appid)
								
								uni.removeStorageSync('token')
								uni.removeStorageSync('saveTime')
								uni.removeStorageSync('expires_in')
								
								toRedirect()
							}
						})
					} else {
						uni.removeStorageSync('token')
						uni.removeStorageSync('saveTime')
						uni.removeStorageSync('expires_in')
						
						// uni.request({
						// 	url: '/api/v1/live/shop',
						// 	data: {},
						// 	method: 'GET',
						// 	header: {
						// 		Authorization: '',
						// 		accept: "application/json"
						// 	},
						// 	success: res => {
						// 		data.shopList = res.data.data
						// 		data.showChoose = true
						// 	}
						// })
						// showToast('请访问正确的链接地址')
					}
				}
			}
			
			async function chooseShop(row) {
				uni.setStorageSync('shop_id', row.id)
				uni.setStorageSync('appId', row.appid)
				toRedirect()
			}

			return {
				getShopInfo,
				...toRefs(data),
				toRedirect,
				pwdLogin,
				judgeShopId,
				chooseShop
			}
		},
		onLoad(options) {
			console.log('options', options)
			this.judgeShopId()
		}
	}
</script>

<style lang="scss" scoped>
	.whole {
		width: 100%;
		height: 100vh;
		overflow: hidden;
		box-sizing: border-box;
		position: relative;

		.logo {
			display: flex;
			justify-content: center;
		}

		.twoBox {
			margin-top: 30%;
			padding: 20px;

			.row {

				// margin-bottom: 15px;
				// background-color: #f5f5f5;
				.iconfont {
					color: #666;
				}
			}
		}

		.btn {
			width: 90%;
			height: 40px;
			display: flex;
			align-items: center;
			justify-content: center;
			background-color: rgb(241, 73, 57);
			color: #fff;
			border-radius: 4px;
			margin: 30px auto;

		}
	}
	.topTitle{
		font-size: 30rpx;
		color: #303030;
		padding: 24rpx;
		font-weight: 600;
		box-sizing: border-box;
	}
	.listbox{
		height: 65vh;
		padding: 24rpx;
		overflow: auto;
		background: #fff;
	}
	.tipsBox{
		border-radius: 10px;
		background-color: #fff;
		width: 80%;
		margin: 30% auto 0;
		padding: 40rpx;
		box-sizing: border-box;
		.title{
			font-size: 32rpx;
			font-weight: 600;
			text-align: center;
		}
		.txt{
			margin-top: 30rpx;
			font-size: 28rpx;
			line-height: 50rpx;
			color: #666;
			text-indent: 46rpx;
		}
	}
</style>