<template>
	<div class="login-wrapper" :data-theme="theme">
		<div class="shading">
			<!-- <image :src="logoUrl"/> -->
			<image :src="logoUrl" />
			<!-- <image src="/static/images/logo2.png" v-if="!logoUrl" /> -->
		</div>
		<div class="whiteBg" v-if="showphone">

			<div class="list" v-if="current !== 0 || appLoginStatus || appleLoginStatus">
				<div class="item">
					<div class="acea-row row-middle">
						<image src="/static/images/phone_1.png" style="width: 24rpx; height: 34rpx;"></image>
						<input type="number" class="texts" placeholder="输入手机号码" v-model="account" maxlength="11" />
					</div>
				</div>
				<div class="item">
					<div class="acea-row row-middle">
						<image src="/static/images/code_2.png" style="width: 28rpx; height: 32rpx;"></image>
						<input type="number" placeholder="填写验证码" class="codeIput" v-model="captcha" maxlength="6" />
						<button class="code main_color" @click="code">
							<template v-if="!isCountdownStarted">{{ text }}</template>
							<template v-else>{{ countdown }}s</template>
						</button>
					</div>
				</div>
				<div class="item" v-if="isShowCode">
					<div class="acea-row row-middle">
						<image src="/static/images/code_2.png" style="width: 28rpx; height: 32rpx;"></image>
						<input type="number" placeholder="填写验证码" class="codeIput" v-model="codeVal" maxlength="6" />
						<div class="code" @click="again"><img :src="codeUrl" /></div>
					</div>
				</div>
			</div>
			<div class="logon bg_color" @click="loginMobile" v-if="current !== 0">绑定手机号</div>



		</div>
		<view class="logon bg_color" @click="getali()" v-if="showphone==false">
			授权登录
		</view>
		<div class="bottom"></div>
	</div>
</template>

<script>
	import dayjs from "@/plugin/dayjs/dayjs.min.js";
	import sendVerifyCode from "@/mixins/SendVerifyCode";
	import {
		loginH5,
		loginMobile,
		registerVerify,
		register,
		// getCodeApi,
		getUserInfo,
		aliCode
	} from "@/api/user";
	let app = getApp();
	import attrs, {
		required,
		alpha_num,
		chs_phone
	} from "@/utils/validate";
	import {
		validatorDefaultCatch
	} from "@/utils/dialog";
	import {
		getLogo,
		appAuth,
		appleLogin
	} from "@/api/public";
	import {
		VUE_APP_API_URL
	} from "@/utils";
	import Routine from '@/libs/routine';
	import {
		Debounce
	} from '@/utils/validate.js'
	const BACK_URL = "login_back_url";
	export default {
		data() {
			return {
				showphone: false,
				logoUrl: "",
				openId: '',
				authCode: '',
				navList: ["快速登录", "账号登录"],
				current: 1,
				account: "",
				password: "",
				captcha: "",
				formItem: 1,
				type: "login",
				logoUrl: "",
				keyCode: "",
				codeUrl: "",
				codeVal: "",
				isShowCode: false,
				platform: '',
				appLoginStatus: false, // 微信登录强制绑定手机号码状态
				appUserInfo: null, // 微信登录保存的用户信息
				appleLoginStatus: false, // 苹果登录强制绑定手机号码状态
				appleUserInfo: null,
				appleShow: false, // 苹果登录版本必须要求ios13以上的
				theme: app.globalData.theme,
				text: '获取验证码',
				countdown: 0,
				isCountdownStarted: false,

			}
		},
		onLoad(option) {
			this.getLogoImage();
			this.listenMessageFromMiniProgram()
			this.getjmauthCode()
		},
		methods: {
			getjmauthCode() {
				my.postMessage({
					data: {
						action: 'getjmCode'
					}
				})
			},
			async getLogoImage() {
				let that = this;
				getLogo().then(res => {
					that.logoUrl = res.data.logoUrl ? res.data.logoUrl : '/static/images/logo2.png';
				});
			},
			getali() {
				my.postMessage({
					data: {
						action: 'getCode'
					}
				})
			},

			listenMessageFromMiniProgram() {
				let that = this
				my.onMessage = (e) => {
					console.log(e, 'aaaa'); // 在这里处理来自小程序的消息
					if (e.type == 'codeResult') {
						that.authCode = e.data
						console.log(that.authCode, 'that.authCodethat.authCode');
						// uni.setStorageSync('aliOpenid',this.openId)
						that.alicode()
					} else if (e.type == 'jmcodeResult') {
						that.authCode = e.data
						that.jmalicode()
					}

				};
			},
			jmalicode() {
				let data = {
					authCode: this.authCode
				}
				// console.log('调用了');
				uni.request({
					url: 'https://yruibao.com/prod/api/front/login/aliOauthLogin',
					// url: 'http://192.168.2.26:20411/api/front/login/aliOauthLogin', //仅为示例，并非真实接口地址。
					data: data,
					method: 'POST',

					success: (res) => {

						if (res.data.code == 200) {
							this.openId = res.data.data.alipaySystemOauthTokenResponse.openId
							console.log(res, 'resres');
							uni.setStorageSync('openids', this.openId)
							if (res.data.data.isEXist == false) {

							} else {
								let data = res.data.data.loginResponse;
								let newTime = Math.round(new Date() / 1000);
								this.$store.commit("LOGIN", {
									'token': res.data.data.loginResponse.token
								});

								this.getUserInfo(data);
							}
						} else {
							this.$util.Tips({
								title: res.data.message
							});
						}

					},
					fail: (err) => {
						this.$util.Tips({
							title: err
						});
					}
				});
			},
			alicode() {
				let data = {
					authCode: this.authCode
				}
				// console.log('调用了');
				uni.request({
					url: 'https://yruibao.com/prod/api/front/login/aliOauthLogin',
					// url: 'http://192.168.2.26:20411/api/front/login/aliOauthLogin', //仅为示例，并非真实接口地址。
					data: data,
					method: 'POST',

					success: (res) => {

						if (res.data.code == 200) {
							this.openId = res.data.data.alipaySystemOauthTokenResponse.openId
							console.log(res, 'resres');
							uni.setStorageSync('openids', this.openId)
							if (res.data.data.isEXist == false) {
								this.showphone = true
							} else {
								let data = res.data.data.loginResponse;
								let newTime = Math.round(new Date() / 1000);
								this.$store.commit("LOGIN", {
									'token': res.data.data.loginResponse.token
								});
								uni.hideLoading();
								this.getUserInfo(data);
							}
						} else {
							this.$util.Tips({
								title: res.data.message
							});
						}

					},
					fail: (err) => {
						this.$util.Tips({
							title: err
						});
					}
				});
				// aliCode(data).then(res => {

				// 	if (res.code== '200') {
				// 		console.log(res);


				// 	}
				// 	uni.hideLoading();
				// }).catch(error => {
				// 	uni.hideLoading();

				// });
			},
		
			again() {
				this.codeUrl =
					VUE_APP_API_URL +
					"/sms_captcha?" +
					"key=" +
					this.keyCode +
					Date.parse(new Date());
			},
			getCode() {
				let that = this
			},
			async getLogoImage() {
				let that = this;
				getLogo().then(res => {
					that.logoUrl = res.data.logoUrl ? res.data.logoUrl : '/static/images/logo2.png';
				});
			},
			//手机号验证码登录
			loginMobile: Debounce(function() {
				let that = this;
				if (!that.account) return that.$util.Tips({
					title: '请填写手机号码'
				});
				if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(that.account)) return that.$util.Tips({
					title: '请输入正确的手机号码'
				});
				if (!that.captcha) return that.$util.Tips({
					title: '请填写验证码'
				});
				if (!/^[\w\d]+$/i.test(that.captcha)) return that.$util.Tips({
					title: '请输入正确的验证码'
				});
				uni.showLoading({
					title: '登录中'
				})
				let channelId = 0
				let abb = uni.getStorageSync('channelId')

				if (abb != undefined) {
					channelId = parseInt(abb);
				}
				console.log(channelId, 'channelIdchannelId');
				loginMobile({
						phone: that.account,
						captcha: that.captcha,
						spread_spid: that.$Cache.get("spread"),
						channel_id: channelId,
						aliOpenid: that.openId

					})
					.then(res => {
						if (res.code == 200) {
							let data = res.data;
							let newTime = Math.round(new Date() / 1000);
							this.$store.commit("LOGIN", {
								'token': res.data.token
							});
							uni.hideLoading();
							that.getUserInfo(data);
						} else {
							that.$util.Tips({
								title: res.message
							});
						}

					})
					.catch(res => {
						uni.hideLoading();
						that.$util.Tips({
							title: res
						});
					});
			}),
			async register() {
				let that = this;
				if (!that.account) return that.$util.Tips({
					title: '请填写手机号码'
				});
				if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(that.account)) return that.$util.Tips({
					title: '请输入正确的手机号码'
				});
				if (!that.captcha) return that.$util.Tips({
					title: '请填写验证码'
				});
				if (!/^[\w\d]+$/i.test(that.captcha)) return that.$util.Tips({
					title: '请输入正确的验证码'
				});
				if (!that.password) return that.$util.Tips({
					title: '请填写密码'
				});
				if (!/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/i.test(that.password)) return that.$util.Tips({
					title: '您输入的密码过于简单'
				});
				register({
						account: that.account,
						captcha: that.captcha,
						password: that.password,
						spread_spid: that.$Cache.get("spread"),


					})
					.then(res => {
						that.$util.Tips({
							title: res
						});
						that.formItem = 1;
					})
					.catch(res => {
						that.$util.Tips({
							title: res
						});
					});
			},
		async code() {
		    if (!this.account) {
		        this.$util.Tips({
		            title: '请填写手机号码'
		        });
		        return;
		    }
		    
		    if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(this.account)) {
		        this.$util.Tips({
		            title: '请输入正确的手机号码'
		        });
		        return;
		    }
		
		    if (this.isCountdownStarted) return; // Prevent multiple clicks during countdown
		
		    this.isCountdownStarted = true;
		    this.countdown = 60; // Set initial countdown value
		
		    // Start countdown
		    const countdownInterval = setInterval(() => {
		        if (this.countdown > 0) {
		            this.countdown--; // Decrease countdown value
		        } else {
		            clearInterval(countdownInterval); // Stop countdown when it reaches 0
		            this.isCountdownStarted = false; // Enable the button
		        }
		    }, 1000);
		
		    try {
		        uni.showLoading({
		            title: '加载中...'
		        });
		        await registerVerify(this.account);
		        this.$util.Tips({
		            title: '验证码已发送'
		        });
		    } catch (err) {
		        this.$util.Tips({
		            title: err.message || '发送验证码失败'
		        });
		    } finally {
		        uni.hideLoading();
		    }
		},
			navTap: function(index) {
				this.current = index;
			},
			//账号密码登录

			getUserInfo(data) {
				this.$store.commit("SETUID", data.uid);
				getUserInfo().then(res => {
					this.$store.commit("UPDATE_USERINFO", res.data);
					let backUrl = this.$Cache.get(BACK_URL) || "/pages/index/index";
					if (backUrl.indexOf('/pages/users/login/index') !== -1) {
						backUrl = '/pages/index/index';
					}
					uni.reLaunch({
						url: backUrl
					});
				})
			},
			sendMessageToMiniProgram() {

			},
		}
	}
</script>


<style lang="scss" scoped>
	page {
		background: #fff;
	}

	.appLogin {
		margin-top: 60rpx;

		.hds {
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 24rpx;
			color: #B4B4B4;

			.line {
				width: 68rpx;
				height: 1rpx;
				background: #CCCCCC;
			}

			p {
				margin: 0 20rpx;
			}
		}

		.btn-wrapper {
			display: flex;
			align-items: center;
			justify-content: center;
			margin-top: 30rpx;

			.btn {
				display: flex;
				align-items: center;
				justify-content: center;
				width: 68rpx;
				height: 68rpx;
				border-radius: 50%;
			}

			.apple-btn {
				display: flex;
				align-items: center;
				justify-content: center;
				margin-left: 30rpx;
				background: #000;
				border-radius: 34rpx;
				font-size: 40rpx;

				.icon-s-pingguo {
					color: #fff;
					font-size: 40rpx;
				}
			}

			.iconfont {
				font-size: 40rpx;
				color: #fff;
			}

			.wx {
				margin-right: 30rpx;
				background-color: #61C64F;
			}

			.mima {
				background-color: #28B3E9;
			}

			.yanzheng {
				background-color: #F89C23;
			}

		}
	}

	.main_color {
		@include main_color(theme);
	}

	.bg_color {
		@include main_bg_color(theme);
	}

	.code img {
		width: 100%;
		height: 100%;
	}

	.acea-row.row-middle {
		input {
			margin-left: 20rpx;
			display: block;
		}
	}

	.login-wrapper {
		padding: 30rpx;

		.logon {
			display: flex;
			align-items: center;
			justify-content: center;
			width: 100%;
			height: 86rpx;
			margin-top: 80rpx;
			background-color: $theme-color;
			border-radius: 120rpx;
			color: #FFFFFF;
			font-size: 30rpx;
		}

		.shading {
			display: flex;
			align-items: center;
			justify-content: center;
			width: 100%;

			/* #ifdef APP-VUE */
			margin-top: 50rpx;
			/* #endif */
			/* #ifndef APP-VUE */

			margin-top: 200rpx;
			/* #endif */


			image {
				width: 180rpx;
				height: 180rpx;
			}
		}

		.whiteBg {
			margin-top: 100rpx;

			.list {
				border-radius: 16rpx;
				overflow: hidden;

				.item {
					border-bottom: 1px solid #F0F0F0;
					background: #fff;

					.row-middle {
						position: relative;
						padding: 16rpx 45rpx;

						.texts {
							flex: 1;
							font-size: 28rpx;
							height: 80rpx;
							line-height: 80rpx;
							display: flex;
							justify-content: center;
							align-items: center;
						}

						input {
							flex: 1;
							font-size: 28rpx;
							height: 80rpx;
							line-height: 80rpx;
							display: flex;
							justify-content: center;
							align-items: center;
						}

						.code {
							position: absolute;
							right: 30rpx;
							top: 50%;
							color: $theme-color;
							font-size: 26rpx;
							transform: translateY(-50%);
						}
					}
				}
			}

			.logon {
				display: flex;
				align-items: center;
				justify-content: center;
				width: 100%;
				height: 86rpx;
				margin-top: 80rpx;
				background-color: $theme-color;
				border-radius: 120rpx;
				color: #FFFFFF;
				font-size: 30rpx;
			}

			.tips {
				margin: 30rpx;
				text-align: center;
				color: #999;
			}
		}
	}
</style>