<template>
	<view class="login">
		<view class="logo">
			<image :src="configList.logo_image" mode=""></image>
		</view>
		
		<view class="title">
			欢迎使用{{ configList.logo_name }}
		</view>
		
		<view class="btn mt"
			@click="handleLogin">
			<!-- <view class="icon">
				<image src="../static/auth/wx.png" mode=""></image>
			</view> -->
			<view class="">
				授权登录
			</view>
		</view>
		
		<view class="btn b2"
		@click="qux">
			取消登录
		</view>
		
		<view class="config">
			<uv-checkbox-group
				v-model="checkboxValue"
				shape="circle">
				<view class="content">
					<view
					style="display: flex;">
						<uv-checkbox
							size="40rpx"
							icon-size="30rpx"
							activeColor="#0A2463"
							:name="1"
						></uv-checkbox>
						阅读并同意我们的<text @click="$refs.popup.open('user_xy')">"用户协议"</text>
					</view>
					<view class="">
						以及<text @click="$refs.popup.open('user_ys')">隐私政策</text>
					</view>
				</view>
			</uv-checkbox-group>
		</view>
		
		<configPopup ref="popup"></configPopup>
		
	</view>
</template>

<script>
	import SignPackage from '@/utils/share.js'
	export default {
		name : 'Login',
		data() {
			return {
				checkboxValue : [],
				config : {},
			}
		},
		onLoad(query) {
			if (query.shareId) {
				uni.setStorageSync('shareId', query.shareId)
			}
			if(query.path){
				this.config = query
			}
			// #ifdef H5
				this.checkWechatAuthCallback();
			// #endif
		},
		methods: {
			// 微信登录统一入口
			handleLogin() {
				if(!this.checkboxValue.length){
					return uni.showToast({
						title: '请先同意隐私协议',
						icon:'none'
					})
				}

				// #ifdef MP-WEIXIN
				// 小程序环境
				this.miniProgramLogin();
				// #endif
				
				// #ifdef H5
				// H5环境 - 微信公众号授权
				this.wechatOfficialLogin();
				// #endif
			},

			// 小程序登录
			miniProgramLogin() {
				uni.login({
					provider: 'weixin',
					success: async (res) => {
						console.log('小程序登录成功', res);
						await this.processLogin(res.code);
					},
					fail: (err) => {
						console.log('小程序登录失败', err);
						uni.showToast({
							title: '登录失败',
							icon: 'none'
						});
					}
				})
			},

			// 微信公众号授权登录
			wechatOfficialLogin() {
				console.log('开始微信公众号授权登录');
				
				// 构建微信授权URL
				const appId = this.configList.official_appid || 'wx3c85955875a7b099'; // 从配置中获取AppID
				const redirectUri = encodeURIComponent(window.location.origin + window.location.pathname + '#/pages_order/auth/wxLogin');
				
				console.log('redirectUri:', window.location.origin + window.location.pathname + '#/pages_order/auth/wxLogin');
				
				const state = Date.now().toString();
				
				// 保存当前邀请人信息
				if (uni.getStorageSync('shareId')) {
					sessionStorage.setItem('temp_shareId', uni.getStorageSync('shareId'));
				}
				
				const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_userinfo&state=${state}#wechat_redirect`;
				
				console.log('跳转到微信授权页面:', authUrl);
				window.location.href = authUrl;
			},

			// 检查微信授权回调
			checkWechatAuthCallback() {
				const code = this.getUrlParameter('code');
				const state = this.getUrlParameter('state');
				
				if (code && state) {
					console.log('检测到微信授权回调, code:', code, 'state:', state);
					// 恢复邀请人信息
					const tempShareId = sessionStorage.getItem('temp_shareId');
					if (tempShareId) {
						uni.setStorageSync('shareId', tempShareId);
						sessionStorage.removeItem('temp_shareId');
					}
					
					// 处理登录
					this.processLogin(code, 'official');
				}
			},

			// 统一登录处理
			async processLogin(code, type = 'applet') {
				try {
					const loginParams = {
						code: code,
						type
					};

					// 添加邀请人信息
					if (uni.getStorageSync('shareId')) {
						loginParams.shareId = uni.getStorageSync('shareId');
					}

					console.log('登录参数:', loginParams);

					// 根据登录类型选择不同的API
					const apiName = type === 'official' ? 'officialLogin' : 'wxLogin';

					// 调用登录API
					this.$api('wxLogin', loginParams, (res) => {
						if (res.code == 200) {
							uni.setStorageSync('token', res.result.token);
							
							const userInfo = res.result.userInfo;
							
							// 存储用户信息到store
							this.$store.state.userInfo = userInfo;
							this.$store.state.isLogin = true;

							uni.setStorageSync('userInfo', userInfo)

							SignPackage()
							
							if (!userInfo.nickName || !userInfo.headImage) {
								uni.navigateTo({
									url: '/pages_order/auth/wxUserInfo'
								});
								return;
							} else {
								// #ifdef H5
								window.location = 'https://h5.budingxiaoshuo.com'
								return
								// #endif
								uni.showToast({
									title: '登录成功',
									icon: 'success'
								});
								uni.navigateBack(-1);
							}
						} else {
							throw new Error(res.msg || '登录失败');
						}
					});
				} catch (error) {
					console.error('登录失败:', error);
					uni.showToast({
						title: '登录失败，请重试',
						icon: 'none'
					});
					
					// #ifdef H5
					// H5环境下如果登录失败，清除URL参数并重新加载页面
					if (this.getUrlParameter('code')) {
						const cleanUrl = window.location.origin + window.location.pathname + window.location.hash.split('?')[0];
						window.history.replaceState({}, document.title, cleanUrl);
					}
					// #endif
				}
			},

			// 获取URL参数
			getUrlParameter(name) {
				// #ifdef H5
				const url = window.location.href;
				try {
					const urlParams = new URLSearchParams(window.location.search);
					return urlParams.get(name) || '';
				} catch (e) {
					// 兼容性处理
					const regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)');
					const results = regex.exec(url);
					if (!results) return '';
					if (!results[2]) return '';
					return decodeURIComponent(results[2].replace(/\+/g, ' '));
				}
				// #endif
				
				// #ifndef H5
				return '';
				// #endif
			},

			getPhoneNumber(e){
				console.log(e, e.detail.code);
				this.wxLogin(phoneCode)
			},
			
			wxLogin(phoneCode){
				if(!this.checkboxValue.length){
					return uni.showToast({
						title: '请先同意隐私协议',
						icon:'none'
					})
				}
				this.$store.commit('login', this.config)
			},
			
			//打开应用配置
			openConfigDetail(key){
				this.$refs.popup.open(key)
			},
			qux(){
				uni.reLaunch({
					url: '/pages/index/index'
				})
			},
		}
	}
</script>

<style scoped lang="scss">
.login{
	display: flex;
	justify-content: center;
	align-items: center;
	flex-direction: column;
	position: relative;
	background-color: #e5eaf9;
	min-height: 100vh;
	.logo{
		margin-top: 120rpx;
		height: 140rpx;
		width: 140rpx;
		image{
			height: 140rpx;
			width: 140rpx;
			border-radius: 30rpx;
		}
		margin-bottom: 20rpx;
	}
	.title{
		position: relative;
		font-weight: 900;
		font-size: 45rpx;
		&::after{
			content: '';
			position: absolute;
			left: 0;
			top: 100%;
			display: block;
			height: 8rpx;
			width: 210rpx;
			background: linear-gradient(to right,$uni-color, #fff);
		}
	}
	.btn{
		all: unset;
		width: 80%;
		height: 100rpx;
		background-color: $uni-color;
		color: #fff;
		display: flex;
		justify-content: center;
		align-items: center;
		margin: 20rpx 0;
		border-radius: 60rpx;
		border: none;
		&::after{
			
		}
		.icon{
			margin-right: 10rpx;
			image{
				width: 40rpx;
				height: 35rpx;
			}
		}
	}
	.b2{
		background-color: rgba($uni-color, 0.2);
		color: $uni-color;
	}
	.mt{
		margin-top: 200rpx;
	}
	
	.config{
		margin-top: 30rpx;
		font-size: 24rpx;
		text-align: center;
		line-height: 40rpx;
		text{
			color: $uni-color;
		}
	}
}
</style>
