<!-- 微信公众号的登录回调页 -->
<template>
	<view />
	<!-- 积分确权 -->
	<su-popup :show="selectSocialUsers" type="center" round="10" :isMaskClick="false">
		<view class="head-nav">
			<view class="head-box">
				<view class="ss-flex ss-m-b-20">
					<view class="isActive head-title">
						请选择账号登录
					</view>
				</view>
			</view>
		</view>
		<view>
			<scroll-view class="side-menu-wrap" scroll-y style="height:600rpx">
				<view v-for="user in state.socialUsers" :key="user.username" class="ss-flex"
					style="padding: 20rpx;margin: 0 auto;width: 520rpx;" @click="selectUser(user.username)">
					<image :src="user.avatar"
						style="width:100rpx;height:100rpx;border-radius: 50%;margin-right:20rpx" />
					<view>{{user.username}}</view>
				</view>
				<view v-if="!state.socialUsers.length" style="padding: 20rpx;width: 520rpx;text-align: center;margin-top: 100rpx;">
					该微信暂绑定无账号
					<br/>
					请使用其他登陆方式
				</view>
			</scroll-view>
		</view>
	</su-popup>
	<su-popup :show="isPopup" round="10" :showClose="false" @close="closeAuthModal">
		<view>
			<view class="head-box">
				<view class="ss-flex ss-m-b-20">
					<view class="isActive head-title">
						微信注册
					</view>
				</view>
			</view>
			<!-- 表单项 -->
			<uni-forms ref="smsLoginRef" v-model="state.model" :rules="state.rules" validateTrigger="bind"
				labelWidth="140" labelAlign="center" class="loginUniForm">
				<uni-forms-item name="username" label="用户名" class="loginUniFormItem">
					<uni-easyinput placeholder="请输入用户名" v-model="state.registerReqVO.username" :inputBorder="false"
						:clearable="false" @blur="verifyUsername">
						<template v-slot:right>
							<view v-if="!state.verifyUsername" class="icon">
								<image style :src="sheep.$url.static('/static/images/shibai.png')" />
							</view>
							<view v-else class="icon">
								<image :src="sheep.$url.static('/static/images/chenggong.png')" />
							</view>
						</template>
					</uni-easyinput>
				</uni-forms-item>

				<uni-forms-item name="mobile" label="手机号" class="mobile loginUniFormItem ss-p-t-10" :error-message="state.mobileErrorMsg">
					<phoneInternationalInput :verify-username="state.verifyUsername" @input="mobileInput"/>
				</uni-forms-item>
				<uni-forms-item name="code" label="验证码" class="loginUniFormItem">
					<uni-easyinput placeholder="请输入验证码" v-model="state.model.code" :inputBorder="false" type="number"
						maxlength="4">
					</uni-easyinput>
				</uni-forms-item>
			</uni-forms>
			<view
				style="display: flex;justify-content: space-between;padding: 40rpx;padding-bottom: 0rpx;padding-bottom: 40rpx">
				<button class="ss-reset-button login-btn-start" @tap="officialRegister"> 注册 </button>
			</view>
		</view>
	</su-popup>
</template>
<script setup>
	import {
		ref,
		reactive,
		unref,
		computed,
		onBeforeMount
	} from 'vue';

	import sheep from '@/sheep';
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import {
		showAuthModal,
		closeAuthModal,
		getSmsCode,
		getSmsTimer
	} from '@/sheep/hooks/useModal';
	import {
		code,
		mobile
	} from '@/sheep/validate/form';
	import AuthUtil from '@/sheep/api/member/auth';
	import phoneInternationalInput from '@/sheep/components/s-auth-modal/components/phone-international-input.vue';
	const mobileInput = (mobile,mobileError)=>{
		state.model.mobile = mobile;
		state.mobileErrorMsg = mobileError;
	}
	const smsLoginRef = ref(null);
	// 数据
	const state = reactive({
		verifyUsername: false,
		mobileErrorMsg:'',
		openid: '',
		socialUsers: [],
		registerReqVO: {
			type: 31,
			code: "",
			state: "",
			username: "",
		},
		isMobileEnd: false, // 手机号输入完毕
		codeText: '获取验证码',
		model: {
			mobile: '', // 手机号
			code: '', // 验证码
			scene: 1
		},
		rules: {
			code,
			mobile,
		},
	});
	const isPopup = ref(false);
	const selectSocialUsers = ref(false);
	// 定义修改状态的方法
	function updateIsPopup() {
		isPopup.value = true;
	}
	// 打开用户的选择列表,如果有账户并且多个的话
	function updateSocialUsers(openid, socialUsers) {
		selectSocialUsers.value = true;
		state.openid = openid;
		state.socialUsers = socialUsers;
		console.log("updateSocialUsers条用了,这时state.socialUsers是", state.socialUsers)
	}
	// 选登录的用户
	async function selectUser(username) {
		console.log(username)
		// 提交数据
		const {
			code
		} = await AuthUtil.selectUsernameLogin({
			openId: state.openid,
			username
		});
		if (code === 0) {
			// closeAuthModal();
			// 检测 H5 登录回调
			let returnUrl = uni.getStorageSync('returnUrl');
			if (returnUrl) {
				uni.removeStorage('returnUrl');
				location.replace(returnUrl);
			} else {
				uni.switchTab({
					url: '/',
				});
			}
		}
	}
	let lastUsername = ref('')
	async function verifyUsername(e) {
		const username = e.detail.value;
		if (username == '' || username == lastUsername.value) {
			// 为空或者没改东西,不调校验
			return false;
		}
		lastUsername.value = username
		// 提交数据
		const {
			data
		} = await AuthUtil.verifyUsername(username);
		// false就是已经有这个用户名,不可以用。true是没有,可以改
		console.log(data)
		if (data) {
			state.verifyUsername = data
		} else {
			state.verifyUsername = data
		}
	}
	// 直接点微信注册,或者点微信登录,但没账号的都提示注册
	async function officialRegister() {
		// 没有linkId 不给注册
		const linkId = uni.getStorageSync("linkId");
		if (!linkId) {
			sheep.$helper.toast('您只能通过分享注册');
			return false;
		}
		state.registerReqVO.linkId = linkId
		const {
			code
		} = await AuthUtil.OfficialEnterLogin(state.model, state.registerReqVO);
		// 提交数据
		if (code === 0) {
			closeAuthModal();
			// 检测 H5 登录回调
			let returnUrl = uni.getStorageSync('returnUrl');
			if (returnUrl) {
				uni.removeStorage('returnUrl');
				location.replace(returnUrl);
			} else {
				uni.switchTab({
					url: '/',
				});
			}
		}
	}

	onBeforeMount(async () => {
		const options = {}
		new URLSearchParams(location.search).forEach((value, key) => {
			options[key] = value;
		});
		state.registerReqVO.code = options.code
		state.registerReqVO.state = options.state
	})
	onLoad(async (options) => {
		// #ifdef H5
		// 检测 H5 登录回调
		let returnUrl = uni.getStorageSync('returnUrl');
		
		
		// 将 search 参数赋值到 options 中,方便下面解析
		new URLSearchParams(location.search).forEach((value, key) => {
			options[key] = value;
		});

		const event = options.event;
		const code = options.code;
		const state = options.state;

		if (event === 'login') { // 场景一:登录
			const res = await sheep.$platform.useProvider().login(code, state)
			console.log("login.vue的res", res)
			if (!res) {
				uni.showModal({
					title: '提示',
					content: '您的微信没有账号,请通过分享注册',
					confirmColor: '#0e932e', //确定字体颜色
					showCancel: false, //没有取消按钮的弹框
					buttonText: '确定',
					success: function(res) {
						if (res.confirm) {
							sheep.$router.go('/pages/index/index')
						} 
					}
				});
				return false
			}
			if (res.data.socialUsers != null) {
				updateSocialUsers(res.data.openid, res.data.socialUsers)
				return false
			}
		} else if (event === 'register') {
			const res = await sheep.$platform.useProvider().register(code, state)
			updateIsPopup()
			return false
		} else if (event === 'bind') { // 场景二:绑定
			sheep.$platform.useProvider().bind(code, state);
			returnUrl = returnUrl+'?bind=true'
		}
		if (returnUrl) {
			uni.removeStorage('returnUrl');
			location.replace(returnUrl);
		} else {
			uni.switchTab({
				url: '/',
			});
		}
		// #endif

	});
</script>

<style lang="scss" scoped>
	.icon {
		display: flex;
		align-items: center;
		margin-right: 7rpx
	}

	.icon image {
		width: 35rpx;
		height: 35rpx;
	}

	@keyframes title-animation {
		0% {
			font-size: 32rpx;
		}

		100% {
			font-size: 36rpx;
		}
	}

	.login-wrap {
		padding: 50rpx 34rpx;
		min-height: 500rpx;
		background-color: #fff;
		border-radius: 20rpx 20rpx 0 0;
	}

	.head-box {
		padding: 40rpx 40rpx 0;

		.head-title {
			min-width: 160rpx;
			font-size: 36rpx;
			font-weight: bold;
			color: #333333;
			line-height: 36rpx;
		}

		.head-title-active {
			width: 160rpx;
			font-size: 32rpx;
			font-weight: 600;
			color: #999;
			line-height: 36rpx;
		}

		.head-title-animation {
			animation-name: title-animation;
			animation-duration: 0.1s;
			animation-timing-function: ease-out;
			animation-fill-mode: forwards;
		}

		.head-title-line {
			position: relative;

			&::before {
				content: '';
				width: 1rpx;
				height: 34rpx;
				background-color: #e4e7ed;
				position: absolute;
				left: -30rpx;
				top: 50%;
				transform: translateY(-50%);
			}
		}

		.head-subtitle {
			font-size: 26rpx;
			font-weight: 400;
			color: #afb6c0;
			text-align: left;
			display: flex;
		}
	}

	// .code-btn[disabled] {
	// 	background-color: #fff;
	// }
	.code-btn-start {
		width: 160rpx;
		height: 56rpx;
		line-height: normal;
		border: 2rpx solid var(--ui-BG-Main);
		border-radius: 28rpx;
		font-size: 26rpx;
		font-weight: 400;
		color: var(--ui-BG-Main);
		opacity: 1;
	}

	.forgot-btn {
		width: 160rpx;
		line-height: 56rpx;
		font-size: 30rpx;
		font-weight: 500;
		color: #999;
	}

	.login-btn-start {
		width: 158rpx;
		height: 56rpx;
		line-height: normal;
		background: linear-gradient(90deg, var(--ui-BG-Main), var(--ui-BG-Main-gradient));
		border-radius: 28rpx;
		font-size: 26rpx;
		font-weight: 500;
		color: #fff;
	}

	.type-btn {
		padding: 20rpx;
		margin: 40rpx auto;
		width: 200rpx;
		font-size: 30rpx;
		font-weight: 500;
		color: #999999;
	}

	.auto-login-box {
		width: 100%;

		.auto-login-btn {
			width: 68rpx;
			height: 68rpx;
			border-radius: 50%;
			margin: 0 30rpx;
		}

		.auto-login-img {
			width: 68rpx;
			height: 68rpx;
			border-radius: 50%;
		}
	}

	.agreement-box {
		margin: 80rpx auto 0;

		.protocol-check {
			transform: scale(0.7);
		}

		.agreement-text {
			font-size: 26rpx;
			font-weight: 500;
			color: #999999;

			.tcp-text {
				color: var(--ui-BG-Main);
			}
		}
	}

	// 修改密码
	.editPwd-btn-box {
		.save-btn {
			width: 690rpx;
			line-height: 70rpx;
			background: linear-gradient(90deg, var(--ui-BG-Main), var(--ui-BG-Main-gradient));
			border-radius: 35rpx;
			font-size: 28rpx;
			font-weight: 500;
			color: #ffffff;
		}

		.forgot-btn {
			width: 690rpx;
			line-height: 70rpx;
			font-size: 28rpx;
			font-weight: 500;
			color: #999999;
		}
	}

	.code-btn-start {
		color: #55b774;
		border: 1px solid #55b774;
	}

	.disabled {
		border: 1px solid #f7f7f7;
	}



	.agreement-box {
		margin: 20rpx 0;
	}

	.login-btn-start {
		background: rgb(14, 147, 46);
		width: 100%;
		height: 80rpx;
		font-size: 32rpx;
	}

	.loginUniForm {
		margin: 40rpx;
		border: 1rpx solid #d6d6d6;
		padding: 10rpx 15rpx;
		border-radius: 10rpx;
	}

	.loginUniFormItem {
		border-bottom: 1rpx solid #d6d6d6;
		padding-bottom: 10rpx;
	}

	.loginUniFormItem:last-child {
		border-bottom: none;
		padding-top: 10rpx;
	}

	::v-deep .loginUniFormItem .uni-forms-item__inner {
		padding-bottom: 0;
	}

	::v-deep .loginUniFormItem .uni-error-message {
		bottom: -20rpx;
	}
</style>