<template>
	<view class="login">
		<view class="content">
			<!-- 头部logo -->
			<view class="header">
				<image :src="`../../static/123.png`"></image>
			</view>
			<!-- 主体表单 -->
			<view class="main">
				<wInput v-model="username" type="text" placeholder="用户名" :focus="isFocus"></wInput>
				<wInput v-model="password" type="text" placeholder="登录密码"></wInput>
			</view>
			<wButton class="wbutton" text="登 录" :rotate="isRotate" @click="startLogin"></wButton>
			<view style="height: 100rpx;"></view>
		</view>
	</view>
</template>

<script>
import wInput from '../../components/watch-login/watch-input.vue'
import wButton from '../../components/watch-login/watch-button.vue'
import API from '../../api/index'
var _self
var code
	export default {
		data() {
			return {
				logoImage:'',
				username: 'admin', //用户/电话
				password: '1111111', //密码
				isRotate: false, //是否加载旋转
				isFocus: true // 是否聚焦
			};
		},
		components: {
			wInput,
			wButton,
		},
		mounted() {

		},
		onLoad() {
			_self = this
			_self.isLogin()

			wx.login({
				success(res) {
					if (res.code) {
						code = res.code
					}
				}
			})
		},
		methods: {
			isLogin() {
				//判断缓存中是否登录过，直接登录
				try {
					const token = uni.getStorageSync('equipment_token');
					const equipmentManage = uni.getStorageSync('equipment_manage');
					if (token) {
						//有登录信息
						getApp().globalData.token = token
						getApp().globalData.equipmentManage = equipmentManage
						const eventChannel = _self.getOpenerEventChannel()
						eventChannel.emit('isLoginFromLogin', {
							isLogin: true
						})

						uni.$emit('loginStatusEvent', {
							isLogin: true
						})
					}
				} catch (e) {
					// error
				}
			},
			startLogin(e) {
				//登录
				if (_self.isRotate) {
					//判断是否加载中，避免重复点击请求
					return false
				}

				if (_self.username.length == "") {
					uni.showToast({
						title: '用户名不能为空',
						icon: 'none',
						position: 'center'
					})
					return
				}
				if (_self.password.length < 5) {
					uni.showToast({
						title: '登录密码不正确',
						icon: 'none',
						position: 'center'
					})
					return
				}

				_self.isRotate = true
				uni.showLoading({
					title: '登录中.....'
				})

				uni.request({
					url: API.Login,
					method: 'POST',
					data: {
						username: _self.username,
						password: _self.password
					},
					header: {
						'content-type': 'application/json'
					},
					success: (res) => {
						uni.hideLoading()
						_self.isRotate = false
						console.log('登录用户响应返回数据信息:', res.data);

						// 检查响应是否有效
						if (!res.data) {
							_self.password = ''
							console.error('登录失败: 响应数据为空');
							uni.showToast({
								title: '登录失败: 服务器响应异常',
								icon: 'none',
								position: 'center'
							})
							return;
						}

						// 处理JSON响应
						let responseData = res.data;
						
						// 统一转换为对象格式（如果是字符串的话）
						if (typeof responseData === 'string') {
							try {
								responseData = JSON.parse(responseData);
							} catch (e) {
								console.error('解析响应数据失败:', e);
								uni.showToast({
									title: '登录失败: 服务器返回格式错误',
									icon: 'none',
									position: 'center'
								})
								return;
							}
						}

						// 根据code判断登录是否成功
						// 登录成功后增加本地存储
						if (responseData.code === 0 && responseData.msg === '登录成功') {
							// 登录成功，提取用户信息、token和过期时间
							const userInfo = responseData.data.user || {};
							const ID = userInfo.id || '';
							const token = responseData.data.token || '';
							const expireAt = responseData.data.expiresAt || '';
							const building = userInfo.building || '';
							const room = userInfo.room || '';
							const pen = userInfo.pen || '';
							
							// 设置全局登录状态和信息
							const app = getApp();
							// 确保globalData对象存在
							if (!app.globalData) {
							  app.globalData = {};
							}
							
							// 统一设置全局数据
							app.globalData.ID = ID;
							app.globalData.token = token;
							app.globalData.userInfo = userInfo;
							app.globalData.isLoggedIn = true;
							app.globalData.expireAt = expireAt;
							// 设置全局数据
							app.globalData.building = building; // 栋舍编号
							app.globalData.room = room;       // 房间编号
							app.globalData.pen = pen;         // 栏位编号
							app.globalData.buildingName = building;
							app.globalData.roomName = room;
							app.globalData.penNo = pen;
							app.globalData.equipment_manage = '';
						
							// 持久化到本地存储，确保应用重启后仍能保留登录状态
							try {
							  uni.setStorageSync('equipment_token', token);
							  uni.setStorageSync('token_expire_time', expireAt);
							  uni.setStorageSync('user_info', userInfo);
							  uni.setStorageSync('building', building);
							  uni.setStorageSync('room', room);
							  uni.setStorageSync('pen', pen);
							  console.log('登录信息已保存到本地存储');
							} catch (e) {
							  console.error('保存登录信息到本地存储失败:', e);
							}
						
							// 触发登录状态更新事件
							uni.$emit('loginStatusEvent', {
							  isLogin: true
							});
							
							setTimeout(function() {
							  // 登录成功后跳转到首页，避免直接跳到个人中心导致页面切换问题
							  uni.switchTab({
							    url: '/pages/index/index',
							    success: function(res) {
							      console.log('跳转到首页成功:', res);
							      // 跳转成功后，通知首页加载用户编号信息
							      uni.$emit('reloadUserSettings', {});
							    },
							    fail: function(err) {
							      console.error('跳转到首页失败:', err);
							      // 如果switchTab失败，尝试使用redirectTo作为备选方案
							      if (err.errMsg && err.errMsg.includes('tabBar')) {
							        console.warn('switchTab失败，尝试使用redirectTo');
							        uni.redirectTo({
							          url: '/pages/index/index',
							          success: function(res) {
							            console.log('redirectTo到首页成功:', res);
							            uni.$emit('reloadUserSettings', {});
							          },
							          fail: function(redirectErr) {
							            console.error('redirectTo到首页也失败:', redirectErr);
							            uni.showToast({
							              title: '跳转失败，请手动进入首页',
							              icon: 'none'
							            });
							          }
							        });
							      }
							    }
							  })
							}, 500)
						} else {
							const errorMsg = responseData.msg || '登录失败';
							console.log('登录失败:', errorMsg, res);
							uni.showToast({
								title: errorMsg,
								icon: 'none',
								position: 'center'
							})
						}
					},
					fail: (err) => {
						console.error('登录请求失败:', err);
						uni.hideLoading();
						_self.isRotate = false;
						uni.showToast({
							title: '网络异常，请检查网络连接',
							icon: 'none',
							position: 'center'
						});
					}
				})
			},
			login_weixin() {
				//微信登录
				uni.showToast({
					icon: 'none',
					position: 'bottom',
					title: '...'
				});
			},
			forget() {
				uni.showModal({
					title: '提示',
					content: '请联系系统管理员',
					showCancel: false,
					confirmText: '知道了',
					confirmColor: '#333333'
				});
			}
		}
	}
</script>

<style>
	@import url("../../components/watch-login/css/icon.css");
	@import url("./css/main.css");
	page {
		background-color: #FFFFFF;
	}
</style>
