<template>
	<div class="login_bg">
		<div class="login_adv">
			<div class="login_adv__title">
				<h3><img class="logo" alt="象纬云科" src="https://dm-auto.oss-cn-shanghai.aliyuncs.com/xw_cloud/image/login_logo.png"></h3>
				<h2><span class="origin"></span> 维保系统平台</h2>
			</div>
			<div class="login_adv__mask"></div>
		</div>
		<div class="login_main">
			<div class="login-form">
				<div class="loginRightMask">
					<div class="handerWelcome">
						<div class="title">HELLO</div>
						<div class="name">欢迎登录维保系统</div>
					</div>
					<el-tabs>
						<el-tab-pane label="账号登录" lazy>
							<password-form></password-form>
						</el-tab-pane>
						<el-tab-pane label="手机号登录" lazy>
							<phone-form></phone-form>
						</el-tab-pane>
					</el-tabs>
					<template v-if="$CONFIG.MY_SHOW_LOGIN_OAUTH">
						<div class="thirdParty">
							<el-divider class="dividerBox">{{ $t('login.signInOther') }}</el-divider>
							<div class="login-oauth">
								<div class="btnBox wechat" @click="bindWechat">
									<el-icon><sc-icon-wechat /></el-icon>
									<span class="text">微信登录</span>
								</div>
								<div class="btnBox dingTalk" @click="bindDingTalk">
									<el-icon><sc-icon-DingTalk /></el-icon>
									<span class="text">钉钉登录</span>
								</div>
							</div>
						</div>
					</template>
					<div class="passKeyLogin" @click="passKeyLogin">使用passKey登录</div>
				</div>
				<div class="login_adv__bottom">
					linkwing.com·麟云 版权所有 @ 2023-{{new Date().getFullYear()}}
				</div>
			</div>
		</div>
	</div>
	<el-dialog v-model="showWechatLogin" :title="$t('login.wechatLoginTitle')" :width="400" destroy-on-close>
		<div class="qrCodeLogin">
			<sc-qr-code class="qrCode" :text="WechatLoginCode" :size="200"></sc-qr-code>
			<p class="msg">{{$tc('login.wechatLoginMsg', 1)}}<br />{{$tc('login.wechatLoginMsg', 2)}}</p>
			<div class="qrCodeLogin-result" v-if="isWechatLoginResult">
				<el-result icon="success" :title="$tc('login.wechatLoginResult', 1)"
					:sub-title="$tc('login.wechatLoginResult', 2)"></el-result>
			</div>
		</div>
	</el-dialog>
</template>

<script>
	import passwordForm from './components/passwordForm'
	import phoneForm from './components/phoneForm'

	export default {
		components: {
			passwordForm,
			phoneForm
		},
		data() {
			return {
				config: {
					lang: this.$TOOL.data.get('APP_LANG') || this.$CONFIG.LANG,
					dark: this.$TOOL.data.get('APP_DARK') || false
				},
				lang: [
					{
						name: '简体中文',
						value: 'zh-cn',
					},
					{
						name: 'English',
						value: 'en',
					}
				],
				WechatLoginCode: "",
				showWechatLogin: false,
				isWechatLoginResult: false
			}
		},
		watch: {
			'config.dark'(val) {
				if (val) {
					document.documentElement.classList.add("dark")
					this.$TOOL.data.set("APP_DARK", val)
				} else {
					document.documentElement.classList.remove("dark")
					this.$TOOL.data.remove("APP_DARK")
				}
			},
			'config.lang'(val) {
				this.$i18n.locale = val
				this.$TOOL.data.set("APP_LANG", val)
			}
		},
		created: function () {
			// 监听缓存变化 addEventListener
			window.addEventListener('storage',this.storageChange);

			this.$TOOL.cookie.remove("TOKEN")
			this.$TOOL.data.remove("USER_INFO")
			this.$TOOL.data.remove("MENU")
			this.$TOOL.data.remove("USER_INFO")
			this.$TOOL.data.remove("PERMISSIONS")
			this.$TOOL.data.remove("DASHBOARDGRID")
			this.$TOOL.data.remove("grid")
			this.$store.commit("clearViewTags")
			this.$store.commit("clearKeepLive")
			this.$store.commit("clearIframeList")

			localStorage.removeItem('bindDingTalk');
			localStorage.removeItem('bindWechat');
		},
		unmounted() {
			window.removeEventListener('storage', this.storageChange);
		},
		methods: {
			configLang(command) {
				this.config.lang = command.value
			},

			storageChange(e){
				let dingTalk = localStorage.getItem('bindDingTalk');
				let wechat = localStorage.getItem('bindWechat');
				if(e.key == 'DINGTALK_LOGIN_MESSAGE'){
					if(dingTalk == 1 && typeof e.newValue =="string" && e.newValue!=''){
						this.dingTalkLogin(e.newValue)
					}
					localStorage.removeItem("DINGTALK_LOGIN_MESSAGE");
				}

				if(e.key == 'WECHAT_LOGIN_MESSAGE'){
					if(wechat == 1 && typeof e.newValue =="string" && e.newValue!=''){
						this.wechatLogin(e.newValue);
					}
					localStorage.removeItem("WECHAT_LOGIN_MESSAGE");
				}
			},
			// 微信扫码
			async bindWechat(){
				const res = await this.$API.auth.wechatCode.post();
				if(res.code == 200){
					const url = JSON.parse(JSON.stringify(res.data.redirect));
					localStorage.setItem('bindWechat','1');
					window.open(url);
				}
			},
			// 钉钉扫码
			async bindDingTalk(){
				const res = await this.$API.auth.dingTalkCode.post();
				if(res.code == 200){
					const url = JSON.parse(JSON.stringify(res.data.redirect));
					localStorage.setItem('bindDingTalk','1');
					window.open(url);
				}
			},
			// 钉钉登录
			async dingTalkLogin(e){
				let em = JSON.parse(e);
				let params = {code:em.code};
				const user = await this.$API.auth.dingTalkLogin.post(params);
				if(user.code == 200){
					await this.setLoginData(user);
				}else{
					return false;
				}
			},

			async setLoginData(user) {
				this.$TOOL.cookie.set("TOKEN", user.data.token, {
					expires: 0
				})
				this.$TOOL.data.set("USER_INFO", user.data.user)
				if(user.data.user.avatar!=''){
					this.$store.commit("SET_LOGIN_AVATAR", user.data.user.avatar);
				}
				this.$store.commit("SET_LOGIN_NAME", user.data.user.name);

				if(user.data.user.company_id === 0){
					this.$router.replace({
						path: '/maintenance'
					})
					this.islogin = false
					return
				}

				//获取菜单
				let menu = null;
				menu = await this.$API.system.menu.myMenus.get()
				if (menu.code === 200) {
					if (menu.data.menu.length === 0) {
						this.islogin = false
						await this.$alert("当前用户无任何菜单权限，请联系系统管理员", "无权限访问", {
							type: 'error',
							center: true
						})
						return false
					}
					this.$TOOL.data.set("MENU", menu.data.menu)
					const data_auth = this.$TOOL.objCopy(menu.data.permissions);
					data_auth.auth = this.$TOOL.authPermissions(data_auth.data_permissions);
					this.$TOOL.data.set("PERMISSIONS", data_auth)
					this.$TOOL.data.set("DASHBOARDGRID", menu.data.dashboardGrid)
				} else {
					this.$message.warning(menu.msg)
					return false
				}
				this.$router.replace({
					path: '/'
				})
			},
			// passKey 登录
			async passKeyLogin(){
				const res = await this.$API.system.user.generateAuthentication.post();
				if(res.code == 200){
					const publicKeyConfigForLogin = {
						challenge: Uint8Array.from(res.data.challenge),
						timeout: res.data.timeout,
						rpId:res.data.rpId,
						userVerification: res.data.userVerification
					};
					try {
						const assertion = await navigator.credentials.get({ publicKey:publicKeyConfigForLogin });
						await this.passKeyVerify(assertion);
					}catch(err){
						console.log(err,'您已取消');
					}
				}
			},
			async passKeyVerify(assertion) {
				let params = {
					id: assertion.id,
					rawId: this.bufferToBase64URL(assertion.rawId),
					type: assertion.type,
					response: {
						authenticatorData: this.bufferToBase64URL(assertion.response.authenticatorData),
						clientDataJSON: this.bufferToBase64URL(assertion.response.clientDataJSON),
						signature: this.bufferToBase64URL(assertion.response.signature),
						userHandle:this.bufferToBase64URL(assertion.response.userHandle),
					}
				}
				const user = await this.$API.system.user.verifyAuthentication.post(params);
				if(user.code == 200){
					await this.setLoginData(user);
				}
			},
			bufferToBase64URL(buffer) {
				return btoa(String.fromCharCode.apply(null, new Uint8Array(buffer)))
					.replace(/\+/g, "-")
					.replace(/\//g, "_")
					.replace(/=/g, "");
			},
		}
	}
</script>

<style lang="scss" scoped>
	.login_bg {
		width: 100%;
		height: 100%;
		display: flex;
	}
	.login_adv {
		width: 100%;
		position: relative;
	}
	.login_adv__title {
		color: #547FDB;
		padding: 40px;
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		z-index: 2;
		display: flex;
		align-items: center;
		h3{
			display: flex;
			align-items: center;
		}
		h2{
			height: 28px;
			display: flex;
			align-items: flex-start;
			font-size: 22px;
			position: relative;
			padding-left: 18px;
			color: #595E5C;
			font-weight: 500;
			.origin{
				position: absolute;
				left: 4px;
				top: 12px;
				display: inline-block;
				width: 8px;
				height: 8px;
				border-radius: 50%;
				background: #595E5C;
				margin: 0 8px 0 0;
			}
		}
		.logo{
			width: 200px;
		}
	}

	.login_adv__mask {
		background-size: cover;
		background-position: center;
		background-repeat: no-repeat;
		background-image: url(https://dm-auto.oss-cn-shanghai.aliyuncs.com/xw_cloud/image/login_back5.png);
		width: calc(100% - 460px);
		height: 100%;
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 1;
	}
	.login_main {
		width: 100%;
		height: 100%;
		display: flex;
		justify-content: flex-end;
		position: absolute;
		left: 0;
		top: 0;
		z-index: 200;
	}
	.login-form {
		width: 460px;
		height: 100%;
		position: relative;
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		justify-content: center;
		box-shadow: 2px 10px 20px rgba(0,0,0,0.2);
		background: rgba(255,255,255,1);
		.dividerBox:deep(.el-divider__text){
			font-weight: normal;
			color: #888;
			font-size: 13px;
		}
		.passKeyLogin{
			position: absolute;
			left: 40px;
			bottom: 70px;
			margin-top: 22px;
			font-weight: bold;
			width: calc(100% - 80px);
			height: 40px;
			background: #DAEAFB;
			display: flex;
			align-items: center;
			justify-content: center;
			border-radius: 4px;
			color: var(--el-color-primary);
			cursor: pointer;
			box-shadow: 0 2px 4px rgba(0,0,0,0.1);
		}

		.loginRightMask{
			height: 710px;
			padding: 0 40px 40px 40px;
			width: 100%;
		}
		.handerWelcome{
			.title{
				font-size: 42px;
				font-weight: 600;
				padding-bottom: 10px;
				color: var(--el-color-primary);
			}
			.name{
				font-size: 23px;
				font-weight: 600;
				padding-bottom: 60px;
				color: var(--el-color-primary);
			}
		}
		.login_adv__bottom {
			position: absolute;
			left: 0;
			right: 0;
			bottom: 0;
			padding: 30px;
			text-align: center;
			z-index: 3;
			color: #888;
		}
	}
	.login-header {
		margin-bottom: 40px;
	}

	.login-header .logo {
		display: flex;
		align-items: center;
		color: #fff;
	}

	.login-header .logo img {
		width: 40px;
		height: 40px;
		vertical-align: bottom;
		margin-right: 10px;
	}

	.login-header .logo label {
		font-size: 26px;
		font-weight: bold;
	}
	.thirdParty{
		width: 80%;
		margin: 60px auto 0 auto;
		.login-oauth {
			display: flex;
			justify-content: center;
			.btnBox{
				margin: 2px 12px;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				border-radius: 50%;
				.el-icon{
					font-size: 26px;
				}
				.text{
					color: #888;
					margin-top: 10px;
					font-size: 12px;
				}
			}
		}
	}

	.login-form .el-divider {
		margin-top: 40px;
	}
	.login-form:deep(.el-tabs) .el-tabs__header {
		margin-bottom: 25px;
	}
	.login-form:deep(.el-tabs) .el-tabs__header .el-tabs__item {
		font-size: 14px;
	}
	.login-form:deep(.login-forgot) {
		text-align: right;
	}
	.login-form:deep(.login-forgot) a {
		color: var(--el-color-primary);
	}
	.login-form:deep(.login-forgot) a:hover {
		color: var(--el-color-primary-light-3);
	}
	.login-form:deep(.login-reg) {
		font-size: 14px;
		color: var(--el-text-color-primary);
	}
	.login-form:deep(.login-reg) a {
		color: var(--el-color-primary);
	}
	.login-form:deep(.login-reg) a:hover {
		color: var(--el-color-primary-light-3);
	}
	.login_config {
		position: absolute;
		top: 20px;
		right: 20px;
	}
	.login-form:deep(.login-msg-yzm) {
		display: flex;
		width: 100%;
	}
	.login-form:deep(.login-msg-yzm) .el-button {
		margin-left: 10px;
		--el-button-size: 42px;
	}
	.qrCodeLogin {
		text-align: center;
		position: relative;
		padding: 20px 0;
	}
	.qrCodeLogin img.qrCode {
		background: #fff;
		padding: 20px;
		border-radius: 10px;
	}
	.qrCodeLogin p.msg {
		margin-top: 15px;
	}
	.qrCodeLogin .qrCodeLogin-result {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		text-align: center;
		background: var(--el-mask-color);
	}

	@media (max-width: 1200px) {
		.login-form {
			width: 460px;
			.login-left{
				display: none;
			}
			.login-right{
				border-radius: 10px;
			}
		}
	}

	@media (max-width: 1000px) {
		.login_main {
			display: flex;
		}
		.login_main .login_config {
			position: static;
			padding: 20px 20px 0 20px;
			text-align: right;
		}
		.login-form {
			width: 100%;
			padding: 20px 40px;
		}

		.login_adv {
			display: none;
		}
	}
	@media (max-width: 800px){
		.login-form{
			width: 100%;
			height: 100%;
			padding: 0;
		}
		.login_adv {
			display: none;
		}
	}
</style>
