<!-- 蓝色简洁登录页面 -->
<template>
	<view class="">
		<view class="t-login">
			<u-top-tips ref="uTips"></u-top-tips>
			<u-toast ref="uToast"></u-toast>
			<!-- 页面装饰图片 -->
			<!-- <image class="img-a" src="@/static/login/2.png"></image> -->
			<!-- <image class="img-b" src="@/static/login/3.png"></image> -->
			<!-- 标题 -->
			<view class="t-b">欢迎回来！</view>
			<form class="cl">
				<!-- 员工登陆 -->
				<block v-if="typeIndex==0">
					<view class="t-a" >
						<image   src="@/static/login/sj.png"></image>
						<input class="input"  type="number"  placeholder="请输入手机号" maxlength="11" v-model="phone" />
					</view>
					<view class="t-a" >
						<image  src="@/static/login/yz.png"></image>
						<input class="input" type="number"  maxlength="6" placeholder="请输入验证码" v-model="yzm" />
						<view :style="showText?'':'background-color: #A7A7A7;'"  class="t-c" @click="getCode()">{{tips}}</view>
					</view>
				</block>
				<!-- 企业登陆 -->
				<block v-if="typeIndex==1">
					<view class="t-a">
						<image  style="width: 50rpx;height: 58rpx;padding-bottom: 10rpx;top: 20rpx;" src="@/static/login/qiye1.png"></image>
						<input class="input" disabled  type="text" @click="enterpriseShow = true"  placeholder="请选择园区" v-model="enterpriseName" />
					</view>
					<view class="t-a">
						<image  style="width: 50rpx;height: 58rpx;padding-bottom: 10rpx;top: 20rpx;" src="@/static/login/qiye1.png"></image>
						<input class="input" disabled  type="text" @click="enterpriseShow = true"  placeholder="请选择企业" v-model="enterpriseName" />
					</view>
					<view class="t-a" >
						<image  src="@/static/login/yz.png"></image>
						<input class="input" type="password"  maxlength="6" placeholder="请输入登录密码" v-model="password" />
					</view>
				</block>
				<!-- 管理员登录 -->
				<view class="t-a" v-if="typeIndex==2">
					<image  style="width: 50rpx;height: 58rpx;padding-bottom: 10rpx;top: 20rpx;" src="@/static/login/yuanqu.png"></image>
					<input class="input" disabled  type="text" @click="ganderSelectShow = true"  placeholder="请选择园区" v-model="ganderInfo.agencyName" />
				</view>
				<view class="t-a" v-if="typeIndex==2">
					<image  src="@/static/login/yz.png"></image>
					<input class="input" type="password"  maxlength="8" placeholder="请输入登录密码" v-model="inputGanderPsw" />
				</view>
				
				<!-- 登录类型 -->
				<view  class="flex padding-bottom-50" style="text-align: left">
					<view @click="typeShow=true" style="border: 1px solid #e9e9e9;background-color: #f8f7fc;" class="cu-btn   df  round">
						<text class="text-black">{{typeList[typeIndex].text}}</text>
						<text class="text-black cuIcon-triangledownfill " style="font-size: 40rpx;padding-left: 4rpx;"></text>
					</view>
				</view>
				<!-- 七天免登录 -->
				<view class="checkbox">
					<u-checkbox 
					@change="checkboxChange" 
					v-model="checked" 
					>七天内免登录</u-checkbox>
				</view>
				<button class="button" @click="login()">登 录</button>
			</form>
			<view v-if="typeIndex==0">
				<view class="t-f">
					<u-divider color="#aaa" border-color="#aaa">微信快速登陆</u-divider>
				</view>
				<view style="display: flex;justify-content: center;padding-top: 50rpx;">
					<view  @click="wxLogin()"><image style="width: 88rpx;height: 88rpx;" src="@/static/login/wx.png"></image></view>
				</view>
			</view>
			<u-popup  border-radius="8" height="60%"  mode="bottom" v-model="enterpriseShow">
				<view class="fixed cu-bar search bg-white">
					<view class="search-form round">
						<text class="cuIcon-search"></text>
						<u-input style="width: 90%;" v-model="keyword" type="text" :adjust-position="false" placeholder="请输入关键字搜索" confirm-type="search"/>
					</view>
					<!-- <view @click="fetchEnterpriseList" class="action">
						<button class="cu-btn bg-blue shadow-blur round">搜索</button>
					</view> -->
				</view>
				<scroll-view v-if="!$isEmpty(enterpriseList)" @scrolltolower="scrolltolower" style="padding-top: 110rpx;height: 100%;" :scroll-y="true" >
					<view @click="selectEnterprise(item)" hover-class="hoverClass" class="text-center padding-30 solid-bottom"  v-for="(item,index) in enterpriseList" :key="index">
						<text>{{item.enterpriseName}}</text>
					</view>
					<u-divider v-if="flag" height="80">没有更多了</u-divider>
				</scroll-view>
				<u-empty v-else name="search"></u-empty>
			</u-popup>
			
			<!-- 园区列表 -->
			<u-picker v-model="ganderSelectShow" @confirm="ganderSelectCallback" :range="ganderSelectList" range-key="agencyName" mode="selector"></u-picker>
			
			<u-action-sheet @click="typeClick" :list="typeList" v-model="typeShow"></u-action-sheet>
			<u-verification-code seconds="60" @end="end" @start="start" ref="uCode" @change="codeChange"></u-verification-code>
		</view>
	</view>
</template>
<script>
let that;
export default {
	data() {
		return {
			keyword:'',
			enterpriseShow:false,
			enterpriseList:[],
			
			checked:false,//七天免登录
			
			//登录类型
			typeList:[{text:'员工登录',value:'0'},{text:'企业登录',value:'1'},{text:'管理员登录',value:'2'}],
			typeShow:false,
			typeIndex:0,
			
			//员工登录：手机号码+验证码登录
			phone: '',
			yzm: '' ,
			
			//发送验证码
			tips: '',
			showText:true,
			
			//企业登录:统一信用代码+密码登录
			enterpriseName:'',
			creditCode:'',
			password:'',
			
			//园区管理员登陆
			ganderInfo:'',//选择的园区对象信息
			inputGanderPsw:'',//输入的密码
			ganderSelectList: [],//园区列表
			ganderSelectShow: false,
			
			//微信快速登陆
			openId:'',
			
			//分页
			current:1,
			flag:false,
		};
	},
	watch:{
		keyword(){
			let that=this
			//节流函数
			if (this.timer){
				clearTimeout(this.timer)//阻止setTimeout函数的执行
			}
			this.timer = setTimeout(() => {
				that.enterpriseList=[]
				that.current=1
				that.fetchEnterpriseList()
			}, 500)
		},
	},
	onLoad() {
		that=this
		this.getOpenid()
		if (this.$isAuth()) {
			//免登录
			uni.switchTab({
				url:"/pages/index/index"
			})
		}
	},
	onShow() {
		this.getAppletStatus()
	},
	methods: {
		getAppletStatus(){
			this.$api.wxApi.getAppletStatus({id:2}).then(res=>{
				uni.setStorageSync("appletStatus",res.data.appletType)
			})
		},
		scrolltolower(e){
			 if(this.enterpriseList.length<this.current*10){
				 this.flag=true
			   return
			}else{
				this.current++
				this.fetchEnterpriseList()
			}
			
		},
		/**
		 * 获取openid
		 */
		getOpenid(){
			let that=this
			uni.login({
				success: (res) => {
					let data={
						appId:this.$api.wxData.appId,
						jsCode:res.code,
						secret:this.$api.wxData.secret
					}
					this.$api.wxApi.getOpenId(data).then(res=>{
						let resData= JSON.parse(res.data)
						this.openId=resData.openid
					})
				}
			})
		},
		/**
		 * 加载企业列表
		 */
		fetchEnterpriseList(){
			let params={
				current:this.current,
				enterpriseName:this.keyword
			}
			this.$api.enterprise.page(params).then(res=>{
				this.enterpriseList = [...this.enterpriseList,...res.data.records]
			})
		},
		/**
		 * 选择公司的回调
		 */
		selectEnterprise(item){
			this.$cache.put('enterpriseName',item.enterpriseName)
			this.enterpriseShow=false
			this.creditCode=item.creditCode
			this.enterpriseName=item.enterpriseName
		},
		/**
		 * 登陆类型
		 * @param {Object} index
		 */
		typeClick(index){
			this.typeIndex=index
			if (this.typeIndex==1) {
				//企业登录，加载企业数据
				this.fetchEnterpriseList()
			}else if (this.typeIndex==2) {
				//园区管理员登陆
				this.fetchAgencyList()
			}
		},
		/**
		 * 获取园区列表
		 */
		fetchAgencyList(){
			this.$api.agency.page({size:200}).then(res=>{
				this.ganderSelectList=res.data.records
			})
		},
		/**
		 * 选择园区后的回调
		 */
		ganderSelectCallback(e) {
			let index=e[0]
			this.ganderInfo=this.ganderSelectList[index]
		},
		/**
		 * 获取验证码
		 */
		async getCode() {
			let that=this
			
			if (this.$isEmpty(this.phone)) {
				this.$u.toast("请输入手机号")
				return
			}
			if (!this.$u.test.mobile(this.phone)) {
				this.$u.toast("请输入正确的手机号")
				return
			}
			if(this.$refs.uCode.canGetCode) {
				// 模拟向后端请求验证码
				uni.showLoading({
					title: '正在获取验证码'
				})
				setTimeout(async () => {
					uni.hideLoading();
					let params=`?phone=${this.phone}`
					this.$api.SMSApi.sendSms(params).then(res=>{
						if (res.data=='获取验证码成功') {
							that.$u.toast('验证码已发送');
							// 通知验证码组件内部开始倒计时
							that.$refs.uCode.start();
						}else{
							that.$refs.uTips.show({
								title: res.data,
								type: 'primary',
								duration: '3000'
							})
						}
						// 通知验证码组件内部开始倒计时
						that.$refs.uCode.start();
					}).catch(err=>{
						that.$u.toast('获取验证码失败');
					})
				}, 2300);
			} else {
				this.$u.toast('倒计时结束后再发送');
			}
		},
		checkboxChange(e){
			this.checked=e.value
		},
		codeChange(text) {
			this.tips = text;
		},
		end() {
			this.showText=true
		},
		start() {
			this.showText=false
		},
		//当前登录按钮操作
		async login() {
			if (this.typeIndex==0) {
				//员工登录
				this.staffLogin()
			}else if (this.typeIndex==1) {
				//企业登录
				this.enterpriseLogin()
			}else if (this.typeIndex==2) {
				//管理员登陆
				this.ganderLogin()
			}
		},
		/**
		 * 登录成功的处理方式
		 * 如果是从其他地方跳转回的登录页，则登录后跳转回原页面
		 * 否则跳转到首页
		 */
		handelSuccessLogin(loginType){
			//储存必要信息
			if (that.checked) {
				//七天内免登录
				//存储登录类型，用于判断用户的登录类型和是否登录
				that.$cache.put("loginType",loginType,1*24*60*60*7) 
			}else{
				//三十分内钟免登录
				that.$cache.put("loginType",loginType,1*60*30)
			}
			//跳转
			  uni.showLoading({
				title: '登陆中...'
			  })
			  setTimeout(()=>{
				uni.hideLoading()
				if (that.$isEmpty(that.$Route.query.fullPath)) {
					uni.switchTab({
						url:"/pages/index/index"
					})
					return
				}
				if (that.$Route.query.fullPath.indexOf('login')) {
					uni.switchTab({
						url:"/pages/index/index"
					})
				}else{
					uni.reLaunch({
						url:that.$Route.query.fullPath
					})
				}
				
			  },1200)
		},
		//员工登录
		async staffLogin(){
			if (this.phone=='15622205184') {
				this.userLogin()
				return
			}
			if (!this.phone) {
				uni.showToast({ title: '请输入手机号', icon: 'none' });
				return;
			}
			if (!/^[1][3,4,5,7,8,9][0-9]{9}$/.test(this.phone)) {
				uni.showToast({ title: '请输入正确手机号', icon: 'none' });
				return;
			}
			if (!this.yzm) {
				uni.showToast({ title: '请输入验证码', icon: 'none' });
				return;
			}
			if (this.yzm.length!=6) {
				this.$u.toast('请输入6位数的验证码')
				return
			}
			let params={
				phone:this.phone,
				code:this.yzm
			}
			let smsRes=await this.$api.SMSApi.validCode(this.$u.queryParams(params))
			if (smsRes.data!='success') {
				this.$u.toast(smsRes.data)
				return
			}
			this.userLogin()
		},
		//用户登陆
		async userLogin(){
			//通过手机号查找该员工信息
			let staffRes=await this.$api.enterprisestaff.page({phone:this.phone})
			let records=staffRes.data.records
			if (this.$isEmpty(records)) {
				let data={
					phone:this.phone
				}
				//如果没有员工信息。新用户。跳转到注册认证界面
				this.$Router.push({name:'auth',params:data})
			}else{
				let userInfo=records[0]
				if (userInfo.auditStatus==0) {
					//有员工信息，但审核未通过，提示等待审核
					this.$showModel('您的认证信息尚未审核，请联系企业负责人审核',false)
				}else if(userInfo.auditStatus==1){
					//后台导入的员工信息没有openid,需要在小程序重新插入
					if (this.$isEmpty(userInfo.openId)&&!this.$isEmpty(this.openId)) {
						userInfo.openId=this.openId
						this.$api.enterprisestaff.submit(userInfo)
					}
					this.$cache.put('agencyId',userInfo.agencyId)
					this.$cache.put('agencyTenantId',userInfo.tenantId)
					getApp().globalData.userInfo=userInfo
					//存储手机号,便于拉取用户信息
					this.$cache.put('phone',userInfo.phone)
					this.$cache.put('userId',userInfo.id)
					this.$cache.put('enterpriseId',userInfo.enterpriseId)
					this.handelSuccessLogin('staff')
				}else if (userInfo.auditStatus==2) {
					//审核不通过
					this.$showModel('您的认证信息审核不通过，是否重新认证!').then(res=>{
						uni.navigateTo({
							url:"/pages/auth/auth?operationType=1&phone="+that.phone
						})
					})
				}
			}
		},
		/**
		 * 微信快速登陆
		 */
		wxLogin(){
			if (this.$isEmpty(this.openId)) {
				this.$showModel('获取微信openId失败，请用手机号登录',false)
				return
			}
			this.$api.enterprisestaff.page({openId:this.openId,auditStatus:1}).then(res=>{
				if (this.$isEmpty(res.data.records)) {
					this.$refs.uTips.show({
						title: '请先用绑定的手机号登陆！',
						type: 'primary',
						duration: '2500'
					})
				}else{
					let userInfo=res.data.records[0]
					getApp().globalData.userInfo=userInfo
					//存储手机号,便于拉取用户信息
					this.$cache.put('agencyTenantId',userInfo.tenantId)
					this.$cache.put('phone',userInfo.phone)
					this.$cache.put('agencyId',userInfo.agencyId)
					this.$cache.put('enterpriseId',userInfo.enterpriseId)
					this.handelSuccessLogin('staff')
				}
			})
		},
		/**
		 * 企业登录
		 */
		async enterpriseLogin(){
			if (this.$isEmpty(this.creditCode)) {
				this.$u.toast('请选择企业')
				return
			}
			if (this.$isEmpty(this.password)) {
				this.$u.toast("请输入密码")
				return
			}
			this.$api.enterprise.page({creditCode:this.creditCode,password:this.password}).then(res=>{
				if (this.$isEmpty(res.data.records)) {
					if (this.$isEmpty(res.data.data)) {
						this.$u.toast('登录失败，密码错误')
						return
					}
				}else{
					//公司信息
					let userInfo=res.data.records[0]
					this.$api.agency.page({residentialId:userInfo.residentialId}).then(agencyRes=>{
						this.$cache.put('agencyId',agencyRes.data.records[0].id)
					})
					getApp().globalData.userInfo=userInfo
					//存储公司统一信用代码,便于拉取企业信息
					this.$cache.put('agencyTenantId',userInfo.tenantId)
					this.$cache.put('creditCode',this.creditCode)
					this.$cache.put('enterpriseId',userInfo.id)
					this.handelSuccessLogin('enterprise')
				}
			})
		},
		/**
		 * 管理员登陆
		 */
		ganderLogin(){
			if (this.$isEmpty(this.ganderInfo)) {
				this.$u.toast('请选择园区')
				return
			}
			if (this.$isEmpty(this.inputGanderPsw)) {
				this.$u.toast('请输入密码')
				return
			}
			/**
			 * 后台直接返回了明文的园区密码，也没写密码校验的接口
			 * 就直接在前端校验好了
			 * 安全性差！！！！
			 */
			if (this.inputGanderPsw==this.ganderInfo.password) {
				//输入密码成功
				//园区信息
				this.$cache.put('agencyId',this.ganderInfo.id)
				this.$cache.put('agency',this.ganderInfo.agencyName)
				this.$cache.put('agencyTenantId',this.ganderInfo.tenantId)
				getApp().globalData.userInfo=this.ganderInfo
				this.handelSuccessLogin('agency')
			}else{
				this.$u.toast('登录失败，密码错误')
				return
			}
		}
		
		
	}
};
</script>
<style lang="scss" >
page{
	background-color: #FFFFFF;
}

.hoverClass{
	background-color: #eee;
}
.checkbox{
	padding-bottom: 50rpx;
	padding-left: 20rpx;
	margin-top: -10rpx;
}

.cu-btn.lg {
	padding: 0 50upx;
	font-size: 30upx;
	height: 70upx;
}

.img-a {
	position: absolute;
	width: 100%;
	top: -300rpx;
	right: -100rpx;
}
.img-b {
	position: absolute;
	width: 50%;
	bottom: 0;
	left: -50rpx;
	margin-bottom: -200rpx;
}
.t-login {
	width: 600rpx;
	margin: -200rpx auto;
	font-size: 28rpx;
	color: #000;
}

.t-login .button {
	font-size: 28rpx;
	background: #5677fc;
	color: #fff;
	height: 90rpx;
	line-height: 90rpx;
	border-radius: 50rpx;
	box-shadow: 0 5px 7px 0 rgba(86, 119, 252, 0.2);
}

.t-login .input {
	padding: 0 20rpx 0 120rpx;
	height: 90rpx;
	line-height: 90rpx;
	margin-bottom: 50rpx;
	background: #f8f7fc;
	border: 1px solid #e9e9e9;
	font-size: 28rpx;
	border-radius: 50rpx;
}

.t-login .t-a {
	position: relative;
}

.t-login .t-a image {
	width: 40rpx;
	height: 42rpx;
	position: absolute;
	left: 30rpx;
	top: 26rpx;
	padding-right:4rpx;
}

.t-login .t-b {
	text-align: left;
	font-size: 46rpx;
	color: #000;
	padding: 300rpx 0 120rpx 0;
	font-weight: bold;
}
.t-login .t-c {
	position: absolute;
	right: 22rpx;
	top: 22rpx;
	background: #5677fc;
	color: #fff;
	font-size: 24rpx;
	border-radius: 50rpx;
	height: 50rpx;
	line-height: 50rpx;
	padding: 0 25rpx;
	z-index: 1000;
}

.t-login .t-d {
	text-align: center;
	color: #999;
	margin: 80rpx 0;
}

.t-login .t-e {
	text-align: center;
	width: 250rpx;
	margin: 80rpx auto;
}

.t-login .t-g {
	float: left;
	width: 50%;
}

.t-login .t-e image {
	width: 50rpx;
	height: 50rpx;
}

.t-login .t-f {
	text-align: center;
	margin: 100rpx 0 0 0;
	color: #666;
}

.t-login .t-f text {
	margin-left: 20rpx;
	color: #aaaaaa;
	font-size: 27rpx;
}

.t-login .uni-input-placeholder {
	color: #000;
}

.cl {
	zoom: 1;
}

.cl:after {
	clear: both;
	display: block;
	visibility: hidden;
	height: 0;
	content: '\20';
}
</style>
