<template>
	<!-- 登录 -->
	<view class="container flex-items-plus flex-column" :style="{backgroundImage:`url(${$imgUrl('/homePhoto.png')})`}">
		<global-loading />
		<view style="height: 100vh;width: 100%;position: fixed;bottom: 0;left: 0;">
			<view style="width: 45%;margin: 0 auto;margin-top: 15vh;">
				<image src="../../static/login/logo1.png" style="width: 100%;" mode="widthFix"></image>
			</view>

			<view style="width:60%;margin: 0 auto;">
				<image src="../../static/login/logo2.png" style="width: 100%;" mode="widthFix"></image>
			</view>
			<!-- 填写区 -->
			<view class="input-info" style="margin-top: 5vh;">
				<view class="info">
					<view class="info-icon">
						<image src="../../static/login/icon1.png" mode="heightFix"></image>
					</view>
					<input v-model="loginQuery.account" type="tel" maxlength='11' placeholder="请输入您的手机号" />
					<view class="more"></view>
				</view>
				<view class="info">
					<view class="info-icon">
						<image src="../../static/login/icon2.png" mode="heightFix"></image>
					</view>

					<input v-model="loginQuery.code" :maxlength="6" type="tel" placeholder="请输入验证码" />
					<view class="more">
						<text class="mo" v-if="!disabled" @click="codede">获取验证码</text>
						<text class="mo" v-else>{{text}}</text>
						<!-- <view :class="disabled === true ? 'no' : ''" :disabled="disabled" class="getcode"
							@click="codede">{{ text }}
						</view> -->
					</view>
				</view>
			</view>
			<!-- 按钮 -->
			<view class="btn-info">
				<view class="btn" @click="login">
					<text>登录</text>
				</view>
			</view>
	<!-- 		<view class="iphoneNum-box flex-row-plus flex-items">
				<view style="margin-right: 30rpx">
					<image class="loginIcon"
						src="https://jy.scjysm.asia:18086/cdwlMall/questionnaire/file/static/images/phone.png"></image>
				</view>
				<view>
					<input v-model="loginQuery.account" placeholder-class="iphoneNum-input" type="number" maxlength='11'
						placeholder="请输入您的手机号" />
				</view>
			</view>
			<view class="flex-row-plus">
				<view class="code-box">
					<view style="margin-right: 30rpx">
						<image class="loginIcon"
							src="https://jy.scjysm.asia:18086/cdwlMall/questionnaire/file/static/images/code.png">
						</image>
					</view>
					<view>
						<input v-model="loginQuery.code" :maxlength="6" placeholder-class="codeNum-input"
							placeholder="请输入验证码" />
					</view>
				</view>
				<view :class="disabled === true ? 'on' : ''" :disabled="disabled" class="getcode" @click="codede">
					{{ text }}
				</view>
			</view> -->
			<!-- <view class="mar-top-60">
				<view class="registerBut mar-top-100" @click="login">登录
				</view>
			</view> -->
			<view class="agreement">
				<u-checkbox-group @change="checkboxGroupChange" shape="circle" :label-disabled="true">
					<u-checkbox active-color="#3f9b6a" v-model="agreement" name="true">
					</u-checkbox>
				</u-checkbox-group>
				<text class="font-color-999">登录即代表同意</text>
				<text style="color: #3f9b6a;" @click="protocol('app_user_agreement')">《APP用户服务协议》</text>和
				<text style="color: #3f9b6a;" @click="protocol('app_privacy_agreement')">《APP个人隐私协议》</text>
				<!-- <image v-if="!agreement" src="../../static/images/none.png" mode="" @click="agreement=true"></image>
				<image v-else src="../../static/images/solid.png" mode="" @click="agreement=false"></image> -->
			
			</view>
		</view>
	</view>
</template>

<script>
	import sendVerifyCode from "@/mixins/SendVerifyCode";

	const NET = require('../../utils/request')
	const API = require('../../config/api')
	export default {
		data() {
			return {
				loginQuery: {
					account: '',
					code: '',
					salesId: '',
				},
				// 获取验证码
				VerifyQuery: {
					phone: ""
				},
				agreement: false,
				inviteSpell: {},
				inviteSpelltype: false,
				beforePage: undefined,
				doubleBeforePage: undefined,
				text: '获取验证码',
				disabled: false,
				remainingTime: 0, // 剩余倒计时时间
			}
		},
		mixins: [sendVerifyCode],
		onLoad(options) {
			if (options.inviteSpell == 1) {
				this.inviteSpelltype = true
				this.inviteSpell = uni.getStorageSync('inviteSpell');
			}
			this.loginQuery.salesId = uni.getStorageSync('salesId');
			var pages = getCurrentPages()
			if (pages.length >= 2) {
				this.beforePage = pages[pages.length - 2]
			}
			if (pages.length >= 3) {
				this.doubleBeforePage = pages[pages.length - 3]
			}
		},
		methods: {
			checkboxGroupChange(val) {
				if(val[0] == 'true'){
					this.agreement = true
				}else{
				this.agreement = false	
				}
				
			},
			login() {
				let phoneCodeVerification = /^[1][3-9][0-9]{9}$/;
				if (this.loginQuery.account == '') {
					uni.showToast({
						title: '请输入手机号！',
						duration: 2000,
						icon: 'none'
					});
				} else if (!phoneCodeVerification.test(this.loginQuery.account)) {
					uni.showToast({
						title: '请输入正确的手机号！',
						duration: 2000,
						icon: 'none'
					});
				} else if (this.loginQuery.code == '') {
					uni.showToast({
						title: '请获取验证码！',
						duration: 2000,
						icon: 'none'
					})
				} else if (!this.agreement) {
					uni.showToast({
						title: '请先阅读并同意《用户服务协议和个人隐私协议》',
						duration: 2000,
						icon: 'none'
					});
				} else {
					const that = this
					// uni.showLoading({
					//   mask: true,
					//   title: '正在登录...',
					//   duration: 2000,
					// });
					NET.request(API.Login, {
						phone: this.loginQuery.account,
						verificationCode: this.loginQuery.code
					}, 'POST').then(res => {
						uni.hideLoading()
						const item = res.data
						uni.setStorageSync('storage_key', item);
						if (uni.getStorageSync("salesId")) {
							let salesId = uni.getStorageSync("salesId")
							let shopId = uni.getStorageSync("shopId")
							this.bindSalesCustomer(salesId, shopId)
							uni.removeStorageSync('salesId');
							uni.removeStorageSync('shopId');
						}

						// 购物车右上角数量
						NET.request(API.ShoppingCart, {}, 'GET').then(resCart => {
							let cartNum = 0
							resCart.data.forEach(shopItem => {
								shopItem.skus.forEach(goodsItem => {
									cartNum += goodsItem.number
								})
							})
							if (cartNum > 0) {
								uni.setTabBarBadge({
									index: 2,
									text: cartNum.toString()
								})
							}
							console.log(cartNum)
							uni.setStorageSync('allCartNum', cartNum)
						})
						if (this.inviteSpelltype == true) {
							setTimeout(function() {
								uni.reLaunch({
									url: '../../pages_category_page1/goodsModule/inviteSpell?collageId=' +
										this.inviteSpell.collageId + '&orderId=' + this.inviteSpell
										.orderId + '&type=0' + '&productId=' + this.inviteSpell
										.productId + '&skuId=' + this.inviteSpell.skuId
								})
								uni.removeStorageSync('inviteSpell');
							}, 2000)
						} else {
							if (that.beforePage && that.beforePage.route !==
								'pages_category_page2/userModule/accountLogin' &&
								that.beforePage.route !== 'pages_category_page2/userModule/login' &&
								that.beforePage.route !== 'pages_category_page2/userModule/register') {
								console.log(19)
								uni.navigateBack({
									delta: 1
								})
							} else if (that.doubleBeforePage && that.doubleBeforePage.route !==
								'pages_category_page2/userModule/accountLogin' &&
								that.doubleBeforePage.route !== 'pages_category_page2/userModule/login' &&
								that.doubleBeforePage.route !== 'pages_category_page2/userModule/register') {
								uni.navigateBack({
									delta: 2
								})
							} else {
								NET.request(API.GetUser, {}, 'GET').then(res => {
									let MsgList = {
										username: res.data.name,
										userId: res.data.buyerUserId,
										phoneNumber: res.data.phone,
										createTime: this.getCurrentDateTime(),
									}
									NET.request(API.DengJi, MsgList, 'POST').then(res => {

									})
								})
								setTimeout(function() {
									uni.switchTab({
										url: '../../pages/tabbar/user/index'
									})
								}, 600)
							}
						}
					}).catch(res => {
						console.log('Login failed')
						console.dir(res)
						uni.hideLoading()
						uni.showToast({
							title: res.data.message,
							duration: 2000,
							icon: 'none',
						});
					})
				}

			},
			// 获取时间
			getCurrentDateTime() {
				const now = new Date();
				const year = now.getFullYear();
				const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的，所以需要+1
				const day = String(now.getDate()).padStart(2, '0');
				const hours = String(now.getHours()).padStart(2, '0');
				const minutes = String(now.getMinutes()).padStart(2, '0');
				const seconds = String(now.getSeconds()).padStart(2, '0');

				return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			},
			// 获取验证码
			codede() {
				if (this.disabled) return
				this.getVerify()

			},
			getVerify() {
				let phoneCodeVerification = /^[1][3-9][0-9]{9}$/;
				if (this.loginQuery.account === '') {
					uni.showToast({
						title: '请输入手机号！',
						duration: 2000,
						icon: 'none'
					});
				} else if (!phoneCodeVerification.test(this.loginQuery.account)) {
					uni.showToast({
						title: '请输入正确的手机号！',
						duration: 2000,
						icon: 'none'
					});
				} else {
					this.disabled = true;
					this.remainingTime = 60;
					this.text = `${this.remainingTime}s后重试`;

					const timer = setInterval(() => {
						this.remainingTime--;
						if (this.remainingTime > 0) {
							this.text = `${this.remainingTime}s后重试`;
						} else {
							clearInterval(timer);
							this.disabled = false; // 倒计时结束，启用按钮
							this.text = '获取验证码';
						}
					}, 1000);

					this.VerifyQuery.phone = this.loginQuery.account;

					NET.request(API.verification, {
						phone: this.VerifyQuery.phone
					}, 'POST').then(res => {
						// 如果 sendCode 方法有实际用途，需要定义该方法
						// this.sendCode(); 
						console.log(res);
					}).catch(res => {
						uni.showToast({
							title: res.data.message,
							duration: 1000,
							icon: 'none'
						});
					});
				}
			},
			//绑定关系
			bindSalesCustomer(salesId, storeId) {
				if (salesId && storeId) {
					//如果已登录，静默绑定客户关系，否则跳转到登录页面
					NET.request(API.BindSalesCustomer, {
						shopId: storeId,
						distributorId: salesId
					}, 'POST').then(res => {
						uni.showToast({
							title: "绑定成功",
							icon: "none"
						})
					}).catch(res => {
						uni.showToast({
							title: res.data.message,
							icon: "none"
						})
					})

				}
			},
			// 多商户用户协议
			protocol(type) {
				uni.navigateTo({
					url: 'protocol?type=' + type
				})
			},
		}
	}
</script>

<style lang="scss">
	.container {
		position: absolute;
		left: 0;
		top: 0;
		width: 100%;
		height: 100%;
		background-size: cover;
		background-color: #FFFFFF;

		.login-logoBox {
			margin-top: -300rpx;

			.login-logo {
				width: 234rpx;
				height: 193rpx;
			}
		}

		.iphoneNum-box {
			margin-top: 100rpx;
			border-bottom: 1rpx solid #DDDDDD;
			height: 100rpx;
			width: 600rpx;

			.loginIcon {
				width: 40rpx;
				height: 53rpx;
			}

			.iphoneNum-input {
				color: #999999;
				font-size: 28rpx;
				font-weight: 400;
			}
		}

		.passwordNum-box {
			border-bottom: 1rpx solid #DDDDDD;
			height: 100rpx;
			width: 600rpx;

			.passwordNum-input {
				color: #999999;
				font-size: 28rpx;
				font-weight: 400;
				width: 346rpx;
			}
		}

		.code-box {
			border-bottom: 1rpx solid #DDDDDD;
			height: 100rpx;
			width: 360rpx;
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			align-items: center;

			.loginIcon {
				width: 44rpx;
				height: 50rpx;
			}

			.code-lab {
				width: 200rpx;
			}

			.codeNum-input {
				color: #999999;
				font-size: 28rpx;
				font-weight: 400;
			}
		}

		.getcode {
			background-color: #39be7a;
			height: 100rpx;
			width: 230rpx;
			display: flex;
			flex-direction: row;
			justify-content: center;
			align-items: center;
			margin-left: 20rpx;
			color: #FFFFFF;
		}

		.registerBut {
			background: #3f9b6a;
			color: #FFEBC4;
			height: 100rpx;
			width: 600rpx;
			text-align: center;
			line-height: 100rpx;
			margin-top: 30rpx;
		}

		.agreement {
			margin: 100rpx 50rpx;
			line-height: 50rpx;

			image {
				width: 34rpx;
				height: 34rpx;
				margin-right: 15upx;
			}
		}
	}
	/* 填写 */
	.input-info{
	  padding: 0 6%;
	  // margin: 80rpx 0 40rpx 0;
	  .info{
	    display: flex;
	    align-items:center;
	    justify-content: space-between;
	    width: 100%;
	    height: 100rpx;
		background-color: #fff;
		border-radius: 32rpx;
		margin-bottom: 40rpx;
		padding: 0 30rpx 0 40rpx;
		border: 2rpx solid rgba(15,187,89,0.1804);
	    input{
	      width: 70%;
	      height: 100%;
	      font-size: 26rpx;
	      color: #222222;
	    }
		.info-icon {
			image {
				width: 28rpx;
				height: 28rpx;
				margin-right: 20rpx;
			}
		}
	    .more{
	      display: flex;
	      align-items: center;
	      justify-content: flex-end;
	      width: 32%;
	      height: 100%;
	      .iconfont{
	        font-size: 34rpx;
	      }
	      .mo{
	        font-size: 26rpx;
	        padding-left: 20rpx;
	        // margin-left: 10rpx;
	        border-left: 2rpx solid #ccc;
	      }
	    }
	  }
	}
	/* 按钮 */
	.btn-info{
	  display: flex;
	  align-items: center;
	  justify-content: center;
	  width: 100%;
	  .btn{
	    display: flex;
	    align-items: center;
	    justify-content: center;
	    width: 88%;
	    height: 90rpx;
	    background-color:#0FBB59;
	    border-radius: 32rpx;
	    color: #FFFFFF;
	    font-size: 32rpx;
	  }
	}
</style>