<template>
  <view class="container">
    <!-- #ifdef MP-WEIXIN -->
	<image class="bg" src="https://ysrw-1395926010.cos.ap-chengdu.myqcloud.com/images/bg_login.png" mode="widthFix"></image>
    <view class="force-login-wrap">
		<view :style="{height:menuButtonInfo.height,marginTop:menuButtonInfo.top}" class="backImg" >
			<image @tap="goBack()" src="@/static/image/back.png"></image>
		</view>
		<view class="top-title">
			<view class="title-text">登录</view>
			<view class="login-notice">登录后可体验更多功能</view>
		</view>
      <view class="force-login__content">
		  <image class="bg-type" :src="current==0?'https://ysrw-1395926010.cos.ap-chengdu.myqcloud.com/images/bg_tab_login.png':'https://ysrw-1395926010.cos.ap-chengdu.myqcloud.com/images/bg_tab_login2.png'" mode="widthFix"></image>
		<view class="logintype">
			<view :class="current==0 ? 'logintype-item active':'logintype-item'" @click="changeType(0)">验证码登录</view>
			<view :class="current==1 ? 'logintype-item active':'logintype-item'" @click="changeType(1)">密码登录</view>
		</view>
		
		<view class="input-form">
			<view class="input-item">
				<input 
					class="input-field" 
					type="number" 
					v-model="phone" 
					placeholder="请输入手机号" 
					maxlength="11"
				/>
			</view>
			<view class="input-item code-input-item">
				<input 
					v-if="current == 0"
					class="input-field code-input" 
					type="number" 
					v-model="code" 
					placeholder="请输入验证码" 
					maxlength="6"
				/>
				<view v-else class="mima">
					<input
						class="input-field code-input" 
						type="text" 
						:password="showPassword"
						v-model="password" 
						placeholder="请输入密码" 
					/>
					<image @click="closePwd" :src="showPassword?'/static/image/icon_invisible.png':'/static/image/icon_visible.png'" mode="aspectFill"></image>
				</view>
				<view v-if="current == 0" class="get-code-btn" @click="getVerifyCode">
					{{ codeText }}
				</view>
			</view>
		</view>
		
		<view class="login-btn-wrap">
			<button class="login-btn" @click="handleLogin">{{ current == 0 ? '登录/注册用户' : '登录' }}</button>
		</view>
		
		<view class="tips">
			<checkbox :checked="isAgreement" @click="handleAgreement()" />
			<view class="tips-text" @click="handleAgreement()">已阅读并接受</view>
			<view class="btn" @click="openH5('/pages_user/userAgreement')">《用户注册协议》</view>
			<view class="btn" @click="openH5('/pages_user/privacyPolicy')">《隐私保护政策》</view>
		</view>
      </view>
    </view>
    <!-- #endif -->
  </view>
</template>

<script>
import { loginByMiniApp, getUserInfo, loginByMp } from '@/api/user'
import { loginByCode, loginByPassword, sendLoginVerifyCode } from '@/api/login'
export default {
	data() {
		return {
			code:null, // 微信登录code
			isAgreement:false,
			current:0, // 0-验证码登录 1-密码登录
			menuButtonInfo:{},
			phone:'', // 手机号
			code:'', // 验证码
			password:'', // 密码
			codeText:'获取验证码', // 验证码按钮文字
			countdown:0, // 倒计时
			countdownTimer:null, // 倒计时定时器
			showPassword:true ,// 是否显示密码
			companyUserId:null,
			companyId:null
		}
	},
	computed: {
	},
	onLoad(option) {
		
		this.getMenuButtonInfo()
		if(option.scene){
			const decodedStr = decodeURIComponent(option.scene);
			const result = {};
			decodedStr.split(",").forEach(item => {
			  const [key, value] = item.split("=");
			  result[key] = value;
			});
			console.log(result)
			this.companyUserId=result.cuid
			this.companyId=result.cid
			//console.log('this.companyUserId',this.companyUserId)
		}
		// #ifdef MP-WEIXIN
		uni.$on('refreshLogin', () => {
			uni.navigateBack({
				delta:1
			})
		})
		//选获取CODE，防止后请求的时候腾讯服务端未同步报错
		//this.getCode();
		// #endif
	 
	},
	onUnload() {
		// 清除倒计时
		if(this.countdownTimer) {
			clearInterval(this.countdownTimer);
			this.countdownTimer = null;
		}
	},
	mounted() {
    
	},
	methods: {
		closePwd(){
			this.showPassword=!this.showPassword
		},
		// 获取胶囊按钮布局参数
		getMenuButtonInfo() {
			// 微信小程序API（Uniapp可直接用uni.getMenuButtonBoundingClientRect）
			const menuBtn = uni.getMenuButtonBoundingClientRect();
			if (menuBtn) {
		
				this.menuButtonInfo = {
					top: menuBtn.top + 'px', // 胶囊顶部距离
					height: menuBtn.height + 'px', // 胶囊高度
					centerY: (menuBtn.top + menuBtn.height / 2) + 'px', // 胶囊垂直居中Y坐标
					right: menuBtn.right + 'px' // 胶囊右侧距离
				};
			}
		},
		changeType(index) {
			this.current = index;
			// 切换时清空输入
			if(index == 0) {
				this.password = '';
			} else {
				this.code = '';
			}
		},
		// 返回主页
		goBack() {
			uni.navigateBack({
				delta: 1
			});
		},
		// 获取验证码
		async getVerifyCode() {
			if(this.countdown > 0) {
				return;
			}
			if(!this.phone) {
				uni.showToast({
					icon:'none',
					title: "请输入手机号",
				});
				return;
			}
			if(!/^1[3-9]\d{9}$/.test(this.phone)) {
				uni.showToast({
					icon:'none',
					title: "请输入正确的手机号",
				});
				return;
			}
			try {
				uni.showLoading({
					title:"发送中..."
				});
				const res = await sendLoginVerifyCode({ phone: this.phone })
				uni.hideLoading();
				
				if(res.code === 200) {
					uni.showToast({
						icon:'success',
						title: "验证码已发送",
					});
					// 开始倒计时
					this.countdown = 60;
					this.codeText = this.countdown + '秒重新获取';
					this.countdownTimer = setInterval(() => {
						this.countdown--;
						this.codeText = this.countdown + '秒重新获取';
						if(this.countdown <= 0) {
							clearInterval(this.countdownTimer);
							this.countdownTimer = null;
							this.codeText = '获取验证码';
						}
					}, 1000);
				} else {
					uni.showToast({
						icon:'none',
						title: res.msg || "发送验证码失败",
					});
				}
			} catch (e) {
				uni.hideLoading();
				console.error('发送验证码失败', e);
				uni.showToast({
					icon:'none',
					title: "发送验证码失败",
				});
			}
		},
		// 登录
		handleLogin() {
			if(!this.isAgreement) {
				uni.showToast({
					icon:'none',
					title: "请先同意协议后再登录",
				});
				return;
			}
			if(!this.phone) {
				uni.showToast({
					icon:'none',
					title: "请输入手机号",
				});
				return;
			}
			if(!/^1[3-9]\d{9}$/.test(this.phone)) {
				uni.showToast({
					icon:'none',
					title: "请输入正确的手机号",
				});
				return;
			}
			
			if(this.current == 0) {
				// 验证码登录
				if(!this.code) {
					uni.showToast({
						icon:'none',
						title: "请输入验证码",
					});
					return;
				}
				this.loginByCode();
			} else {
				// 密码登录
				if(!this.password) {
					uni.showToast({
						icon:'none',
						title: "请输入密码",
					});
					return;
				}
				this.loginByPassword();
			}
		},
		// 验证码登录
		async loginByCode() {
			try {
				uni.showLoading({
					title:"登录中..."
				});
				const info={
					phone: this.phone,
					code: this.code,
					loginType:2,
				}
				//console.log('this.companyUserId',this.companyUserId,this.companyId)
				if(this.companyId!=null && this.companyUserId!=null){
					info.companyId=this.companyId,
					info.companyUserId=this.companyUserId
				}
				const res = await loginByCode(info);
				uni.hideLoading();
				if(res.code === 200) {
					// 保存token和用户信息
					if(res.data.token) {
						uni.setStorageSync('AppToken', res.data.token);
					}
					if(res.data.docker) {
						uni.setStorageSync('userInfo', JSON.stringify(res.data.docker));
					}
					uni.showToast({
						icon:'success',
						title: "登录成功",
					});
					uni.$emit('refreshLogin');
					var data= res.data.docker
					setTimeout(() => {
						if(data.status==4){
							uni.navigateTo({
								url: '/pages_user/certification'
							})
						}else{
						if(this.companyId!=null && this.companyUserId!=null){
								uni.switchTab({
									url: '/pages/home/index',
								})
							}else{
								uni.navigateBack({
									delta: 1
								});
							}
						}
					}, 500);
				} else {
					uni.showToast({
						icon:'none',
						title: res.msg || "登录失败",
					});
				}
			} catch (e) {
				uni.hideLoading();
				console.error('登录失败', e);
				uni.showToast({
					icon:'none',
					title: "登录失败",
				});
			}
		},
		// 密码登录
		async loginByPassword() {
			try {
				uni.showLoading({
					title:"登录中..."
				});
				console.log('---------------')
				const res = await loginByPassword({ 
					phone: this.phone, 
					password: this.password,
					loginType:1
				});
				uni.hideLoading();
				if(res.code === 200) {
					// 保存token和用户信息
					if(res.data.token) {
						uni.setStorageSync('AppToken', res.data.token);
					}
					if(res.data.docker) {
						uni.setStorageSync('userInfo', JSON.stringify(res.data.docker));
					}
					uni.showToast({
						icon:'success',
						title: "登录成功",
					});
					uni.$emit('refreshLogin');
					var data= res.data.docker
					setTimeout(() => {
						if(data.status==4){
							uni.navigateTo({
								url: '/pages_user/certification'
							})
						}else{
							uni.navigateBack({
								delta: 1
							});
						}
					}, 500);
				} else {
					uni.showToast({
						icon:'none',
						title: res.msg || "登录失败",
					});
				}
			} catch (e) {
				uni.hideLoading();
				console.error('登录失败', e);
				uni.showToast({
					icon:'none',
					title: "登录失败",
				});
			}
		},
		checkWeixin(){
			var ua = window.navigator.userAgent.toLowerCase();
			if (ua.match(/micromessenger/i) == 'micromessenger') {
				return true;
			} else {
				return false;
			}
		},
		//URL地址是否存在CODE
		getUrlCode(name) {
			return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ''])[1]
				.replace(/\+/g, '%20')) || null
		},
		//获取微信CODE
		getWxCode() {
			//在微信公众号请求用户网页授权之前，开发者需要先到公众平台官网中的“开发 - 接口权限 - 网页服务 - 网页帐号 - 网页授权获取用户基本信息”的配置选项中，修改授权回调域名。请注意，这里填写的是域名（是一个字符串），而不是URL，因此请勿加 http:// 等协议头； 
			//http://shequ.natapp1.cc/#/pages/index/index?deviceId=8
			var appId="wx40593595e62f61ad";
			var url="http://h5.yjf.runtzh.com";
			window.location.href ='https://open.weixin.qq.com/connect/oauth2/authorize?appid='+appId+'&redirect_uri=' +encodeURIComponent(url+"/#/pages/auth/wxLogin") +'&response_type=code&scope=snsapi_userinfo&state=JeffreySu-954&connect_redirect=1#wechat_redirect';
			//console.log('https://open.weixin.qq.com/connect/oauth2/authorize?appid='+appId+'&redirect_uri=' +encodeURIComponent("http://shequ.natapp1.cc/#/pages/index/index?deviceId="+this.deviceId) +'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect')
			// redirect_uri是授权成功后，跳转的url地址，微信会帮我们跳转到该链接，并且通过？的形式拼接code
		},
		handleAgreement(){
			this.isAgreement=!this.isAgreement;
		},
		openH5(url){
			// var requestPath = uni.getStorageSync('requestPath');
			// uni.setStorageSync('url',requestPath+url);
			uni.navigateTo({
				url: url
			})
		},
		getCode(){
			var that=this;
			this.utils.getProvider()
			.then(provider => {
				console.log('当前的环境商',provider)
				if (!provider) {
				  reject()
				}
				// uni登录
				uni.login({
					provider: provider,
					success: async loginRes => {
						that.code = loginRes.code
					}
				})
			})
			.catch(err => {
				
			})
		},
		// 微信用户手机号登录
		phoneLogin(e) {
			var that=this;
			if(!this.isAgreement){
				uni.showToast({
					icon:'none',
					title: "请先同意协议后再登录",
				});
				return false;
			}
			uni.showLoading({
				title:"处理中..."
			})
			console.log(e,"e")
			if (e.mp.detail.errMsg == 'getPhoneNumber:ok') {
				this.utils.getProvider()
				.then(provider => {
					console.log('当前的环境商',provider)
					if (!provider) {
					  reject()
					}
					// uni登录
					uni.login({
						provider: provider,
						success: async loginRes => {
							console.log(loginRes)
							let code = loginRes.code // 获取开发code
							var userCode=uni.getStorageSync('userCode');
							loginByMiniApp({
							   encryptedData: e.mp.detail.encryptedData,
							   iv: e.mp.detail.iv,
							   code: code,
							   userCode:userCode
							})
							.then( res => {
								if(res.code==200){
									uni.hideLoading();
									uni.showToast({
										icon:'none',
										title: "登录成功",
									});
									uni.setStorageSync('AppToken',res.token);
									uni.setStorageSync('userInfo',JSON.stringify(res.user));
									uni.hideLoading()
									//that.getUserInfo()
									uni.$emit('refreshLogin');
									uni.navigateBack({
										delta:1
									})
								}
								else{
									uni.hideLoading();
									uni.showToast({
										icon:'none',
										title: "授权登录失败,请重新登录",
									});
								}
							   
							 })
							 .catch(error => {
								console.log(error)
								uni.hideLoading();
								uni.showToast({
									icon:'none',
									title: "登录接口调用失败",
								});
							 })
							 
						}
					})
				})
				.catch(err => {
					uni.showToast({
						icon:'none',
						title: err,
					});
				})
				 
			} else {
				uni.showToast({
					title: '已拒绝授权',
					icon: 'none',
					duration: 2000,
				})
			}
		},
		back() {
			uni.switchTab({
				url: '/pages/home/index'
			});
			// uni.navigateBack()
		}
	}
}
</script>

<style lang="scss">
.container {
  flex: 1;
  padding:0 24rpx;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  position: relative;
  .bg {
  	width: 100%;
  	position: absolute;
  	top: 0;
  	left: 0;
  }
  .backImg{
	  display: flex;
	  align-items: center;
	  image{
		  width: 40rpx;
		  height: 40rpx;
	  }
	 
	  margin-left: 32rpx;
	  // position: absolute;
	  // left: 30rpx;
	  // z-index: 100;
  }
}

.force-login-wrap {
  width: 100%;
  height: 100vh;
  position: relative;

  .top-title {
    padding:0 32rpx;
    text-align: left;
    margin-top: 20rpx;
    .title-text {
      font-size: 56rpx;
      font-family: PingFang SC;
      font-weight: bold;
      color: #000000;
      margin-bottom: 20rpx;
    }

    .login-notice {
      font-size: 26rpx;
      font-family: PingFang SC;
      font-weight: 400;
      color: #999999;
      line-height: 36rpx;
    }
  }

  .force-login__content {
	  margin-top: 54rpx;
    padding:0 32rpx;
	position: relative;
	.bg-type{
		width: 100%;
		position: absolute;
		top: 0;
		left: 0;
	}
    .logintype {
      display: flex;
      margin-bottom: 66rpx;
      border-bottom: 2rpx solid #f0f0f0;
     
      .logintype-item {
        flex: 1;
        text-align: center;
       padding-top:36rpx;
	   padding-bottom: 48rpx;
       font-family: PingFang SC, PingFang SC;
       font-weight: 400;
       font-size: 32rpx;
       color: #666666;
        position: relative;
        
        &.active {
         font-size: 36rpx;
         color: #333333;
          font-weight: 600;
          &::after {
            content: '';
            position: absolute;
            bottom: 30rpx;
            left: 50%;
            transform: translateX(-50%);
            width: 52rpx;
            height: 6rpx;
            background: #388BFF;
            border-radius: 42rpx;
          }
        }
      }
    }
    
    .input-form {
      margin-bottom: 60rpx;
      
      .input-item {
        background: #FFFFFF;
        border-radius: 16rpx;
        padding: 30rpx 40rpx;
        margin-bottom: 48rpx;
        box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.04);
        &::last-child{
			margin-bottom:0
		}
        .input-field {
          width: 100%;
          font-size: 30rpx;
          font-family: PingFang SC;
          color: #333333;
          
          &::placeholder {
            color: #CCCCCC;
          }
        }
        .mima{
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: space-between;
			image{
				width: 32rpx;
				height: 32rpx;
			}
		}
        &.code-input-item {
          display: flex;
          align-items: center;
          
          .code-input {
            flex: 1;
          }
          
          .get-code-btn {
            font-size: 28rpx;
            font-family: PingFang SC;
            font-weight: 500;
            color: #388BFF;
            padding-left: 20rpx;
            border-left: 2rpx solid #f0f0f0;
            white-space: nowrap;
          }
        }
      }
    }
    
    .login-btn-wrap {
      margin-bottom: 40rpx;
       margin-top:140rpx;
      .login-btn {
        width: 100%;
        height: 88rpx;
        background: rgba(56, 139, 255, 1);
        border-radius: 44rpx;
        font-size: 32rpx;
        font-family: PingFang SC;
        font-weight: 500;
        color: #FFFFFF;
        border: none;
        display: flex;
        align-items: center;
        justify-content: center;
        &::after {
          border: none;
        }
      }
    }
  }
}
.tips{
	display: flex;
	justify-content: center;
	align-items: center;
	font-size: 24rpx;
	color: #666666;
	flex-wrap: nowrap;
	padding: 0 60rpx;
	
	checkbox{
		margin-right: 10rpx;
		flex-shrink: 0;
	}
	
	.tips-text{
		margin-right: 4rpx;
		white-space: nowrap;
	}
	
	.btn{
		color:#388BFF;
		margin: 0 2rpx;
		white-space: nowrap;
	}
}


.wx-login{
	background: rgba(0,0,0,0.7);
	z-index: 99999;
	position: fixed;
	top: 0;
	left: 0;
	height: 100%;
	width: 100%;
	display: flex;
	align-items: center;
	justify-content: center;
	.form{
		border-radius: 20rpx;
		padding: 60rpx 30rpx;
		width: 500upx;
		height: 300upx;
		background-color: #fff;
		.title{
			font-size: 32upx;
			font-family: PingFang SC;
			font-weight: bold;
			
		}
		.desc{
			font-size: 28upx;
			margin: 60upx 0upx 60upx 0upx;
			font-family: PingFang SC;
			font-weight: 500;
		}
		.btn-box{
			margin-top: 30rpx;
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: center;
			
			.btn{
				display: flex;
				align-items: center;
				justify-content: center;
				margin-left: 10upx;
				width: 50%;
				height: 80rpx;
				border-radius: 5rpx;
				background-color: #0bb3f2;
				font-size: 30rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #fff;
				position: relative;
			}
			.btn-close{
				margin-right: 10upx;
				width: 50%;
				height: 80rpx;
				border-radius: 5rpx;
				border: 2rpx solid #0bb3f2;
				background: none;
				font-size: 30rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #0bb3f2;
			}
		}
	}
}
.auth_btn{
	width: 100%;
	height: 100%;
	top:0upx;
	position: absolute;
	opacity:0.0;
}
</style>
