<template>
	<view class="">
		<view class="top">

		</view>
		<view class="content" style="height: 85vh;">
			<scroll-view style="border-radius: 20rpx;padding-left: 20rpx;" scroll-x class="bg-white nav"
				scroll-with-animation :scroll-left="scrollLeft">
				<view class="cu-item text-lg" :class="index==current?'text-checked text-bold cur':''"
					v-for="(item,index) in list" :key="index" @tap="tabSelect(index)">
					{{item.name}}
				</view>
			</scroll-view>
			<view class="item">
				<swiper :circular="true" style="height: 100%;" :current="current" @change="swiperChange"
					@animationfinish="animationfinish">
					<swiper-item style="height: 100%;">
						<view class="flex justify-center flex-direction align-center">
							<image style="width: 120rpx;height: 120rpx;" src="../../static/login/yuangong.png"></image>
						</view>
						<view class="input">
							<text class="cuIcon-discoverfill text-base"
								style="font-size: 34rpx;margin-right: 22rpx;"></text>
							<input disabled v-model="agencyName" @click="agencyShow = true" placeholder="请选择您所在的园区"
								type="text" value="" />
						</view>
						<view class="input">
							<text class="cuIcon-mobilefill text-base text-bold"
								style="font-size: 38rpx;margin-right: 22rpx;"></text>
							<input v-model="phone" placeholder="请输入您的手机号码" type="text" value="" />
						</view>
						<view class="input" style="position: relative;">
							<text class="cuIcon-safe text-base text-bold"
								style="font-size: 34rpx;margin-right: 22rpx;"></text>
							<input v-model="yzm" style="width: 60%;" placeholder="请输入验证码" type="text" value="" />
							<view :style="showText?'':'background-color: #A7A7A7;'" class="code" @click="getCode()">
								{{tips}}
							</view>
						</view>
					</swiper-item>
					<swiper-item>
						<view class="flex justify-center flex-direction align-center">
							<image style="width: 90rpx;height: 90rpx;" src="../../static/login/qiye.png"></image>
						</view>
						<view class="input">
							<text class="cuIcon-discoverfill text-base"
								style="font-size: 34rpx;margin-right: 22rpx;"></text>
							<input disabled v-model="agencyName" @click="agencyShow = true" placeholder="请选择您所在的园区"
								type="text" value="" />
						</view>
						<view class="input">
							<text class="cuIcon-homefill text-base"
								style="font-size: 34rpx;margin-right: 22rpx;"></text>
							<input disabled v-model="enterpriseName" @click="enterpriseShow = true"
								placeholder="请选择您所在的企业" type="text" value="" />
						</view>
						<view class="input">
							<image src="../../static/login/account.png"
								style="width: 32rpx;height: 34rpx;margin-right: 22rpx;"></image>
							<input v-model="enterpriseAccount" style="width: 60%;" placeholder="请输入您的登录账号" type="text"
								value="" />
						</view>
						<view class="input">
							<image src="../../static/login/password.png"
								style="width: 32rpx;height: 34rpx;margin-right: 22rpx;"></image>
							<input v-model="enterprisePassword" style="width: 60%;" placeholder="请输入您的登录密码"
								type="password" value="" />
						</view>
					</swiper-item>
					<swiper-item>
						<view class="flex justify-center  ">
							<image style="width: 120rpx;height: 120rpx;" src="../../static/login/guanliyuan.png">
							</image>
						</view>
						<view class="input">
							<text class="cuIcon-discoverfill text-base"
								style="font-size: 34rpx;margin-right: 22rpx;"></text>
							<input disabled v-model="agencyName" @click="agencyShow = true" placeholder="请选择您所在的园区"
								type="text" value="" />
						</view>
						<view class="input">
							<image src="../../static/login/account.png" mode=""
								style="width: 32rpx;height: 34rpx;margin-right: 22rpx;"></image>
							<input v-model="agencyAccount" style="width: 60%;" placeholder="请输入您的登录账号" type="text"
								value="" />
						</view>
						<view class="input">
							<image src="../../static/login/password.png"
								style="width: 32rpx;height: 34rpx;margin-right: 22rpx;"></image>
							<input type="password" v-model="agencyPassword" style="width: 60%;" placeholder="请输入您的登录密码"
								value="" />
						</view>
					</swiper-item>
					<swiper-item>
						<view class="flex justify-center flex-direction align-center">
							<image style="width: 100rpx;height: 100rpx;" src="../../static/login/fangke.png"></image>
						</view>
						<view class="input">
							<text class="cuIcon-timefill text-base"
								style="font-size: 34rpx;margin-right: 22rpx;"></text>
							<input disabled v-model="interviewTime" @click="interviewTimeShow = true"
								placeholder="请选择您要访问的日期" type="text" value="" />
						</view>
						<view class="input">
							<text class="cuIcon-discoverfill text-base"
								style="font-size: 34rpx;margin-right: 22rpx;"></text>
							<input disabled v-model="agencyName" @click="agencyShow = true" placeholder="请选择您要访问的园区"
								type="text" value="" />
						</view>
						<view class="input">
							<text class="cuIcon-homefill text-base"
								style="font-size: 34rpx;margin-right: 22rpx;"></text>
							<input disabled v-model="enterpriseName" @click="enterpriseShow = true"
								placeholder="请选择您要访问的企业 (选填)" type="text" value="" />
						</view>
						<view class="text-center base-color padding-top-50 text-lg">
							<text @click="jump('/pages/guest/records/records')"
								style="text-decoration: underline;">申请记录</text>
						</view>
					</swiper-item>
				</swiper>
			</view>
			<button v-if="current!=3" class="button" @click="login()">登 录</button>
			<button v-else class="button" @click="applyOpenDoor">申请开门</button>
		</view>
		<!-- 园区 -->
		<u-popup border-radius="8" height="60%" mode="bottom" v-model="agencyShow">
			<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="agencyKeyWord" type="text" :adjust-position="false"
						placeholder="请输入关键字搜索" confirm-type="search" />
				</view>
			</view>
			<scroll-view v-if="!$isEmpty(agencyList)" style="padding-top: 110rpx;height: 100%;" :scroll-y="true">
				<view @click="selectAgency(item)" hover-class="hoverClass" class="text-center padding-30 solid-bottom"
					v-for="(item,index) in agencyList" :key="index">
					<text>{{item.name}}</text>
				</view>
				<u-divider v-if="agencyList.length>=20" height="80">只显示20条数据</u-divider>
			</scroll-view>
			<u-empty v-else name="search"></u-empty>
		</u-popup>
		<!-- 企业列表 -->
		<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="enterpriseKeyword" type="text" :adjust-position="false"
						placeholder="请输入关键字搜索" confirm-type="search" />
				</view>
			</view>
			<scroll-view v-if="!$isEmpty(enterpriseList)" 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="enterpriseList.length>=20" height="80">只显示20条数据</u-divider>
			</scroll-view>
			<u-empty v-else name="search"></u-empty>
		</u-popup>

		<!-- 访问时间 -->
		<u-picker @confirm="interviewTimeConfirm" :params="params" v-model="interviewTimeShow" mode="time"></u-picker>
		<!-- 验证码 -->
		<u-verification-code seconds="60" @end="end" @start="start" ref="uCode" @change="codeChange">
		</u-verification-code>
	</view>
</template>
<script>
	var that;
	export default {
		name: 'card',
		data() {
			return {
				backpath: '',

				contentHeight: '',

				list: [{
					name: '员工'
				}, {
					name: '企业'
				}, {
					name: '管理员',
				}, {
					name: '访客',
				}],
				current: 0,
				//发送验证码
				tips: '',
				showText: true,

				//园区下拉框
				agencyName: '',
				agencyList: [],
				agencyKeyWord: '',
				agencyShow: false,

				//园区登录
				agencyId: '',
				agencyAccount: '',
				agencyPassword: '',

				//企业下拉框
				enterpriseName: '', //回显
				enterpriseShow: false,
				enterpriseList: [],
				enterpriseKeyword: '',

				//企业登录
				creditCode: '',
				enterpriseId: '',
				enterpriseAccount: '',
				enterprisePassword: '',

				openId: '',
				//员工登录
				phone: '',
				yzm: '',

				//访客
				interviewTimeShow: false,
				interviewTime: '',
				params: {
					year: true,
					month: true,
					day: true,
					hour: false,
					minute: false,
					second: false
				},
			};
		},
		onLoad(options) {
			this.contentHeight = this.$u.sys().windowHeight + 'px'
			that = this
			if (!this.$isEmpty(options.backpath)) {
				this.backpath = options.backpath
			}
			if (this.$isAuth()) {
				uni.reLaunch({
					url: '/pages/index/index'
				})
				//免登录
				return
			}
			if (this.$isEmpty(this.$cache.get('openId'))) {
				this.getOpenId()
			} else {
				this.openId = this.$cache.get('openId')
			}
			this.getAgencyList()
		},
		onShow() {
			this.handelNoToken()
			this.getAppletStatus()
		},
		watch: {
			agencyKeyWord() {
				let that = this
				//节流函数
				if (this.timer) {
					clearTimeout(this.timer)
				}
				this.timer = setTimeout(() => {
					that.agencyList = []
					that.getAgencyList()
				}, 500)
			},
			enterpriseKeyword() {
				let that = this
				//节流函数
				if (this.timer) {
					clearTimeout(this.timer)
				}
				this.timer = setTimeout(() => {
					that.enterpriseList = []
					that.getEnterpriseList()
				}, 500)
			},
		},
		methods: {
			//处理没token但是却选择了园区的情况
			//访客从申请列表返回登录页时，是没有token的，这样导致其他接口报错
			async handelNoToken() {
				let that = this
				if (!this.$cache.get('tokenObj') && !this.$isEmpty(this.agencyId)) {
					//如果没有token,且园区id不为空
					this.agencyList.forEach(item => {
						if (item.id == that.agencyId) {
							let params = {
								tenant_id: item.tenantId,
								username: item.account,
								password: item.password,
								grant_type: "password"
							}
							//放进缓存中，并获取token
							that.$cache.put('tokenObj', params)
							//获取token
							that.$api.getToken(that.$u.queryParams(params)).then(res => {
								let token = res.token_type + " " + res.access_token
								uni.setStorageSync('token', token)
								//获取企业列表
								that.getEnterpriseList()
							})
						}
					})

				}
			},
			//访问时间
			interviewTimeConfirm(e) {
				this.interviewTime = e.year + '-' + e.month + '-' + e.day
			},
			/**
			 * 获取openid
			 */
			getOpenId() {
				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
							this.$cache.put('openId', this.openId)
						})
					}
				})
			},
			//获取园区列表
			getAgencyList() {
				let params = {
					size: 20,
					name: this.agencyKeyWord
				}
				this.$api.agency.getAgencyTenantList(params).then(res => {
					this.agencyList = res.data
				})
			},
			//选择园区
			selectAgency(item) {
				console.log(item, "/**********");
				let params = {
					tenant_id: item.tenantId,
					username: item.account,
					password: item.password,
					grant_type: "password",
					scope: "all",
					type: "account"
				}
				this.agencyId = item.id
				this.agencyName = item.name
				this.agencyShow = false
				this.$cache.put('tokenObj', params)
				//获取token
				this.$api.getToken(this.$u.queryParams(params)).then(res => {
					let token = res.token_type + " " + res.access_token
					uni.setStorageSync('token', token)
					//获取企业列表
					this.getEnterpriseList()
				})
			},
			/**
			 * 获取验证码
			 */
			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('获取验证码失败');
						})
					}, 800);
				} else {
					this.$u.toast('倒计时结束后再发送');
				}
			},
			codeChange(text) {
				this.tips = text;
			},
			end() {
				this.showText = true
			},
			start() {
				this.showText = false
			},
			//当前登录按钮操作
			async login() {
				if (this.current == 0) {
					//员工登录
					this.staffLogin()
				} else if (this.current == 1) {
					//企业登录
					this.enterpriseLogin()
				} else if (this.current == 2) {
					//管理员登陆
					this.ganderLogin()
				}
			},
			//员工登录
			async staffLogin() {
				//15622205184
				if (this.phone == '15622205184') {
					this.userLogin()
					return
				}
				if (this.$isEmpty(this.agencyId)) {
					this.$u.toast('请选择您所在的园区')
					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 params = {
					openId: this.openId,
					loginType: 0,
					phone: this.phone
				}
				let staffRes = await this.$api.login(params)
				let userInfo = staffRes.data
				if (this.$isEmpty(userInfo)) {
					//如果没有员工信息。新用户。跳转到注册认证界面
					uni.navigateTo({
						url: '/pages/auth/auth?phone=' + this.phone
					})
				} else {
					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('loginuser', userInfo)
						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
							})
						})
					}
				}
			},
			//获取企业列表
			getEnterpriseList() {
				let params = {
					size: 20,
					enterpriseName: this.enterpriseKeyword
				}
				this.$api.enterprise.page(params).then(res => {
					this.enterpriseList = res.data.records
				})
			},
			//选择企业
			selectEnterprise(item) {
				this.creditCode = item.creditCode
				this.enterpriseShow = false
				this.enterpriseName = item.enterpriseName
				this.enterpriseId = item.id
			},
			/**
			 * 企业登录
			 */
			async enterpriseLogin() {
				if (this.$isEmpty(this.agencyId)) {
					this.$u.toast('请选择园区')
					return
				}
				if (this.$isEmpty(this.enterpriseId)) {
					this.$u.toast('请选择企业')
					return
				}
				if (this.$isEmpty(this.enterpriseAccount)) {
					this.$u.toast("请输入账号")
					return
				}
				if (this.$isEmpty(this.enterprisePassword)) {
					this.$u.toast("请输入密码")
					return
				}
				let params = {
					"loginType": 1,
					"enterpriseId": this.enterpriseId,
					"enterpriseAccount": this.enterpriseAccount,
					"enterprisePassword": this.enterprisePassword,
					"openId": this.openId
				}
				this.$api.login(params).then(res => {
					if (this.$isEmpty(res.data)) {
						this.$u.toast('账号或密码错误')
						return
					} else {
						//公司信息
						let userInfo = res.data
						this.$cache.put('agencyId', userInfo.agencyId)
						getApp().globalData.userInfo = userInfo
						this.$cache.put('loginuser', userInfo)
						this.$cache.put('loginAccount', this.enterpriseAccount)
						this.$cache.put('agencyTenantId', userInfo.tenantId)
						this.$cache.put('creditCode', this.creditCode)
						this.$cache.put('enterpriseId', userInfo.enterpriseId)
						this.handelSuccessLogin('enterprise')
					}
				})
			},
			/**
			 * 管理员登陆
			 */
			async ganderLogin() {
				if (this.$isEmpty(this.agencyId)) {
					this.$u.toast('请选择您所在的园区')
					return
				}
				if (this.$isEmpty(this.agencyAccount)) {
					this.$u.toast('请输入账号')
					return
				}
				if (this.$isEmpty(this.agencyPassword)) {
					this.$u.toast('请输入密码')
					return
				}
				let params = {
					"loginType": 2,
					"agencyId": this.agencyId,
					"agencyAccount": this.agencyAccount,
					"agencyPassword": this.agencyPassword,
					"openId": this.openId
				}
				let res = await this.$api.login(params)
				let ganderInfo = res.data
				if (this.$isEmpty(ganderInfo)) {
					this.$u.toast('账号或密码错误')
					return
				}
				//订阅消息通知  -- 登录不了，暂时去掉，
				// await this.$mpi.subscribe(this.$adminTmplIds)
				//输入密码成功
				//园区信息
				this.$cache.put('loginuser', ganderInfo)
				this.$cache.put('loginAccount', this.agencyAccount)
				this.$cache.put('agencyId', ganderInfo.agencyId)
				this.$cache.put('agency', ganderInfo.agencyName)
				this.$cache.put('agencyTenantId', ganderInfo.tenantId)
				getApp().globalData.userInfo = ganderInfo
				this.handelSuccessLogin('agency')
			},
			/**
			 * 登录成功的处理方式
			 * 如果是从其他地方跳转回的登录页，则登录后跳转回原页面
			 * 否则跳转到首页
			 */
			handelSuccessLogin(loginType) {
				that.$cache.put("loginType", loginType)
				if (!this.$isEmpty(this.backpath)) {
					uni.navigateTo({
						url: this.backpath
					})
					return
				}
				uni.switchTab({
					url: "/pages/index/index"
				})
			},
			async applyOpenDoor() {
				if (this.$isEmpty(this.interviewTime)) {
					this.$u.toast('请选择访问日期')
					return
				}
				if (this.$isEmpty(this.agencyId)) {
					this.$u.toast('请选择要访问的园区')
					return
				}
				let params = {
					interviewTime: this.interviewTime,
					agencyId: this.agencyId,
					openId: this.openId
				}
				let res = await this.$api.guest.page(params)
				let data = res.data.records[0]
				if (this.$isEmpty(data)) {
					that.reApply(params)
					return
				}
				uni.showModal({
					content: "检测到您有该园区的申请记录，是否立即去开门？",
					cancelText: "重新申请",
					confirmText: '去开门',
					success: (res) => {
						if (res.confirm) {
							console.log("去开门")
						} else {
							that.reApply(params)
						}
					}
				})
			},
			reApply(params) {
				params.enterpriseId = this.enterpriseId,
					params.agencyName = this.agencyName
				params.enterpriseName = this.enterpriseName
				uni.navigateTo({
					url: "/pages/guest/guest" + this.$u.queryParams(params)
				})
			},
			jump(url) {
				if (!this.$isEmpty(url)) {
					uni.navigateTo({
						url
					})
				}
			},
			isToday(str) {
				var d = new Date(str.replace(/-/g, "/"));
				var todaysDate = new Date();
				if (d.setHours(0, 0, 0, 0) == todaysDate.setHours(0, 0, 0, 0)) {
					return true;
				} else {
					return false;
				}
			},
			getAppletStatus() {
				this.$api.wxApi.getAppletStatus({
					id: 2
				}).then(res => {
					uni.setStorageSync("appletStatus", res.data.appletType)
				})
			},
			tabSelect(index) {
				this.current = index
			},
			swiperChange(e) {
				this.current = e.detail.current
			},
			animationfinish({
				detail: {
					current
				}
			}) {
				this.current = current;
			},
		}
	};
</script>

<style lang="scss">
	page {
		background-color: #FFFFFF;
		height: 100%;
	}

	.text-checked {
		font-size: 36rpx;
		// color: #333;
		color: $base-color;
	}

	.button {
		position: fixed;
		bottom: 5%;
		left: 0;
		right: 0;
		font-size: 28rpx;
		background: $base-color;
		color: #fff;
		height: 90rpx;
		margin: 0rpx 30rpx;
		line-height: 90rpx;
		border-radius: 50rpx;
		box-shadow: 0 5px 7px 0 rgba(86, 119, 252, 0.2);
	}

	.guest {
		font-size: 28rpx;
		color: #fff;
		background: $base-color;
		height: 90rpx;
		margin: 120rpx 30rpx;
		line-height: 90rpx;
		border-radius: 50rpx;
		box-shadow: 0 5px 7px 0 rgba(86, 119, 252, 0.2);
	}

	.top {
		height: 220rpx;
		background-color: #5064eb;
	}

	.content {
		border-radius: 20rpx;
		background-color: #FFFFFF;
		margin: -120rpx 20rpx 0;

		.item {
			height: 100%;
			padding-top: 15%;

			.input {
				margin: 40rpx 30rpx;
				border-radius: 50rpx;
				background-color: rgba(80, 100, 235, .1);
				display: flex;
				padding: 20rpx 30rpx;

				image {
					width: 32rpx;
					height: 34rpx;
					margin-right: 22rpx;
					margin-top: 4rpx;
				}

				.phone {
					width: 40rpx;
					height: 40rpx;
					margin-top: 4rpx;
					margin-right: 22rpx;
				}

				.qiye {
					width: 38rpx;
					height: 38rpx;
					margin-top: 4rpx;
					margin-right: 22rpx;
				}

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

				.code {
					position: absolute;
					right: 22rpx;
					top: 18rpx;
					background: $base-color;
					color: #fff;
					font-size: 24rpx;
					border-radius: 50rpx;
					height: 50rpx;
					line-height: 50rpx;
					padding: 0 25rpx;
					z-index: 1000;
				}
			}
		}
	}
</style>
