<template>
	<view class="normal-login-container flex flex-direction align-center">
		<!-- 标题 -->
		<view class="login-title-content">
			<view class="title">欢迎来到课件夹</view>
		</view>
		<!-- 标题 -->
		<!-- 登录按钮 -->
		<view class="login-btn-content">
			<view>
				<button @click="handleLogin" class="login-btn">登录</button>
				<view class="xieyi flex align-center justify-center">
					<u-checkbox-group v-model="agree" @change="onchange">
						<u-checkbox shape="circle" size='14' name="agree"></u-checkbox>
					</u-checkbox-group>
					<text>已阅读并同意</text>
					<text @click="handleFileUrl(item)" class="text-blue" style="margin: 0 5px;" v-for="item in fileList"
						:key="item.ossId">{{item.name}}</text>
				</view>
			</view>
			<image v-if="logoUrl && showIcon" class="logo" :src="logoUrl" mode="aspectFit"></image>
		</view>
		<!-- 登录按钮 -->
		<!-- 登录信息 -->
		<view class="login-form-content flex flex-direction justify-between">
			<view class="input-item flex align-center">
				<image class="icon" src="@/static/images/phone.png"></image>
				<input v-model="loginForm.phonenumber" class="input" type="text" placeholder="请输入手机号" maxlength="11" />
			</view>
			<view class="input-item flex align-center">
				<image class="icon" src="@/static/images/message.png"></image>
				<input v-model="loginForm.smsCode" class="input" type="number" placeholder="请输入验证码" maxlength="4" />
				<view class="msgCode text-center">
					<u-code ref="uCode" @change="onMsgCodeChange" @start="canClick = false" @end="canClick = true"
						keepRunning></u-code>
					<view :class="canClick ? 'color-custom' : 'text-gray'" @tap="getMsgCode">{{tips}}</view>
				</view>
			</view>
			<view class="text-gray text-center" @click="show = true">收不到验证码</view>

		</view>
		<!-- 登录信息 -->
		<u-modal :show="show" title="提示" content='请再次获取验证码，如仍然无法收到，请描述问题发送至hr01@nullht.com'
			@confirm="show = false"></u-modal>
	</view>
</template>

<script>
	import {
		getCodeImg,
		getTenantInfo,
		getMsgCode,
		registerWithMsgCode
	} from '@/api/login'
	import {
		getDocUrl
	} from "@/api/case/case"
	const regexPhone = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
	export default {
		data() {
			return {
				isRead: false,
				agree: [],
				tips: '', //倒计时文本
				canClick: true,
				show: false,
				fileList: [], //项目协议
				globalConfig: getApp().globalData.config,
				loginForm: {
					clientId: getApp().globalData.config.clientId,
					grantType: getApp().globalData.config.grantType,
					tenantId: uni.getStorageSync('tenantId') || null, // H0202311221425001
					phonenumber: "", //13852286548
					smsCode: "",
					uuid: ''
				},
				register: '', //是否允许注册 0开通 1关闭
				logoUrl:'',
				originHeight: '',
				showIcon: true
			}
		},
		created() {
			let urls = window.location.href.split('?')
			if (urls.length > 1) {
				let strs = urls[urls.length - 1]
				let arr = strs.split('&')
				let arr2 = arr.filter(item => item.indexOf('tenantId') > -1)
				if (arr2.length > 0) {
					let tenantId = arr2[0].split('=')[1]
					this.loginForm.tenantId = tenantId
					uni.setStorageSync('tenantId', tenantId)
					this.getTenantInfo()
				} else {
					uni.$u.toast('缺少租户编号')
				}
			} else {
				uni.$u.toast('缺少租户编号')
			}
		},
		mounted() {
		  this.originHeight = document.documentElement.clientHeight || document.body.clientHeight;
		  window.addEventListener('resize',this.handleResize);
		},
		beforeDestroy() {
		  // 移除绑定的handleResize事件监听
		  window.removeEventListener("resize",this.handleResize);
		  console.log('移除resize监听');
		},
		methods: {
			handleResize() {
			   var resizeHeight = document.documentElement.clientHeight || document.body.clientHeight;
			   if (resizeHeight < this.originHeight) {
			     //当软键盘弹起，在此处操作
			     if (!this.isIos()) {
			       this.showIcon = false;
			     }
			   } else {
			     //当软键盘收起，在此处操作
			     if (!this.isIos()) {
			       this.showIcon = true;
			     }
			   }
			 },
			 
			 isIos() {
			    var m = navigator.userAgent;
			    var isIos = !!m.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
			    let result = isIos ? true : false;
			    return result;
			  }, 
			  
			//获取租户信息
			getTenantInfo() {
				getTenantInfo(this.loginForm.tenantId).then(res => {
					if (res.code == 200) {
						this.fileList = res.data.agreementFileList
						this.register = res.data.register
						if(res.data.organizationLogo){
							this.logoUrl = res.data.organizationLogo[0].url
						}
					}
				}).catch(err => {

				})
			},
			// 项目协议
			handleFileUrl(item) {
				let url = item.url
				let name = item.name
				let fileType = url.substring(url.lastIndexOf('.') + 1).toUpperCase();
				if (fileType == 'PDF') {
					let newurl = encodeURIComponent(url.replace('http','https'))
					let pdfUrl = '/static/html/web/viewer.html?file=' + newurl
					// let pdfUrl = '/static/html/web/viewer.html?file=/static/html/web/compressed.tracemonkey-pldi-09.pdf'
					this.$tab.navigateTo(`/pages/phone/common/webview/index?title=${name}&url=${pdfUrl}&type=PDF`)
				} else if (fileType == 'DOC' || fileType == 'DOCX') {
					// let newUrl = "https://view.officeapps.live.com/op/view.aspx?src=" + url
					//XDOC文档预览服务地址
					// let newUrl = "https://view.xdocin.com/view?src=" + encodeURIComponent(url)
					// this.$tab.navigateTo(`/pages/phone/common/webview/index?title=${name}&url=${newUrl}`)
					
					// 新方式
					let that = this
					getDocUrl(item.ossId).then(res => {
						console.log('res==', res);
						if(res&&res.code == 200){
							let newUrl = res.data.url.replace('http','https')
							uni.setStorageSync('FileUrl', newUrl)
							that.$tab.navigateTo(`/pages/phone/common/webview/index?title=${name}&type=OSS`)
						}
					}).catch(err => {
					
					})
				} else {
					uni.$u.toast('暂不支持预览此类型文件')
				}
			},
			onMsgCodeChange(text) {
				this.tips = text
			},
			//获取短信验证码
			getMsgCode() {
				if (!this.canClick) {
					return
				}

				if (!this.validatePhoneNum()) {
					return
				}

				getMsgCode({
					phonenumber: this.loginForm.phonenumber
				}).then(res => {
					if (res.code == 200) {
						//开始倒计时
						this.$refs.uCode.start()
					}
				})

			},
			onchange(e) {
				this.agree = e
			},
			//验证手机号
			validatePhoneNum() {
				let phonenumber = this.loginForm.phonenumber
				if (!phonenumber) {
					this.$modal.msgError("请输入手机号")
					return false
				} else if (!regexPhone.test(phonenumber)) {
					this.$modal.msgError("请输入正确的手机号")
					return false
				} else {
					return true
				}
			},
			// 登录方法
			async handleLogin() {
				if (!this.agree || this.agree.length == 0) {
					uni.$u.toast("请先阅读协议并勾选！")
					return
				} else if (!this.validatePhoneNum()) {
					return
				} else if (this.loginForm.smsCode === "") {
					this.$modal.msgError("请输入验证码")
					return
				}

				//1.先获取租户信息是否允许注册
				if (this.register == '0') {
					//先注册
					registerWithMsgCode(this.loginForm).then(res => {
						if (res.code == 200) {
							this.pwdLogin()
						}
					})
				} else {
					//直接登录
					this.pwdLogin()
				}

			},
			// 密码登录
			async pwdLogin() {
				this.$modal.loading("登录中，请耐心等待...")
				this.$store.dispatch('Login', this.loginForm).then(() => {
					this.$modal.closeLoading()
					this.loginSuccess()
				}).catch(() => {

				})
			},
			// 登录成功后，处理函数
			loginSuccess(result) {
				// 设置用户信息
				this.$store.dispatch('GetInfo').then(res => {
					let nickName = res.data.user.nickName
					if (!nickName) {
						uni.navigateTo({
							url: '/pages/phone/chooseIdentity'
						})
					} else {
						this.$tab.reLaunch('/pages/phone/index')
					}
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.normal-login-container {
		width: 100%;
		height: 100vh;


		.login-title-content {
			width: 100%;
			height: 48vh;
			position: relative;
			z-index: 0;
			overflow: hidden;

			.title {
				width: 100%;
				position: absolute;
				top: 35%;
				color: white;
				font-weight: 500;
				font-size: 72rpx;
				font-style: normal;
				z-index: 1;
				text-align: center;
			}
		}

		.login-title-content::after {
			content: '';
			display: block;
			width: 200%;
			height: 200%;
			border-radius: 50%;
			position: absolute;
			left: 50%;
			top: -100%;
			transform: translateX(-50%);
			background: linear-gradient(148deg, white 5.53%, var(--phone-theme-color) 84.5%);
		}

		.login-form-content {
			width: 630rpx;
			height: 300rpx;
			padding: 36rpx 36rpx 28rpx;
			box-sizing: border-box;
			border-radius: 16rpx;
			background: #FFF;
			box-shadow: 0px 8rpx 60rpx 0px rgba(0, 0, 0, 0.08);
			position: absolute;
			top: 35%;
			z-index: 1;


			.input-item {
				width: 100%;
				height: 44rpx;

				.icon {
					width: 32rpx;
					height: 32rpx;
				}

				.input {
					flex: 1;
					font-size: 28rpx;
					line-height: 44rpx;
					text-align: left;
					padding-left: 30rpx;
				}

				.msgCode {
					width: 200rpx;
					height: 44rpx;
					font-size: 28rpx;

					button {
						height: 44rpx;
					}
				}

			}
		}


		.login-btn-content {
			width: 100%;
			height: calc(52vh - 300rpx);
			padding: 0 60rpx;
			margin-top: 240rpx;
			text-align: center;
			box-sizing: border-box;
			display: flex;
			flex-direction: column;
			justify-content: space-between;

			.login-btn {
				width: 100%;
				height: 88rpx;
				background: var(--phone-theme-color);
				border-radius: 8rpx;
				color: white;
				font-size: 28rpx;
				line-height: 88rpx;
			}

			.xieyi {
				margin-top: 30rpx;
				font-size: 24rpx;
				color: #86909C;

        text{
          white-space: nowrap;
        }

        .text-blue{
          flex:1;
          overflow: hidden;
          text-overflow: ellipsis;
        }
			}
			.logo-content{
				width: 100%;
				height: 50%;
				display: flex;
				align-items: flex-end;
				justify-content: center;
				padding-bottom: 40rpx;
			}
		
			.logo{
				// width: 100rpx;
				// height: 100rpx;
				max-width: 280rpx;
				max-height: 140rpx;
				border-radius: 10rpx;
				align-self: center;
			}
		}
	}

	/deep/ .uni-input-input {
		color: #000;
	}
</style>
