<template>
	<div class="login-box">
		<div class="login-title">
			<div class="login-title-value">登录红链</div>
			<div class="login-title-line"></div>
		</div>
		<div class="login-form">
			<el-form :model="loginForm" :rules="loginRules" status-icon ref="loginForm" label-position="left">
				<el-form-item prop="phone">
					<el-input type="text" prefix-icon="iconfont huifont-shoujihao" v-model="loginForm.phone"
						placeholder="手机号" maxlength="11">
					</el-input>
				</el-form-item>
				<el-form-item prop="code" class="image-item">
					<el-input type="text" prefix-icon="iconfont huifont-tuxingyanzhengma" v-model="loginForm.code"
						placeholder="图片验证码" maxlength="4"></el-input>
					<img v-if="codeImg" :src="codeImg" alt="图片验证码" class="code-image" @click="imgCodeFunc">
				</el-form-item>
				<el-form-item prop="phoneCode" class="phone-code">
					<el-input type="number" prefix-icon="iconfont huifont-duanxinyanzhengma"
						v-model="loginForm.phoneCode" placeholder="短信验证码"
						oninput="if(value.length > 6) value=value.slice(0, 6)"></el-input>
					<div :class="codeName === '获取验证码'?'get-code-btn' : 'get-code-btn-disabled get-code-btn'"
						@click="getPhoneCode">
						{{codeName}}
					</div>
				</el-form-item>
			</el-form>
			<el-button type="primary" @click="loginSubmit" :loading="loginLoading">登录</el-button>
		</div>
		<div class="register">
			<span @click="$router.push('/loginRegister/password')">账号密码登录</span>
		</div>
	</div>
</template>

<script>
	import {
		login,
		getImgCode,
		sendPhoneCode,
		getUserInfo,
		selectOrangaized
	} from '@/httpApi/loginRegister';
	import {
		getProjectListByIdentity
	} from '@/httpApi/space'
	import {
		getIdentityResource
	} from '@/httpApi/system'
	import {
		setToken,
		setComment
	} from '@/uitls/auth';
	export default {
		data() {
			return {
				loginForm: {
					phone: '',
					code: '',
					phoneCode: ''
				},
				loginLoading: false,
				codeImg: '',
				codeName: '获取验证码', //获取验证码text
				isDisabled: false, //获取验证码按钮状态
				loginRules: {
					code: [{
						required: true,
						message: '请输入图片验证码',
						trigger: 'blur'
					}],
					phone: [{
						required: true,
						message: '请输入手机号',
						trigger: 'blur'
					}, {
						validator: (rule, value, callback) => {
							if (!/^1[123456789]\d{9}$/.test(value)) {
								callback(new Error("请输入正确的手机号"));
							} else {
								callback();
							}
						},
						trigger: 'blur'
					}],
					phoneCode: [{
						required: true,
						message: '请输入短信验证码',
						trigger: 'blur'
					}]
				},
			};
		},
		mounted() {
			localStorage.removeItem('chatToken')
			this.imgCodeFunc();
			if (this.$store.getters.codeNumber != 60) this.codeReset();
		},
		methods: {
			imgCodeFunc() {
				getImgCode().then(res => {
					if (res.state) {
						this.codeImg = res.data.pngBase64;
					}
				})
			},
			getPhoneCode() {
				if (this.isDisabled) return;
				this.$refs.loginForm.validateField('phone', valid => {
					if (!valid) {
						this.$refs.loginForm.validateField('code', valid => {
							if (!valid) {
								sendPhoneCode(this.loginForm.phone, this.loginForm.code).then(res => {
									if (res.state) {
										this.codeReset();
										this.$message.success('发送成功');
									}
								})
							}
						})
					}
				})
			},
			codeReset() {
				//重置获取验证码倒计时
				let codeNumber = this.$store.getters.codeNumber;
				codeNumber--;
				this.handleCode(codeNumber);
				let codeRestFn = setInterval(() => {
					codeNumber--;
					this.handleCode(codeNumber);
					if (codeNumber == 0) clearInterval(codeRestFn); //停止
				}, 1000);
			},
			handleCode(codeNumber) {
				//code操作
				this.codeName = codeNumber == 0 ? '获取验证码' : '重新获取' + codeNumber;
				this.isDisabled = codeNumber == 0 ? false : true;
				this.$store.dispatch('loginRegister/changeCodeNumber', codeNumber == 0 ? 60 : codeNumber);
			},
			loginSubmit() {
				if (this.loginLoading) return;
				this.loginLoading = true;
				this.$refs['loginForm'].validate(valid => {
					if (!valid) return this.loginLoading = false;
					this.loginFunc();
				})
			},
			loginFunc() {
				let postData = {
					phone: this.loginForm.phone,
					phoneCode: this.loginForm.phoneCode
				}
				login(postData).then(res => {
					if (res.state) {
						setToken(res.data.token);
						getUserInfo().then(res => {
							if (res.state) {
								let user = res.data;
								if (user.projectId === -1) {
									let organziation = user.organizationList.find(node => node
										.contactTel == user.phone);
									selectOrangaized(organziation)
									this.$store.dispatch('app/changeOrganization', organziation);
									this.$store.dispatch('app/changeUser', user);
									this.$store.dispatch('projectBase/changeProject', {});
									this.$store.dispatch('app/changeIdentity', {
										id: 6,
										name: '所有者',
										remark: '所有者'
									});
									localStorage.setItem('projectId', 0);
									return this.successLogin('/work/space/project');
								} else {
									this.$store.dispatch('app/changeOrganization', user.organization);
									this.$store.dispatch('app/changeUser', user);
									this.$store.dispatch('app/changeMenuData', user.resource ? JSON.parse(
										user.resource) : []);
									setComment(user.menu ? user.menu : JSON.stringify([]));
									this.initProjectData(user.projectId, user.identityId);
								}
							} else {
								this.loginLoading = false;
							}
						})
					} else {
						this.loginLoading = false;
					}
				})
			},
			initProjectData(projectId, identityId) {
				getProjectListByIdentity().then(res => {
					if (res.state) {
						if (res.data.length === 0) {
							this.$store.dispatch('projectBase/changeProject', {});
							this.$store.dispatch('app/changeIdentity', {
								id: 6,
								name: '所有者',
								remark: '所有者'
							});
							localStorage.setItem('projectId', 0);
							return this.successLogin('/work/space/project');
						}
						let project = projectId === -1 ? res.data[0] : res.data.find(node => node.id ===
							projectId);
						this.$store.dispatch('projectBase/changeProject', project);
						let identity = identityId === -1 ? project.projectListIdentity[0] : project
							.projectListIdentity.find(node => node.id === identityId);
						this.$store.dispatch('app/changeIdentity', identity);
						localStorage.setItem('projectId', projectId);
						this.successLogin('/');
					} else {
						this.loginLoading = false;
					}
				})
			},
			successLogin(url) {
				let item = this.$store.getters.identity;
				if (item.id === 3 || this.$store.getters.user.userId === 1) {
					this.loginLoading = false;
					this.$router.push(url);
					this.$message.success('登录成功');
				} else {
					getIdentityResource({
						identityId: item.id,
						type: this.$store.getters.project.type || 1
					}).then(node => {
						if (node.state) {
							let role = node.data[0] || {};
							this.$store.dispatch('app/changeMenuData', role
								.resource ? JSON.parse(role.resource) : []);
							setComment(role.menus ? role.menus : JSON.stringify(
								[]));
							this.loginLoading = false;
							this.$router.push(url);
							this.$message.success('登录成功');
						} else {
							this.loginLoading = false;
						}
					})
				}
			}
		}
	};
</script>

<style lang="scss">

</style>