<template>
	<view class="login_register">
		<view class="nav-bar" style="position: relative;">
			<image style="display: block;width: 100%;height: 100%;" :src="myTopBgSrc"></image>
		</view>
		<view class="handle-area">
			<view class="handle-type">
				<text class="typeText" :class="{active:isPassword}" @click="changeLogType('password')">密码登录</text>
				<text class="typeText" :class="{active:isMessage}" @click="changeLogType('message')">验证码登录</text>
			</view>
			<view class="login-area" v-if="isPassword">
				<form style="display: block;" @submit="formSubmit">
					<view class="login-item">
						<image class="login-icon" src="../../static/login/avatar.png" mode=""></image>
						<input placeholder-style="color: #2c6fd9;" style="color: #2c6fd9;" class="loginItemInput"
							type="text" name="username" placeholder="请输入您的账号" />
					</view>
					<view class="login-item">
						<image class="login-icon" src="../../static/login/password.png" mode=""></image>
						<input placeholder-style="color: #2c6fd9;" style="color: #2c6fd9;" class="loginItemInput"
							type="text" name="password" password placeholder="请输入您的密码" />
					</view>
					<view class="privacy">
						<view class="privacyIn">
							<u-checkbox-group>
								<u-checkbox @change="checkboxChange" v-model="checkedShow"></u-checkbox>
							</u-checkbox-group>
							<view class="privacyCon">
								我已阅读并同意《<text style="color: #2d8cff;" @click="agreementFn(1)">用户协议</text>》和《<text
									style="color: #2d8cff;" @click="agreementFn(2)">隐私政策</text>》
							</view>
						</view>
					</view>
					<view class="">
						<button type="default" form-type="submit" class="login-btn">立即登录</button>
					</view>
				</form>
			</view>
			<view class="login-area" v-if="isMessage">
				<form style="display: block;" @submit="formSubmit2">
					<view class="login-item">
						<image class="login-icon" src="../../static/login/avatar.png" mode=""></image>
						<input placeholder-style="color: #2c6fd9;" style="color: #2c6fd9;" class="loginItemInput"
							type="text" name="phone" v-model="phoneNumber" placeholder="请输入手机号" />
					</view>
					<view class="login-item">
						<image class="login-icon" src="../../static/login/password.png" mode=""></image>
						<input placeholder-style="color: #2c6fd9;" style="color: #2c6fd9;" class="loginItemInput"
							type="text" name="code" placeholder="请输入验证码" />
						<button class="getMessageCode" @click="getCode">{{codeTips}}</button>
					</view>
					<u-verification-code seconds="30" ref="uCode" @change="codeChange"></u-verification-code>
					<view class="privacy">
						<view class="privacyIn">
							<u-checkbox-group>
								<u-checkbox @change="checkboxChange" v-model="checkedShow"></u-checkbox>
							</u-checkbox-group>
							<view class="privacyCon">
								我已阅读并同意《<text style="color: #2d8cff;" @click="agreementFn(1)">用户协议</text>》和《<text
									style="color: #2d8cff;" @click="agreementFn(2)">隐私政策</text>》
							</view>
						</view>
					</view>
					<view class="">
						<button type="default" form-type="submit" class="login-btn">立即登录</button>
					</view>
				</form>
			</view>
			<view class="wxBig">
				<view class="Wxtitle">
					<view class="WxtitleIn">访客注册</view>
				</view>
				<view class="registerWrap">
					<view class="visitorReg" @click="userRegister('visitor')">
						<image src="/static/login/userRegister.png" mode=""></image>
						<text>访客</text>
					</view>
					<view class="driverRegWrap">
						<view class="driverReg" @click="userRegister('driver')">
							<image src="/static/login/driver.png" mode=""></image>
						</view>
						<text>司机</text>
					</view>
					
				</view>
			</view>
		</view>
		<u-popup v-model="agreement" mode='center' :mask='true' border-radius='20' width='85%' height='75%'
			:closeable='true'>
			<view style="padding: 30rpx;" v-html="content">{{content}}</view>
		</u-popup>
	</view>
</template>
<script>
	var that;
	export default {
		data() {
			return {
				wxcode: null,
				agreement: false,
				checkedShow: true,
				key: "",
				img: "",
				username: '',
				password: '',
				phoneNumber: '',
				message: '',
				code: "",
				isShow: true,
				myTopBgSrc: require("../../static/login/my-bg.jpg"),
				content: '',
				userContent: '',
				privacyContent: '',
				wxShow: false,
				isPassword: true,
				isMessage: false,
				codeTips: "获取验证码",
				testUrl: 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf7d6140f507466be&redirect_uri=http%3A%2F%2Fqyjy.ctc-zc.com&response_type=code&scope=snsapi_base#wechat_redirect',

			}
		},
		onLoad() {
			that = this;
		},
		methods: {
			checkboxChange(e) {
				uni.setStorageSync('privacyShow', e.value)
			},
			//第三方登录
			loginFn() {
				if (that.checkedShow == false) {
					uni.showToast({
						title: '请勾选用户协议和隐私政策',
						icon: 'none',
						duration: 2000
					})
					return false;
				}
				uni.login({
					provider: 'weixin',
					success(res) {
						if (res.authResult.unionid) {
							appLogin(res.authResult.unionid).then(res1 => {
								console.log(res1)
								if (res1.statusCode == 200) {
									if (res1.data.massage == 1) {
										uni.navigateTo({
											url: 'BangWx?unionid=' + res.authResult.unionid
										})
									} else {
										uni.setStorageSync('my_token', res1.data.oAuth2AccessToken
											.access_token);
										that.updateCidFn(res1.data.userName);
									}
								} else {
									uni.showToast({
										title: '登录失败',
										duration: 2000,
										icon: 'none',
									})
								}

							}).catch(err => {
								console.log(err)
								uni.showToast({
									title: "请求失败",
									icon: 'none'
								})

							})
						} else {
							uni.showToast({
								title: '登录失败请重新登录',
								duration: 2000,
								icon: 'none',
							})
						}
					}
				})

			},
			mpLogin() {
				// #ifdef H5
				this.getWxCode()
				// #endif
				// #ifdef MP-WEIXIN
				uni.showLoading({
					title: '微信登录中...',
					mask: true
				})
				uni.login({
					provider: 'weixin',
					success: (loginRes) => {
						this.$u.api.wxmplogin({
							code: loginRes.code
						}).then(res => {
							this.$u.vuex('vuex_token', res.access)
							this.$u.api.userInfo().then(res => {
								uni.hideLoading()
								uni.showToast({
									title: "登录成功",
									icon: "none"
								})
								uni.reLaunch({
									url: "/pages/home/home"
								})
								this.$u.vuex('vuex_user', res)
								// 修改资源请求地址
								// this.$u.vuex('vuex_user.avatar', this.vuex_user.avatar +
								// 	'?token=' + this.vuex_token)
							})
						}).catch(e => {
							uni.setStorageSync('wxmp_openid', e.data.wxmp_openid)
							uni.hideLoading()
							uni.showToast({
								title: "暂未绑定微信!",
								icon: "none"
							})
						})
					}
				});
				// #endif
			},
			// 获取code
			// 先判断url中有没有code，如果有code，表明已经授权，如果没有code，跳转微信授权链接
			getWxCode() {
				// 截取地址中的code，如果没有code就去微信授权，如果已经获取到code了就直接把code传给后台获取openId
				let code = this.getUrlCode('code')
				if (code === null || code === '') {
					window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + this.vuex_appid +
						'&redirect_uri=' + encodeURIComponent(this.vuex_login) +
						'&response_type=code&scope=snsapi_base&state=1#wechat_redirect'
					// redirect_uri是授权成功后，跳转的url地址，微信会帮我们跳转到该链接，并且通过？的形式拼接code，这里需要用encodeURIComponent对链接进行处理。
					// 如果配置参数一一对应，那么此时已经通过回调地址刷新页面后，你就会再地址栏中看到code了。
					// http://127.0.0.1/pages/views/profile/login/login?code=001BWV4J1lRzz00H4J1J1vRE4J1BWV4q&state=1
				} else {
					this.wxcode = code
					this.wxcodeLogin()
				}
				// }
			},

			updateCidFn(username) {
				var data = {
					userCid: uni.getStorageSync('setcid'),
					username: username
				}
				updateCid(data).then(res => {
					console.log(res, 'zhiixngle ')
					if (res.statusCode == 200) {
						uni.showToast({
							title: '登录成功',
							duration: 2000,
							icon: 'none',
						})
						setTimeout(() => {
							uni.reLaunch({
								url: '../../index/index'
							})
						}, 2000)
					}
				}).catch(err => {
					uni.showToast({
						title: '请求失败',
						icon: 'none'
					})
				})
			},
			//检查form表单是否填写完整
			checkedParams(obj) {
				/*
				Azuma
				1234qwer
				*/
				if (obj.username == "" || obj.username == undefined || obj.username == null) {
					myShowToast('用户名不能为空');
					return false;
				};
				if (obj.password == "" || obj.password == undefined || obj.password == null) {
					myShowToast('密码不能为空');
					return false;
				};
				if (that.checkedShow == false) {
					myShowToast('请勾选用户协议和隐私政策');
					return false;
				}

				function myShowToast(text) {
					uni.showToast({
						title: text,
						icon: 'none'
					})
				};
				return true;
			},
			changeLogType(index) {
				if (index === 'password') {
					this.isPassword = true;
					this.isMessage = false;
				} else {
					this.isPassword = false;
					this.isMessage = true;
				}
			},
			userRegister(type){
				let params = `?type=${type}`;
				uni.navigateTo({
					url: '/pages/login/userRegister'+params
				})
			},
			ranStr(e) { 
				//形参e,需要产生随机字符串的长度   
				//如果没有传参，默认生成32位长度随机字符串
			    e = e || 32;
			    //模拟随机字符串库
			    var t = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz0123456789",
			    a = t.length,//字符串t的长度，随机数生成最大值
			    n = "";
			    for (let i = 0; i < e; i++) {
			    	//随机生成长度为e的随机字符串拼接
			        n += t.charAt(Math.floor(Math.random() * a));
			    }
			    //返回随机组合字符串
			    return n
			},
			//获取客户端ID
			getClientId() {
				//获取客户端ID和版本号
				var clientid = '';
				// #ifdef APP-PLUS
				// 苹果系统
				plus.device.getInfo({
					success: function(e) {
						clientid = e.uuid;
						uni.setStorageSync('clientid', clientid);
					},
					fail: function(e) {
						console.log(e);
					}
				});
				// 安卓系统
				plus.device.getAAID({
					success: function(e) {
						clientid = e.aaid;
						console.log(clientid);
						uni.setStorageSync('clientid', clientid);
					},
					fail: function(e) {
						console.log(e);
					}
				});
				//老版本、安卓模拟器
				if (clientid == '') {
					clientid = plus.device.uuid;
					uni.setStorageSync('clientid', clientid);
				}
				// #endif
				return clientid;
			},

			formSubmit(e) {
				// debugger;
				uni.showLoading({
				    title: '加载中'
				});
				var that = this;
				const obj = e.target.value;
				if (!that.checkedParams(obj)) return;
				that.$u.api.login(obj).then(res => {
					 uni.hideLoading();
					that.$u.vuex('vuex_token', res.access)
					that.$u.vuex('vuex_refresh', res.refresh);
					that.getUserRange();
					that.$u.api.getUserInfo().then(user => {
						if(user.avatar){
							user.avatar = this.vuex_host + user.avatar
						}
						that.$u.vuex('vuex_user', user)
						if(user.avatar){
							user.avatar = this.vuex_host + user.avatar
						}
						let perms = [];
						for (let key in user.perms) {
						        perms.push(key);
						}
						console.log(perms);
						that.$u.vuex('vuex_perm', perms)
						})
					that.$u.api.hrmUserInfo().then(res => {
						that.$u.vuex('vuex_employee', res)
						if(res.type==='employee'){
							uni.reLaunch({
								url: '/pages/home/home_'
							})
						}else{
							//非正式员工
							if(res.id_number==''||res.photo==''||res.id_number==null||res.photo==null){
								//信息不完善，进入信息完善页面
								uni.reLaunch({
									url: '/pages/my/myInfoChange'
								})
							}else{
								//信息完善
								if(res.type==='remployee'){
									uni.reLaunch({
										url: '/pages/home/home_'
									})
								}else{
									uni.reLaunch({
										url: '/pages/workSpace/workSpace'
									})
								}
							}
						}
					})
					// #ifdef APP-PLUS
					let secret = that.ranStr(12)
					let mySecret = {'username': obj.username, 'secret': secret}
					that.$u.api.bindSecret({secret: secret}).then(res=>{
						uni.setStorageSync('mySecret', JSON.stringify(mySecret))
						uni.reLaunch({
							url: '/pages/home/home_'
						})
					}).catch(e=>{})
					// #endif
				}).catch(e => {
					console.log(e)
				})
			},
			getUserRange(){
				let that = this;
				that.$u.api.deptList({page: 0,type__in:'rparty,dept'}).then(res => {
					let arr = [];
					let obj  = {};
					res.forEach(item=>{
						obj = {...item};
						obj.children = [];
						arr.push(obj)
					})
					let userRange0 = that.resetData(arr);
					var useArr = userRange0[0].children;
					
					for (let i=0;i<useArr.length;i++){
						let requestList = []
						requestList.push(that.$u.api.userList({page: 0,belong_dept:useArr[i].id}))
						Promise.all(requestList).then(res=>{
							res.forEach(item=>{
								item.forEach(item0=>{
									useArr[i].children.push(item0);
									if(useArr[i].children.length>0){
										let childrenArr = useArr[i].children;
										for(let j = 0;j<childrenArr.length;j++){
											let requestList2= []
											if(childrenArr[j].children){
												requestList2.push(that.$u.api.userList({page: 0,belong_dept:childrenArr[j].id}))
												Promise.all(requestList2).then(res2=>{
													res2.forEach(item=>{
														item.forEach(item1=>{
															useArr[i].children[j].children.push(item1);
														})
													})
												})
											}
											
										}
									}
								})
							})
							
						})
						
					}
					that.$u.vuex('vuex_userRange', useArr)
				})
			},
			getUser1(id) {
				that.$u.api.userList({page: 0,belong_dept:id}).then(res0 => {
					res0.forEach(item0=>{
						useArr[i].children.push(item0);
						that.$u.vuex('vuex_userRange', useArr);
						if(useArr[i].children.length>0){
							let childrenArr = useArr[i].children;
							for(let j = 0;j<childrenArr.length;j++){
								if(childrenArr[j].children){
									that.$u.api.userList({page: 0,belong_dept:childrenArr[j].id}).then(res1 => {
										res1.forEach(item1=>{
											useArr[i].children[j].children.push(item1);
											that.$u.vuex('vuex_userRange', useArr)
										})
									})
								}
								
							}
						}
					})
				})
			},
			resetData(params) {
			    let posts = [];
			    params.forEach((item) => {
			     let obj = new Object();
			     obj = {
			      ...item
			     };
			     obj.value = item.id;
			     obj.text = item.name;
			     obj.parentId = item.parent;
			     posts.push(obj);
			    });
			    let obj = posts.reduce((res, v) => ((res[v.id] = v), res), {}); //Object
			    let arr = [];
			    for (let item of posts) {
			     if (item.parentId == null) {
			      arr.push(item);
			      continue;
			     }
			     let parent = obj[item.parentId];
			     parent.children = parent.children ? parent.children : [];
			     parent.children.push(item);
			    }
			    return arr;
			   },
			formSubmit2(e) {
				var that = this;
				const obj = e.target.value;
				console.log(obj)
				that.$u.api.codeLogin(obj).then(res => {
					that.$u.vuex('vuex_token', res.access)
					that.$u.vuex('vuex_refresh', res.refresh)
					that.getUserRange();
					that.$u.api.getUserInfo().then(res => {
						if(res.avatar){
							res.avatar = this.vuex_host + res.avatar
						}
						that.$u.vuex('vuex_user', res)
						// 修改资源请求地址
					})
					// #ifdef APP-PLUS
					let secret = that.ranStr(12)
					let mySecret = {'username': obj.username, 'secret': secret}
					that.$u.api.bindSecret({secret: secret}).then(res=>{
						uni.setStorageSync('mySecret', JSON.stringify(mySecret))
					}).catch(e=>{})
					// #endif
					
					uni.reLaunch({
						url: '/pages/home/home_'
					})
				}).catch(e => {
				})
			},
			codeChange(text) {
				this.codeTips = text;
			},
			// 获取验证码
			getCode() {
				// debugger;
				console.log(this.phoneNumber)
				if (this.phoneNumber !== '') {
					if (this.$refs.uCode.canGetCode){
						uni.showLoading({
							title: '正在获取验证码',
							mask: true
						})
						this.$u.api.getCode({
							phone: this.phoneNumber
						}).then(res => {
							setTimeout(() => {
								uni.hideLoading();
								// 这里此提示会被this.start()方法中的提示覆盖
								this.$u.toast('验证码已发送');
								// 通知验证码组件内部开始倒计时
								this.$refs.uCode.start();
							}, 2000);
						})
					}
				} else {
					this.$u.toast('请输入手机号');
				}
			},
			agreementFn(e){
				if(e == 1){
					that.content = that.userContent;
					that.agreement = true;
				}else if(e == 2){
					that.content = that.privacyContent;
					that.agreement = true;
				}
			},
		}
	}
</script>

<style scoped lang="less">
	.privacy {
		width: 100%;
		height: 40rpx;
		padding: 0 40rpx;
		margin-bottom: 25rpx;

		.privacyIn {
			width: 100%;
			height: 100%;
			display: flex;
			align-items: center;

			.privacyCon {
				font-size: 26rpx;
			}
		}
	}

	.wxBig {
		width: 100%;
		height: auto;
		margin-top: 100rpx;
		display: flex;
		align-items: center;
		flex-wrap: wrap;
		justify-content: center;

		.Wxtitle {
			text-align: center;
			width: 100%;
			padding: 0 50rpx;

			.WxtitleIn {
				width: 100%;
				font-size: 26rpx;
				color: #808080;
				position: relative;
			}

			.WxtitleIn::after {
				content: '';
				width: 217rpx;
				height: 2rpx;
				background-color: #f6f6f6;
				position: absolute;
				right: 0;
				top: 18rpx;
			}

			.WxtitleIn::before {
				content: '';
				width: 217rpx;
				height: 2rpx;
				background-color: #f6f6f6;
				position: absolute;
				left: 0;
				top: 18rpx;
			}
		}

		.wx {
			width: 70rpx;
			height: 70rpx;
			margin-top: 50rpx;

			image {
				width: 100%;
				height: 100%;
			}
		}
	}

	.login_register {
		position: relative;
		background-color: #f3fbff;
		min-height: 100vh;
	}

	.nav-bar {
		height: 494rpx;
		background-color: #2cade8;
		color: #FFFFFF;
	}

	.handle-area {
		width: 705rpx;
		height: auto;
		background-color: #FFFFFF;
		border-radius: 10rpx;
		position: absolute;
		top: 340rpx;
		left: 50%;
		padding-bottom: 30rpx;
		transform: translateX(-50%);
	}

	.handle-type {
		font-family: PingFang-SC-Medium;
		font-size: 30rpx;
		line-height: 72rpx;
		color: #1e1e1e;
		padding: 62rpx;
	}

	.typeText {
		margin-right: 20rpx;
	}

	.active {
		font-size: 34rpx;
		line-height: 72rpx;
		color: #2c6fd9;
		font-weight: bold;
		position: relative;
	}

	.active::after {
		display: block;
		content: "";
		width: 100%;
		height: 6rpx;
		background-color: #2c6fd9;
		border-radius: 3rpx;
		position: absolute;
		left: 50%;
		bottom: -8rpx;
		transform: translateX(-50%);
	}

	.login-item {
		width: 635rpx;
		height: 88rpx;
		border-radius: 88rpx;
		margin: 0 auto;
		background-color: #ebf6ff;
		padding-left: 72rpx;
		box-sizing: border-box;
		position: relative;
		margin-bottom: 56rpx;
	}

	.loginItemInput {
		border-radius: 0 88rpx 88rpx 0;
	}

	.code-img-item {
		padding-left: 72rpx;
	}

	.login-item .login-icon {
		width: 22rpx;
		height: 28rpx;
		position: absolute;
		top: 50%;
		left: 35rpx;
		transform: translateY(-50%);
	}

	.login-item input {
		height: 100%;
		line-height: 88rpx;
		font-family: PingFang-SC-Medium;
		font-size: 26rpx;
	}

	.my-code-input {
		width: 300rpx;
	}

	.code-img {
		width: 155rpx;
		height: 53rpx;
		position: absolute;
		top: 50%;
		right: 20rpx;
		transform: translateY(-50%);
		background-color: #EEEEEE;
	}

	.getMessageCode {
		width: fit-content;
		position: absolute;
		top: 10%;
		right: 20rpx;
		height: 80%;
		color: #ffffff;
		font-size: 26rpx;
		border-color: #19be6b;
		background-color: #19be6b;
		z-index: 100;
		border-radius: 36rpx !important;
	}

	.login-btn,
	.register-btn {
		width: 635rpx;
		height: 88rpx;
		border-radius: 88rpx;
		margin: 0 auto;
		background-color: #1d7ef3;
		font-family: AdobeHeitiStd-Regular;
		font-size: 30rpx;
		line-height: 88rpx;
		color: #ffffff;
	}

	.to-login {
		font-family: AdobeHeitiStd-Regular;
		font-size: 24rpx;
		line-height: 72rpx;
		color: #2c6fd9 !important;
		border: none !important;
		margin-top: 20rpx;
	}

	.code-item {
		position: relative;
	}

	.my-code {
		width: 376rpx;
	}

	.code {
		width: 155rpx;
		height: 53rpx;
		background-color: #0075ff;
		border-radius: 27rpx;
		font-family: PingFang-SC-Medium;
		font-size: 20rpx !important;
		line-height: 53rpx;
		color: #fefeff;
		position: absolute;
		top: 50%;
		right: 20rpx;
		transform: translateY(-50%);
		padding-left: 12rpx;
		padding-right: 12rpx;
	}
	.registerWrap{
		display: flex;
		margin-top: 40upx;
	}
	.visitorReg{
		margin-right: 50upx;
	}
	.visitorReg,.driverRegWrap{
		display: flex;
		text-align: center;
		flex-direction: column;
	}
	.visitorReg>image{
		width: 90upx;
		height: 90upx;
	}
	.driverReg{
		width: 80upx;
		height: 80upx;
		border-radius: 40upx;
		background: #0075ff;
		margin-bottom: 8upx;
	}
	.driverReg>image{
		width: 46upx;
		height: 46upx;
		margin: 16upx;
	}
</style>
