<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>
</template>

<script>
	import {
		login,
		getUserInfo,
		selectProject,
		selectOrangaized,
		getOrganizedProjectList,
		getImgCode,
		sendPhoneCode
	} from '@/httpApi/loginRegister';
	import {
		bindProjectDetail
	} from '@/httpApi/organization'
	import {
		getProjectDetailById
	} from '@/httpApi/space'
	import {
		getIdentityResource
	} from '@/httpApi/system'
	import {
		setToken,
		setComment
	} from '@/uitls/auth';
	export default {
		data() {
			return {
				loginForm: {
					phone: '18888888888',
					code: '8',
					phoneCode: '888888'
				},
				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'
					}]
				},
			};
		},
		created() {
			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;
								let organized = this.testOrganized(user);
								this.selectOrganized(organized);
								this.$store.dispatch('app/changeOrganization', organized);
								this.$store.dispatch('app/changeUser', user);
								this.getUserProjectList(user.projectId);
							} else {
								this.loginLoading = false;
							}
						})
					} else {
						this.loginLoading = false;
					}
				})
			},
			testOrganized(data) {
				let organized = !data.organization ? data.organizationList[0] : data.organization;
				return organized;
			},
			getUserProjectList(projectId) {
				bindProjectDetail({
					userId: this.$store.getters.user.userId
				}).then(res => {
					if (res.state) {
						let clientData = res.data;
						bindProjectDetail({
							bindOrganizationId: this.$store.getters.organization.id
						}).then(res => {
							if (res.state) {
								let organizationData = res.data;
								getOrganizedProjectList(this.$store.getters.organization.id).then(res => {
									if (res.state) {
										let data = res.data || [];
										let obj = []
										if (this.$store.getters.user.phone == this.$store.getters
											.organization.contactTel) {
											obj = data.map(node => {
												return {
													projectId: node.id,
													projectName: node.name,
													organizationId: node.organizationId,
													organizationName: this.$store.getters
														.user.organizationList.find(item =>
															item.id === node.organizationId
														).name,
													identityId: 6
												}
											})
										}
										let projectList = clientData.concat(organizationData, obj)
											.sort((a, b) => a.projectId - b.projectId);
										console.log(projectList);
										if (projectList.length === 0) {
											this.loginLoading = false;
											this.$store.dispatch('app/changeMenuData', []);
											setComment(JSON.stringify([]));
											this.$store.dispatch('projectBase/changeProject', {});
											localStorage.setItem('projectId', 0);
											this.$store.dispatch('app/changeiIdentityId', 6);
											this.$message.success('登录成功');
											return this.$router.push('/space/project');
										} else {
											if (projectId === -1) {
												this.selectProject(projectList[0]);
											} else {
												this.selectProject(projectList.filter(project =>
													project.projectId === projectId)[0]);
											}
										}
									} else {
										this.loginLoading = false;
									}
								});
							} else {
								this.loginLoading = false;
							}
						})
					} else {
						this.loginLoading = false;
					}
				})
			},
			selectProject(item) {
				getProjectDetailById(item.projectId).then(res => {
					if (res.state) {
						let data = res.data;
						selectProject(data.id).then(res => {
							if (res.state) {
								let user = res.data;
								this.$store.dispatch('app/changeiIdentityId', item.identityId);
								this.$store.dispatch('projectBase/changeProject', data);
								localStorage.setItem('projectId', data.id);
								this.$store.dispatch('app/changeUser', user);
								if (item.identityId === 3 || user.userId === 1) {
									this.$store.dispatch('app/changeMenuData', user.resource ? JSON.parse(
										user.resource) : []);
									setComment(user.menu ? user.menu : JSON.stringify([]));
									this.loginLoading = false;
									this.$router.push('/');
									this.$message.success('登录成功');
								} else {
									getIdentityResource({
										identityId: item.identityId,
										type: data.type
									}).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('/');
											this.$message.success('登录成功');
										} else {
											this.loginLoading = false;
										}
									})
								}
							} else {
								this.loginLoading = false;
							}
						});
					} else {
						this.loginLoading = false;
					}
				})
			},
			selectOrganized(data) {
				selectOrangaized(data)
			}
		}
	};
</script>

<style lang="scss">

</style>