<template>
	<div class="login" >
		<div class="login-ctn">
			<div class="headder">
				<h2>边坡数据在线监测系统</h2>
				<h4>ONLINE MONITORING SYSTEM FOR TAILINGS POND DATA</h4>
			</div>
			<div class="logo-place">
				<div class="logo-title">用户登录</div>
				<h3 class="subtitle">欢迎登录后台系统</h3>
				<div class="figure">
					<img src="@/assets/images/login_adorn4.png">
				</div>
				<div class="ctn-place">
					<div class="inbox-range">
						<div class="ctn-fix">
							<el-form ref="loginForm" :model="loginForm" :rules="loginRules" label-position="left" label-width="0px" class="login-form">
								<el-form-item prop="username">
									<el-input v-model="loginForm.username" type="text" auto-complete="off" placeholder="账号">
									  <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
									</el-input>
								</el-form-item>
								<el-form-item prop="password">
									<el-input v-model="loginForm.password" type="password" auto-complete="off" placeholder="密码" @keyup.enter.native="handleLogin">
									  <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
									</el-input>
								</el-form-item>
								<!-- 
									<el-form-item prop="code">
									<el-input v-model="loginForm.code" auto-complete="off" placeholder="验证码" style="width: 63%" @keyup.enter.native="handleLogin">
									  <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
									</el-input>
									<div class="login-code">
									  <img :src="codeUrl" @click="getCode">
									</div>
									</el-form-item>
								-->
								<el-form-item style="width:100%;">
									<el-button :loading="loading" size="medium" type="primary" style="width:100%;" @click.native.prevent="handleLogin">
										<span v-if="!loading">登 录</span>
										<span v-else>登 录 中...</span>
									</el-button>
								</el-form-item>
							</el-form>
						</div>
					</div>
				</div>
			</div>
			<!-- 底部 -->
			<div v-if="$store.state.settings.showFooter" id="el-login-footer">
			  <span v-html="$store.state.settings.footerTxt" />
			  <span> ⋅ </span>
			  <!-- <a href="https://beian.miit.gov.cn/#/Integrated/index" target="_blank">{{ $store.state.settings.caseNumber }}</a> -->
			  <span class="">技术支持：山东天地寰宇信息科技有限公司</span>
			</div>
		</div>

		<div class="background-vid">
			<canvas id="bg-a"></canvas>
			<div id="dotcontainer"></div>
		</div>
	</div>
</template>

<script>
import Config from '@/settings'
import { getCodeImg } from '@/api/login'
import Cookies from 'js-cookie'
import qs from 'qs'
import { encrypt } from '@/utils/rsaEncrypt'
import '@/assets/icons' // icon
import {THREE} from '@/assets/js/three.min'
import logo_1 from '@/assets/images/logo/i1.png';
import logo_2 from '@/assets/images/logo/i2.png';
import logo_3 from '@/assets/images/logo/i3.png';

export default {
	name: 'Login',
	data() {
		return {
			//Background:'',
			codeUrl: '',
			cookiePass: '',
			loginForm: {
				username: '',
				password: '',
				rememberMe: false,
				code: '',
				uuid: '',
			},
			loginRules: {
				username: [{ required: true, trigger: 'blur', message: '用户名不能为空' }],
				password: [{ required: true, trigger: 'blur', message: '密码不能为空' }],
				code: [{ required: true, trigger: 'change', message: '验证码不能为空' }],
			},
			loading: false,
			redirect: undefined
		}
	},
	watch: {
		$route: {
		  handler: function(route) {
			const data = route.query
			if (data && data.redirect) {
			  this.redirect = data.redirect
			  delete data.redirect
			  if (JSON.stringify(data) !== '{}') {
				this.redirect = this.redirect + '&' + qs.stringify(data, { indices: false })
			  }
			}
		  },
		  immediate: true
		}
	},
	created() {
		// 获取验证码
		this.getCode()
		// 获取用户名密码等Cookie
		this.getCookie()
		// token 过期提示
		this.point();

		this.runWave();
	},

	mounted() {
		console.log('THREE ________________ ', THREE);

		
	},
	methods: {
		getCode() {
		  getCodeImg().then(res => {
			this.codeUrl = res.img
			this.loginForm.uuid = res.uuid
		  })
		},
		getCookie() {
		  const username = Cookies.get('username')
		  let password = Cookies.get('password')
		  const rememberMe = Cookies.get('rememberMe')
		  // 保存cookie里面的加密后的密码
		  this.cookiePass = password === undefined ? '' : password
		  password = password === undefined ? this.loginForm.password : password
		  this.loginForm = {
			username: username === undefined ? this.loginForm.username : username,
			password: password,
			rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
			code: '',
		  }
		},
		handleLogin() {
		  this.$refs.loginForm.validate(valid => {
			const user = {
			  username: this.loginForm.username,
			  password: this.loginForm.password,
			  rememberMe: this.loginForm.rememberMe,
			  code: this.loginForm.code,
			  uuid: this.loginForm.uuid,
			}
			if (user.password !== this.cookiePass) {
				user.password = encrypt(user.password);
			};

			if (valid) {
			  this.loading = true
			  if (user.rememberMe) {
				Cookies.set('username', user.username, { expires: Config.passCookieExpires })
				Cookies.set('password', user.password, { expires: Config.passCookieExpires })
				Cookies.set('rememberMe', user.rememberMe, { expires: Config.passCookieExpires })
			  } else {
				Cookies.remove('username')
				Cookies.remove('password')
				Cookies.remove('rememberMe')
			  }
			  this.$store.dispatch('Login', user).then((res) => {
				this.loading = false
				if(/* res.head.code !== '0000' */ res.code){
					return this.$notify({
						title: '提示',
						message: res.msg,
						type: 'warning',
						duration: 5000
					})
				};
				//this.$router.push({ path: this.redirect || '/' })
				window.location.href = this.redirect || '/';
			  }).catch((err) => {
				this.loading = false
				this.getCode()
			  })
			} else {
			  console.log('error submit!!')
			  return false
			}
		  })
		},
		point() {
		  const point = Cookies.get('point') !== undefined
		  if (point) {
			this.$notify({
			  title: '提示',
			  message: '当前登录状态已过期，请重新登录！',
			  type: 'warning',
			  duration: 5000
			})
			Cookies.remove('point')
		  }
		},

		runWave(){
			// Wave
			(function(){
				var totalW = window.innerWidth, 
					totalH = window.innerHeight, 
					particles, particle, 
					count = 0, 
					SEPARATION = 100, 
					AMOUNTX = 100,		// 横向数量 50
					AMOUNTY = 50,		// 纵向数量 50
					fineLogined = false;
				var dotcamera, dotscene, dotrenderer;

				function onWindowResize() {
					totalW = window.innerWidth;
					totalH = window.innerHeight;
					//camera.aspect = totalW / totalH;
					//camera.updateProjectionMatrix();
					var a = totalH / 3;
					//dotcamera.aspect = totalW / a;
					//dotcamera.updateProjectionMatrix();
					dotrenderer.setSize(totalW, a);
					dotrender()
				}
				function initParticleObjects() {
					var dotcontainer = document.getElementById("dotcontainer");
					var c = totalH / 3;
					dotcamera = new THREE.PerspectiveCamera(75,totalW / c,1,1e4);
					dotcamera.position.z = 1e3;
					dotscene = new THREE.Scene;
					particles = [];
					for (var e = Math.PI * 2, d = new THREE.ParticleCanvasMaterial({
						color: '#62AAFF',
						program: function(a) {
							a.beginPath();
							a.globalAlpha = .6;
							a.arc(0, 0, 1, 0, e, true);
							a.fill()
						}
					}), f = 0, a = 0; a < AMOUNTX; a++)
						for (var b = 0; b < AMOUNTY; b++) {
							particle = particles[f++] = new THREE.Particle(d);
							particle.position.x = a * SEPARATION - AMOUNTX * SEPARATION / 2;
							particle.position.z = b * SEPARATION - AMOUNTY * SEPARATION / 2;
							dotscene.add(particle)
						}
					dotrenderer = new THREE.CanvasRenderer({
						alpha: true
					});
					dotrenderer.setSize(totalW, c);
					dotcontainer.appendChild(dotrenderer.domElement);
					dotanimate()
				};
				function dotanimate() {
					setTimeout(dotanimate, 60);
					dotrender()
				};
				function dotrender() {
					var rangeX = 70, rangeY = 70;	// 波浪幅度
					var currentX = -22;
					var currentY = -450;
					dotcamera.position.x += (currentX - dotcamera.position.x) * .05;
					dotcamera.position.y += (-currentY - dotcamera.position.y) * .05;
					
					// 像是设置视角
					//dotcamera.lookAt(scene.position);		// scene.position = {x: 0, y: 0, z: 0}
					dotcamera.lookAt({x: 0, y: 0, z: 0})
					for (var c = 0, a = 0; a < AMOUNTX; a++)
						for (var b = 0; b < AMOUNTY; b++) {
							particle = particles[c++];
							particle.position.y = Math.sin((a + count) * .3) * rangeX + Math.sin((b + count) * .5) * rangeY;
							particle.scale.x = particle.scale.y = (Math.sin((a + count) * .3) + 1) * 2 + (Math.sin((b + count) * .5) + 1) * 2.5
						}
					dotrenderer.render(dotscene, dotcamera);
					count += .1
				};
				qf(function(){
					var camera = new THREE.PerspectiveCamera(40,totalW / totalH,1,1e4);
					camera.position.z = 1300;
					qf.resize(function(){onWindowResize()});
					initParticleObjects()
				});
			})();
			
			// element
			qf(function(){
				var Stars = function(el){
					el = typeof el === "string" ? document.getElementById(el) : el;
					el.width = window.innerWidth;
					el.height = window.innerHeight;
					var wRatio = el.width / window.screen.width;
					var hRatio = el.height / window.screen.height;
					var w = window.screen.width;
					var h = window.screen.height;
					var ctx = el.getContext("2d");
					var id = 0, ELMaps = {Star:{},Codes:{},Name:{},Dot:{},};
					var construct = function(){
						var self = this;
						this.MapList = {Star:[],Codes:[],Name:[],Dot:[],};
						this.logoList = [new Image(), new Image(), new Image()];
						this.logoList[0].src = logo_1;
						this.logoList[1].src = logo_2;
						this.logoList[2].src = logo_3;
						//ctx.scale(wRatio, hRatio);
						window.addEventListener('resize', function(){
							el.width = window.innerWidth;
							el.height = window.innerHeight;
							wRatio = el.width / window.screen.width;
							hRatio = el.height / window.screen.height;
							self.drawFrame();
						}, false);
						//浏览器切换事件
						document.addEventListener('visibilitychange', function(){
							if(document.visibilityState === 'hidden'){ // 离开当前tab标签
								window.cancelAnimationFrame(self.requestFrame);
								delete self.requestFrame;
								self.timerA.stop();
							}else{
								self.timerA.setTime(800);
								!self.requestFrame && self.loop() && self.timerA.start();
							}
						});
						(self.loop = function(){
							self.drawFrame();
							return self.requestFrame = window.requestAnimationFrame(self.loop);
						})();
						this.autoPlay();this.timerA.start();
					};
					construct.prototype = {
						init: function(){
							var self = this;
						},
						startPlay:function(){
							this.timerA.start();
						},
						stopPlay:function(){
							this.timerA.stop();
						},
						startDraw: function(){
							!this.requestFrame && this.loop() && this.startPlay();
						},
						stopDraw: function(){
							window.cancelAnimationFrame(this.requestFrame);
							delete this.requestFrame;
							this.stopPlay();
						},
						autoPlay: function(){
							var self = this;
							self.timerA = new qf.Async.timerCtrl(100, 'timerA');
							self.timerA(function(){
								self.timerA.setTime(Math.random()*2000 + 500);
								var starNum = ~~(Math.random()*3);
								for(var i=0; i<starNum; i++){star.createStar()};

								var codeNum = ~~(Math.random()*6);
								for(var i=0; i<codeNum; i++){star.createCodes()};

								// name
								!self.MapList.Name[0] && !~~(Math.random()*4) && star.createName();

								var dotNum = ~~(Math.random()*8) + 1;
								for(var i=0; i<dotNum; i++){star.createDot()};
							});
							self.timerA.stop();
						},
						createStar:function(x, y){
							var lightVal = ~~(Math.random() * 70);		// 亮度浮动2分之1的机率大于50
							var maxLight = lightVal > 50 ? 50 : lightVal + 40;
							var id = this.getId() + '';
							var size = 5 + ~~(Math.random() * 21);
							var obj = {
								type:'star',
								id:id,
								x: x || ~~(w * Math.random()),
								y: y || h * Math.random() + h * .3,
								ySpeed: 0.3 + (8 * Math.random())/10,
								size:size,
								thick:1.4 + ~~(Math.random() * (size+1)) / 10,
								tooth:4,
								light:~~(Math.random() * maxLight),
								maxLight:maxLight,
								flashSpeed: ~~(Math.random() * 3) + 1,
								color:'white',
							};this.addEls('Star', id, obj);
						},
						createCodes: function(){	
							var id = this.getId() + '';
							var sizeDev = ~~(Math.random() * 40)/10;
							var obj = {
								textLength:18 + ~~(8 * Math.random()),
								type:'code',
								id:id,
								x: w * Math.random(),
								y: h-(50 * Math.random()),
								speed: 2.5 + ~~(10 * Math.random())/10,
								size: 7 + sizeDev,
								r: 8 + sizeDev*1.5,
								light:~~(Math.random() * 100),
								color:'white',
								odds:1,
							};this.addEls('Codes', id, obj);
						},
						createName: function(){
							var id = this.getId() + '', size = 28;
							var textArr = ~~(Math.random()*2) ? 'JING HE'.split('') : 'GEMHO'.split('');
							var obj = {
								id:id,
								textArr:textArr,
								type:'name',
								x: ~~(w * Math.random()),
								y: h+textArr.length * size,
								speed: 1.5 + (6 * Math.random())/10,
								size:size,
								light:~~(Math.random() * 100),
								color:'#38648A',
							};this.addEls('Name', id, obj);
						},
						createDot:function(x, y){
							var type = ~~(25 * Math.random()) ? 'dot' : 'logo';
							var r = type === 'dot' ? 5 + 14*Math.random() : 13 + 6*Math.random();
							var id = this.getId() + '';
							var obj = {
								id:id,
								type:type,
								x: ~~(w * Math.random()),
								y: h+r*2,
								speed: 1.1 + (8 * Math.random())/10,
								r:r,
								img:this.logoList[~~(3 * Math.random())],
								color:'#38648A',
							};this.addEls('Dot', id, obj);
						},
						addEls: function(name, id, obj){
							var map = ELMaps[name];
							map[id] = obj;this.MapList[name] = Object.keys(map);return obj;
						},
						drawFrame: function(x, y){
							ctx.clearRect(0, 0, w, h);
							for(var name in ELMaps){
								var map = ELMaps[name];
								if(Object.keys(map).length){
									for(var key in map){
										var item = map[key];
										this['draw'+name](item);
									};
								};
							};
						},
						drawStar: function(opts){
							var x = this.scaleX(opts.x), y = this.scaleY(opts.y), maxLight = opts.maxLight;
							opts.light %= (maxLight * 2);

							// 半值
							//var lightHalf = maxLight / 2;
							var light = maxLight - Math.abs(maxLight- (opts.light+=opts.flashSpeed));
							var angle = 360/(opts.tooth*2);
							var arr = [];
							for(var i=0;i<opts.tooth*2;i++){
								var starObj = {};
								if(i%2==0){
									starObj.x = x + opts.size*Math.cos(i*angle*Math.PI/180);
									starObj.y = y + opts.size*Math.sin(i*angle*Math.PI/180);
								}else{
									starObj.x = x + opts.thick*Math.cos(i*angle*Math.PI/180);
									starObj.y = y + opts.thick*Math.sin(i*angle*Math.PI/180);
								};arr.push(starObj);
							};
							var devVal = 0.5;
							ctx.globalAlpha = light / 100;
							ctx.beginPath();
							ctx.fillStyle= opts.color;
							ctx.strokeStyle = opts.color;
							ctx.moveTo(arr[0].x+devVal,arr[0].y+devVal);
							for(var i=0;i<arr.length;i++){
								ctx.lineTo(arr[i].x+devVal, arr[i].y+devVal);
							}
							ctx.closePath();
							ctx.fill();

							opts.y -= opts.ySpeed;
							if((opts.y + opts.size) < 0){
								this.removeEls('Star', opts.id);
							};
						},
						drawCodes: function(opts){
							var x = this.scaleX(opts.x), y = this.scaleY(opts.y), h = opts.size;
							opts.codeArr = !opts.odds ? this.getCodes(opts.textLength) : opts.codeArr || [];

							var codeLength = opts.codeArr.length;
							var sumH = (opts.textLength || codeLength) * h;
							var textrgrd = ctx.createLinearGradient(x, y, x, y+sumH);
							textrgrd.addColorStop(0.1, "#1977d1");
							textrgrd.addColorStop(0.50, "rgba(31, 120, 208, .6)");
							textrgrd.addColorStop(0.75, "rgba(31, 120, 208, .2)");
							textrgrd.addColorStop(1, "transparent");

							var r = opts.r || 12, diam = r*2;
							var devX = h/2 - h*0.19;
							var rgrd = ctx.createRadialGradient(x+devX, y-r, 0, x+devX, y-r, r);
							rgrd.addColorStop(0,"rgba(0,131,241, 1)");
							rgrd.addColorStop(0.2,"rgba(22,117,224, 1)");
							rgrd.addColorStop(0.5,"rgba(22,117,224, .6)");
							rgrd.addColorStop(0.9,"transparent");
							
							ctx.globalAlpha = 1;
							// dot
							ctx.fillStyle = rgrd;
							ctx.fillRect(x-r+devX, y-diam, diam, diam);
							
							// text
							ctx.fillStyle = textrgrd;
							ctx.font = 'normal '+h+"px 'Open Sans', 'PingFang SC', Helvetica, Arial, sans-serif";
							for(var i=0; i<codeLength; i++){
								var word = opts.codeArr[i];
								var textY = y + h * i;
								ctx.fillText(word, x, textY);
							};
							opts.odds++ && (opts.odds %= 3);
							opts.y = opts.y - opts.speed || opts.speed / 100;
							if((opts.y + sumH) < 0){this.removeEls('Codes', opts.id);};
						},
						drawName: function(opts){
							var x = this.scaleX(opts.x), y = this.scaleY(opts.y), h = opts.size;
							var textArr = opts.textArr;
							var sumH = (textArr.length-0) * h;
							ctx.save();
							ctx.translate(x, y);
							ctx.rotate(0.017453293 * 90, 0.017453293 * 90);
							ctx.fillStyle = opts.color;
							ctx.globalAlpha = 1;
							ctx.font = 'normal '+ opts.size+"px 'Open Sans', 'PingFang SC', Helvetica, Arial, sans-serif";
							var len = textArr.length;
							for(var i=0; i<len; i++){
								var word = textArr[i];
								var textY = (0 - sumH / 2) + (h-5) * i;
								ctx.fillText(word, textY, h/2);
							};
							ctx.restore();
							opts.y = opts.y - opts.speed || opts.speed / 100;
							if((opts.y + sumH) < 0){this.removeEls('Name', opts.id);};
						},
						drawDot: function(opts){
							var x = this.scaleX(opts.x), y = this.scaleY(opts.y), r = opts.r;
							ctx.globalAlpha = 1;
							if(opts.type === 'dot'){
								var rgrd = ctx.createRadialGradient(x , y, 0 , x , y , r);
								rgrd.addColorStop(0,"rgba(93,168,254, 1)");
								rgrd.addColorStop(0.15,"rgba(105,174,255, 1)");
								rgrd.addColorStop(0.3,"rgba(105,174,255, 1)");
								rgrd.addColorStop(1,"transparent");
								ctx.fillStyle = rgrd;
								ctx.fillRect(x-r, y-r, r*2, r*2);
							}else{
								var h = r*2;
								var w = r*2;
								ctx.save();
								ctx.beginPath();
								var rgrd = ctx.createRadialGradient(x, y, 0, x, y, r);
								rgrd.addColorStop(0, "rgba(255,255,255, 1)");
								rgrd.addColorStop(0.5, "rgba(255,255,255, .8)");
								rgrd.addColorStop(1, "rgba(255,255,255, .3)");
								ctx.fillStyle = rgrd;
								ctx.arc(x, y, r, 0, 2 * Math.PI, false);
								ctx.fill();
								ctx.clip();
								ctx.drawImage(opts.img, x-r, y-r, r*2, r*2);
								ctx.restore();
								ctx.closePath();
							};
							
							var speed = opts.speed;
							opts.y = opts.y - speed || speed / 100;
							if((opts.y + r) < 0){this.removeEls('Dot', opts.id);};
						},
						removeEls: function(name, id){
							var map = ELMaps[name];
							delete map[id];this.MapList[name] = Object.keys(map);
						},
						getId: function(){return id++;},
						getCodes: function(len){
							len = len || 1;
							var hexArr = "0123456789ABCDEF".split(""), hexNum = hexArr.length, arr = [];
							for(var i=0; i<len; i++){arr.push(hexArr[~~(Math.random() * hexNum)])};return arr;
						},
						scaleX: function(val){return val*wRatio || 0},
						scaleY: function(val){return val*hRatio || 0},
					};
					return new construct();
				};
				var star = new Stars('bg-a');
			});
		},
	}
}
</script>

<style rel="stylesheet/scss" lang="scss" scope>
	.login {
		height:100%;background-size:cover;position:relative;

		/* .background-vid{
			position:absolute;
			top:50%;left:50%;min-width:100%;min-height:100%;
			width:auto;height:auto;z-index:0;transform:translateX(-50%) translateY(-50%);
		} */
		
		.background-vid{
			position:absolute;top:0;left:0;height:100%;width:100%;z-index:0;
			#dotcontainer{position:absolute;z-index:2;bottom:0;}
			#bg-a{
				position:absolute;top:0;left:0;height:100%;width:100%;z-index:1;
				background-color:#011638;
			}
		}
		

		.login-ctn{
			position:absolute;top:-70px;left:0;height:100%;width:100%;z-index:1;
			display:flex;justify-content:center;align-items:center;flex-direction:column;
		}
		
		.headder{
			margin-bottom:.48rem;text-align:center;
			h2, h4{
				margin:0;padding:0;line-height:1;background-image:-webkit-linear-gradient(top, #fff, #a2deff, #23a5f9);
				-webkit-background-clip:text;-webkit-text-fill-color:transparent;
			}
			h2{font-size:46px;letter-spacing:.06rem;}
			h4{font-size:20px;margin-top:.20rem;}
		}

		.logo-place{
			position:relative;
			/* width:9.68rem;height:5.56rem;margin:2.01rem auto 0; */
			width:720px;height:410px;
			background:no-repeat top center url('~@/assets/images/login_adorn2.png');background-size:100% 100%;

			.figure{
				position:absolute;top:77px;left:50px;height:246px;width:300px;
				img{display:block;border:0;width:100%;}
			}
		}

		.ctn-place{
			position:absolute;top:130px;right:.06rem;height:auto;width:337px;
			flex:1;display:flex;
			
			.inbox-range{
				flex:1;
				.ctn-fix{width:267px;margin:0 auto;}
			}

			.login-form {
				.el-input {
					input {
						height:40px;padding-left:30px;
						background-color:#1042a1 !important;color:#fff;border-color:#085fa2;
					}
				}
				.input-icon{
					height:40px;width:18px;margin-left:2px;
				}

				.el-form-item__content{
					line-height:40px;
				}
				
				.el-form-item{
					margin-bottom:.35rem;
					&:last-child{margin-bottom:0}
					.el-select{width:100%;}
				}
			}
		}
		
		.logo-title{
			position:absolute;top:12px;left:0;height:auto;width:100%;text-align:center;cursor:default;font-size:18px;line-height:1;letter-spacing:10px;color: rgb(56, 230, 255);text-shadow:0px 0px 2px rgb(56 230 255);
		}
		.subtitle{
			position:absolute;top:64px;left:0;height:auto;width:100%;text-align:center;cursor:default;font-size:24px;line-height:1;letter-spacing:10px;color:#b1edf8;
		}
	}
	
	.login-code {
		width: 33%;
		display: inline-block;
		height: 38px;
		float: right;
		img{
		  cursor: pointer;
		  vertical-align:middle
		}
	}
</style>
