<template>
	<view class="uni-common-mt container">
		<view class="title">欢迎使用乐享运维</view>

		<!-- 用户名输入框 -->
		<view class="input-group">
			<uni-easyinput v-model="userName" placeholder="请输入用户名"></uni-easyinput>
		</view>

		<!-- 密码输入框-->
		<view class="input-group">
			<uni-easyinput type="password" v-model="passWord" placeholder="请输入密码"></uni-easyinput>
		</view>
		<!-- 登录按钮 -->
		<button type="primary" class="login-button" @click="login"><span>立即登录</span></button>
	</view>
</template>

<script>
	import {
		getCurrentInstance,
		ref
	} from 'vue';
	import {
		login as reqLogin,
		getUserZone,
		getUserOperation,
		getUserRegion
	} from '../../utils/api';
	export default {
		setup() {
			const userName = ref('');
			const passWord = ref('');
			// 登录功能
			const login = () => {
				if (!userName.value || !passWord.value) {
					uni.showToast({
						title: '请输入完整信息',
						icon: 'none',
					});
					return;
				}
				const param = {
					"username": userName.value,
					"password": passWord.value
				};
				// uni.switchTab({
				// 	url: '/pages/home/home', // 替换为你的Tab页面路径
				// });
				// return;
				// 使用请求方法
				reqLogin(param).then(
					(res) => {
						if (res.code==200) {
							// 登录成功 
							uni.setStorageSync('token',  res.data.token); 
							uni.setStorageSync('userInfo',  res.data.staff); 
							uni.showToast({
								title: '登录成功',
								icon: 'success',
							});
							getUserZone().then(res => {
								if(res.code == 200){
									uni.setStorageSync('userZone',  res.data); 
									getUserOperation().then(res => {
										if(res.code == 200){
											uni.setStorageSync('userOperation',  res.data);
											if(res.data.length > 0){
												uni.setStorageSync('userDefultOperation',  res.data[0]);
											}
											// 登录成功后跳转到Home Tab页面
											uni.switchTab({
												url: '/pages/mine/mine', // 替换为你的Tab页面路径
											});
										}
										else
										{
											uni.showToast({
												title: '获取用户区域信息失败',
												icon: 'none',
											});
										}
									});
								}
								else
								{
									uni.showToast({
										title: '获取用户区域信息失败',
										icon: 'none',
									});
								}
							});
						} else {
							console.log('OK3--user/login登录失败');
							uni.showToast({
								title: '登录失败',
								icon: 'none',
							});
						}
					},
					(error) => {
						console.log('登录异常--user/login');
						uni.showToast({
							title: '登录失败',
							icon: 'none',
						});
					}
				);
			};
			
			return {
				userName,
				passWord,
				login
			};
		},
	};
</script>

<style scoped>
	.container {
		padding: 20px;
	}

	.container .title {
		font-size: 20px;
		font-weight: 600;
		letter-spacing: 3px;
		margin-top: 20%;
		margin-bottom: 30%;
	}

	.input-group {
		margin-bottom: 30px;
	}

	.input-container {
		display: flex;
		width: 100%;
	}


	.login-button {
		margin-top: 80px;
		background-color: #007aff;
	}
</style>