<template>
	<view class="main" style="background-image: url('../../static/login.png')">
		<view class="one">
			<text>基础研究动态管理平台</text>
			<text>登录</text>
		</view>
		<view class="two">
			<uni-forms ref="valiForm" :rules="rules" :modelValue="form" label-position="top">
				<uni-forms-item label="账号" required name="account">
					<uni-easyinput v-model="form.account" placeholder="请输入账号" />
				</uni-forms-item>
				<uni-forms-item label="密码" required name="password">
					<uni-easyinput type="password" v-model="form.password" placeholder="请输入密码" />
				</uni-forms-item>
			</uni-forms>
			<button class="button" type="primary" @click="onSubmit('valiForm')">登录</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				form: {
					account: '',
					password: ''
				},
				// 校验规则
				rules: {
					account: {
						rules: [{
							required: true,
							errorMessage: '账号不能为空'
						}]
					},
					password: {
						rules: [{
							required: true,
							errorMessage: '密码不能为空'
						}]
					}
				},
			}
		},
		onShow: function(e) {
			const that = this;
			that.searchToken();
		},
		methods: {
			searchToken() {
				const that = this;
				try {
					const res = uni.getStorageSync('token');
					if (res) {
						uni.reLaunch({
							url: `/pages/home/index`
						})
					}
				} catch (e) {
					uni.showToast({
						title: err.errmsg,
						icon: 'error',
						duration: 2000
					});
				}
			},
			// 登录
			onSubmit(ref) {
				const that = this;
				that.$refs[ref].validate().then(async form => {
					const arr = await that.$api(`/admin/login`, 'POST', form, 'jcyjdtglpt');
					if (arr.errcode == '0') {
						uni.setStorage({
							key: 'token',
							data: arr.data,
							success: function(res) {
								uni.reLaunch({
									url: `/pages/home/index`
								})
							},
							fail: function(err) {
								console.log(err);
							}
						})
					} else {
						uni.showToast({
							title: arr.errmsg,
							icon: 'none'
						})
					}
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.main {
		display: flex;
		flex-direction: column;
		width: 100vw;
		height: 100vh;
		background-size: cover;
		background-repeat: no-repeat;
		background-position: center;

		.one {
			padding: 30vw 10vw 20vw 10vw;
			text-align: center;
			font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
			font-size: var(--font20Size);
		}

		.two {
			padding: 2vw;

			.button {
				background: #007aff;
				border-radius: 30px;
			}
		}
	}
</style>