<template>
	<view class="container">
		<view class="lists" v-if="login">
			<!-- 用户信息卡片 -->
			<view class="cu-card case user-card">
				<view class="cu-item">
					
					<view class="content">
						<view class="username">用户名: {{user.username}}</view>
						<view class="user-id" v-if="user.ID">ID: {{user.ID}}</view>
					</view>
				</view>
			</view>

			<!-- 功能列表 -->
			<view class="cu-list menu sm-border card-menu function-list">
				<view class="form-section">
					<picker :range="buildingList" @change="onBuildingChange">
					  <view class="form-item">
						<text class="label"><text class="fa fa-home"></text> 栋舍编号</text>
						<text class="value">{{ form.buildingName || '请选择栋舍' }}</text>
					  </view>
					</picker>

					<picker :range="roomList" @change="onRoomChange">
					  <view class="form-item">
						<text class="label"><text class="fa fa-door-open"></text> 房间编号</text>
						<text class="value">{{ form.roomName || '请选择房间' }}</text>
					  </view>
					</picker>

					<picker :range="Fieldnumber" @change="onFieldChange">
					  <view class="form-item">
						<text class="label"><text class="fa fa-th-large"></text> 栏位编号</text>
						<text class="value">{{ form.penNo || '请选择栏位' }}</text>
					  </view>
					</picker>
				</view>

				<view class="save-btn-container">
					<button class="cu-btn block save-btn" @click="saveSettings" style="background-color: #07c160;">
						<text class="fa fa-save margin-right-xs"></text> 保存设置
					</button>
					<button class="cu-btn block save-btn" @click="logout()" style="background-color: red;">
						<text class="fa fa-save margin-right-xs"></text> 退出登录
					</button>
				</view>
			</view>

		</view>
		<view v-else>
			<view class="empty nologin-content">
				<image src="../../static/nologin.png" mode="widthFix"></image>
				<view class="text-gray">请先登录账号</view>
				<button class="cu-btn block bg-black lg" @click="goLogin()">
					<text class="cuIcon-lock margin-right-xs"></text> 登录账号</button>
			</view>
		</view>
	</view>
</template>

<script>
import API from '../../api/index';
	// 移除全局变量声明，改为在方法内使用const声明
	export default {
		data() {
			return {
				login: false,
				user: {},
				avatar: '',
				managePhone: '',

				// 表单数据
				form: {
					buildingName: '',
					roomName: '',
					penNo: ''
				},

				// 动态从接口获取数据
				buildingList: [],
				roomList: [],
				Fieldnumber: []
			}
		},
		onShow() {
			const _self = this;
			const app = getApp();

			const isLogin = !!app.globalData.token;
			_self.login = isLogin;
			if (!isLogin) {
				wx.login({
					success(res) {
						if (res.code) {
							_self.goWeLogin(res.code);
						}
					}
				});
			} else {
				// 直接从全局状态获取用户信息
				_self.user = app.globalData.userInfo || {};
				_self.avatar = _self.user.avatar || '';
			}

		},
		methods: {
			// 获取栋舍列表
			fetchBuildingList() {
				const _self = this;
				const app = getApp();

				// 从服务器获取栋舍列表
				uni.request({
					url: API.getBuilding,
					method: 'GET',
					header: {
						"x-token": app.globalData.token || ''
					},
					success: (res) => {
          console.log(res.data.data)
						if (res.data && res.data.code === 0 && res.data.data && res.data.data.length > 0) {
							// 更新栋舍列表
							_self.buildingList = res.data.data.map(item => item.name || item.building_name);
							console.log('获取栋舍编号:', _self.buildingList);

							// 如果表单中没有选择栋舍，尝试使用全局数据或本地存储
							if (!_self.form.buildingName) {
								_self.form.buildingName = app.globalData.building || uni.getStorageSync('building') || '';
							}

							// 获取对应栋舍的房间列表
							_self.fetchRoomList();
						} else {
							console.error('get_building响应数据无效或为空:', res.data);
							// 使用默认栋舍列表
							_self.buildingList = [];
						}
					},
					fail: (err) => {
						console.error('获取栋舍列表失败:', err);
					}
				});
			},

			// 新增方法：获取最新用户信息
			// 修复fetchUserInfo方法，确保用户信息正确获取
			fetchUserInfo() {
			  const _self = this;
			  const app = getApp();
			  
			  // 从多个来源获取用户信息，增加可靠性
			  let userInfo = {};
			  
			  // 1. 优先从全局数据获取
			  if (app.globalData.userInfo && Object.keys(app.globalData.userInfo).length > 0) {
			    userInfo = app.globalData.userInfo;
			    console.log('从全局数据获取用户信息:', userInfo);
			  }
			  
			  // 2. 如果全局数据不可用，尝试从本地存储获取
			  if (!userInfo.username || !userInfo.ID) {
			    try {
			      const storedUserInfo = uni.getStorageSync('user_info') || {};
			      if (storedUserInfo && Object.keys(storedUserInfo).length > 0) {
			        userInfo = { ...userInfo, ...storedUserInfo };
			        console.log('从本地存储补充用户信息:', storedUserInfo);
			      }
			    } catch (e) {
			      console.error('读取本地存储用户信息失败:', e);
			    }
			  }
			  
			  // 3. 如果仍然缺少关键信息，尝试从token相关信息中提取
			  if (!userInfo.username) {
			    userInfo.username = app.globalData.username || '';
			  }
			  
			  if (!userInfo.ID) {
			    userInfo.ID = app.globalData.ID || '';
			  }
			  
			  // 记录获取到的用户信息，便于调试
			  console.log('最终获取的用户信息:', userInfo);
			  
			  // 更新页面数据
			  _self.user = userInfo;
			  
			  // 确保即使没有头像也不会出错
			  _self.avatar = userInfo.avatar || '';
			  
			  // 更新表单数据
			  _self.form.buildingName = app.globalData.building || app.globalData.buildingName || '';
			  _self.form.roomName = app.globalData.room || app.globalData.roomName || '';
			  _self.form.penNo = app.globalData.pen || app.globalData.penNo || '';
			  
			  console.log('更新后的表单数据:', _self.form);
			  
			  // 触发设置更新事件，通知其他组件
			  uni.$emit('settingsUpdated', {
			    building: _self.form.buildingName,
			    room: _self.form.roomName,
			    pen: _self.form.penNo
			  });
			},

			data() {
			  return {
			    login: false,
			    user: {
			      username: '', // 提供默认的用户名属性
			      ID: ''        // 提供默认的ID属性
			    },
			    avatar: '',
			    managePhone: '',
			    
			    // 表单数据
			    form: {
			      buildingName: '',
			      roomName: '',
			      penNo: ''
			    },
			
			    // 动态从接口获取数据
			    buildingList: [],
			    roomList: [],
			    Fieldnumber: []
			  }
			},

			// 增强onShow方法中的用户信息获取逻辑
			onShow() {
			  const _self = this;
			  const app = getApp();
			  
			  // 首先检查登录状态
			  const isLogin = !!app.globalData.token;
			  _self.login = isLogin;
			  
			  if (isLogin) {
			    // 获取栋舍列表
			    _self.fetchBuildingList();
			    // 获取最新用户信息
			    _self.fetchUserInfo();
			  } else {
			    // 尝试从本地存储恢复登录信息
			    const token = uni.getStorageSync('equipment_token') || '';
			    const expireAt = uni.getStorageSync('token_expire_time') || '';
			    const userInfo = uni.getStorageSync('user_info') || {};
			    
			    if (token && expireAt) {
			      // 恢复登录信息到全局数据
			      app.globalData.token = token;
			      app.globalData.expireAt = expireAt;
			      app.globalData.userInfo = userInfo;
			      app.globalData.isLoggedIn = true;
			      _self.login = true;
			      _self.fetchBuildingList();
			      _self.fetchUserInfo();
			      console.log('从本地存储恢复登录状态成功');
			    }
			  }
			},

			// 新增一个方法，用于手动刷新用户信息
			refreshUserInfo() {
			  const app = getApp();
			  console.log('手动刷新用户信息 - 当前全局数据:', app.globalData);
			  console.log('手动刷新用户信息 - 当前本地存储:', uni.getStorageSync('user_info'));
			  
			  this.fetchUserInfo();
			  this.fetchBuildingList();
			},
			// 获取房间列表
			fetchRoomList() {
				const _self = this;
				const app = getApp();

				// 获取房间列表
				uni.request({
					url: API.getRoom,
					method: 'GET',
					data: {
						building: _self.form.buildingName // 传递当前选择的栋舍
					},
          header: {
            "x-token": app.globalData.token || ''
          },
					success: (res) => {
						console.log('获取房间编号:', res);

						if (res.data && res.data.code === 0 && res.data.data && res.data.data.length > 0) {
							// 更新房间列表
							_self.roomList = res.data.data.map(item => item.name || item.room_name);

							// 如果表单中没有选择房间，尝试使用全局数据或本地存储
							if (!_self.form.roomName) {
								_self.form.roomName = app.globalData.room || uni.getStorageSync('room') || '';
							}

							// 获取对应房间的栏位列表
							_self.fetchPenList();
						} else {
							console.error('get_room响应数据无效或为空:', res.data);
							// 使用默认房间列表
							_self.roomList = [];
						}
					},
					fail: (err) => {
						console.error('获取房间列表失败:', err);
					}
				});
			},

			// 获取栏位列表
			fetchPenList() {
				const _self = this;
				const app = getApp();
				// 获取栏位列表
				uni.request({
					url: API.getPen,
					method: 'GET',
					data: {
						building: _self.form.buildingName,
						room: _self.form.roomName // 当前选择的房间
					},
					header: {
						'content-type': 'application/x-www-form-urlencoded',
						"x-token": app.globalData.token || ''
					},
					success: (res) => {
						console.log('获取栏位编号:', res);

						if (res.data && res.data.code === 0 && res.data.data && res.data.data.length > 0) {
							// 更新栏位列表
							_self.Fieldnumber = res.data.data.map(item => item.name || item.pen_name || item.pen_no);
							// 如果表单中没有选择栏位，尝试使用全局数据或本地存储
							if (!_self.form.penNo) {
								_self.form.penNo = app.globalData.pen || uni.getStorageSync('pen') || '';
							}
						} else {
							console.error('get_pen响应数据无效或为空:', res.data);
							// 使用默认栏位列表
							_self.Fieldnumber = [];
						}
					},
					fail: (err) => {
						console.error('获取栏位列表失败:', err);
					}
				});
			},

			loadFromStorage() {
			    const _self = this;
			    const app = getApp();
			    const globalUserInfo = app.globalData.userInfo;
			    _self.user = globalUserInfo;
			    _self.form.buildingName = app.globalData.building;
			    _self.form.roomName = app.globalData.room;
			    _self.form.penNo = app.globalData.pen;
			    console.log('从存储加载的表单buildingName:', _self.form.buildingName);
			    console.log('从存储加载的表单roomName:', _self.form.roomName);
			    console.log('从存储加载的表单penNo:', _self.form.penNo);
			},

			// 选择器方法
			onBuildingChange(e) {
			  const selectedValue = this.buildingList[e.detail.value];
			  this.form.buildingName = selectedValue;
			  console.log('栋舍选择已更新:', this.form.buildingName);
			  // 保存到login中定义的全局变量
			  getApp().globalData.building = selectedValue;
			  // 触发全局事件通知设置更新
			  uni.$emit('settingsUpdated');
			  // 获取对应栋舍的房间列表
			  this.fetchRoomList();
			},
			
			onRoomChange(e) {
			  const selectedValue = this.roomList[e.detail.value];
			  this.form.roomName = selectedValue;
			  console.log('房间选择已更新:', this.form.roomName);
			  // 保存到login中定义的全局变量
			  getApp().globalData.room = selectedValue;
			  // 触发全局事件通知设置更新
			  uni.$emit('settingsUpdated');
			  // 获取对应房间的栏位列表
			  this.fetchPenList();
			},
			
			onFieldChange(e) {
			  const selectedValue = this.Fieldnumber[e.detail.value];
			  this.form.penNo = selectedValue;
			  console.log('栏位选择已更新:', this.form.penNo);
			  // 保存到login中定义的全局变量
			  getApp().globalData.pen = selectedValue;
			  // 触发全局事件通知设置更新
			  uni.$emit('settingsUpdated');
			},

			// 保存设置到API
			saveSettings() {
				if (!this.form.buildingName || !this.form.roomName || !this.form.penNo) {
					return uni.showToast({
						title: '请选择完整的栋舍、房间和栏位信息',
						icon: 'none'
					});
				}

				const app = getApp();
				// 获取用户ID（优先从全局数据，其次从本地存储）
				const userId = app.globalData.userInfo?.ID || uni.getStorageSync('user_info')?.ID || '';
				const username = app.globalData.userInfo?.username || uni.getStorageSync('user_info')?.username || '';

				if (!userId) {
					console.error('用户ID不存在，无法保存设置');
					return uni.showToast({
						title: '请先登录',
						icon: 'none'
					});
				};
				uni.showLoading({
					title: '保存中...',
					mask: true
				});

				const submitData = {
					username: username,
					userid: userId,
					building: this.form.buildingName,
					room: this.form.roomName,
					pen: this.form.penNo
				};
				console.log('提交的数据:', submitData);

				// 发送请求到API
				uni.request({
					url: API.postUserSetup,
					method: 'POST',
					data: submitData,
					header: {
						'content-type': 'application/json',
						"x-token": app.globalData.token || uni.getStorageSync('token') || ''
					},
					timeout: 10000, // 设置10秒超时
					success: (res) => {
						if (res.data.code === 0) {
							uni.showToast({
								title: '保存成功',
								icon: 'success',
								duration: 3000 
							});
							// 更新全局数据
							app.globalData.building = submitData.building;
							app.globalData.room = submitData.room;
							app.globalData.pen = submitData.pen;
							// 更新本地存储
							uni.setStorageSync('building', submitData.building);
							uni.setStorageSync('room', submitData.room);
							uni.setStorageSync('pen', submitData.pen);
							// 触发设置更新事件
							uni.$emit('settingsUpdated', {
								building: submitData.building,
								room: submitData.room,
								pen: submitData.pen
							});
						} else {
							console.error('保存设置失败:', res.data);
							uni.showToast({
								title: res.data?.msg || '保存失败，请稍后重试',
								icon: 'none'
							});
						}
					},
					complete: () => {
						uni.hideLoading();
					}
				});
			},

			goWeLogin(code) {
				const _self = this;
				_self.$api.welogin({
					code
				}).then((res) => {
					getApp().globalData.token = res.data.token
					getApp().globalData.equipmentManage = res.data.equipment_manage
					
					// 保存到本地存储
					uni.setStorageSync('equipment_token', res.data.token)
					uni.setStorageSync('equipment_openid', res.data.openid)
					uni.setStorageSync('equipment_manage', res.data.equipment_manage)

					_self.login = true
					// 登录成功后从全局状态获取用户信息
					_self.user = getApp().globalData.userInfo || {};
					_self.avatar = _self.user.avatar || '';
					
					// 登录成功后刷新数据
					_self.fetchBuildingList();
					_self.fetchUserInfo();
				}).catch((err) => {
					console.error('登录失败:', err);
					uni.showToast({
						title: '登录失败，请稍后重试',
						icon: 'none'
					});
				})
			},
			goLogin() {
			const _self = this;
			uni.navigateTo({
				url: '/pages/login/login',
				events: {
					// 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
					isLoginFromLogin: function(data) {
						if (data && data.isLogin) {
							_self.isLoggedIn = true
							// 登录成功后从全局状态获取用户信息
							_self.user = getApp().globalData.userInfo || {};
							_self.avatar = _self.user.avatar || '';
						}
					}
				}
			})
			},
			// 添加退出登录方法
			logout() {
			  try {
			    // 清除全局数据
			    const app = getApp();
			    app.globalData.ID = '';
			    app.globalData.token = '';
			    app.globalData.userInfo = {};
			    app.globalData.isLoggedIn = false;
			    app.globalData.expireAt = '';
			    app.globalData.building = '';
			    app.globalData.room = '';
			    app.globalData.pen = '';
			    app.globalData.buildingName = '';
			    app.globalData.roomName = '';
			    app.globalData.penNo = '';
			    
			    // 清除本地存储
			    uni.removeStorageSync('equipment_token');
			    uni.removeStorageSync('token_expire_time');
			    uni.removeStorageSync('user_info');
			    uni.removeStorageSync('building');
			    uni.removeStorageSync('room');
			    uni.removeStorageSync('pen');
			    
			    console.log('退出登录成功，已清除所有登录信息');
			    
			    // 重置页面状态
			    this.login = false;
			    this.user = { username: '', ID: '' };
			    this.form = {
			      buildingName: '',
			      roomName: '',
			      penNo: ''
			    };
			    
			    // 跳转到登录页面
			    uni.redirectTo({
			      url: '/pages/login/login',
			      success: function() {
			        console.log('跳转到登录页面成功');
			      }
			    });
			  } catch (e) {
			    console.error('退出登录过程中发生错误:', e);
			    uni.showToast({
			      title: '退出登录失败，请重试',
			      icon: 'none'
			    });
			  }
			},
			clearStorage() {
			const _self = this;
			try {
				_self.login = false
				const app = getApp();
				// 清空全局数据
				app.globalData.token = '';
				app.globalData.equipmentManage = 0;
				app.globalData.userInfo = {};
				app.globalData.building = '';
				app.globalData.room = '';
				app.globalData.pen = '';
				app.globalData.buildingName = '';
				app.globalData.roomName = '';
				app.globalData.penNo = '';
				app.globalData.isLoggedIn = false;

				// 清空本地存储
				uni.setStorageSync('equipment_token', '');
				uni.setStorageSync('equipment_openid', '');
				uni.setStorageSync('equipment_manage', '');
				uni.setStorageSync('user_info', {});
				uni.setStorageSync('building', '');
				uni.setStorageSync('room', '');
				uni.setStorageSync('pen', '');
				uni.setStorageSync('buildingName', '');
				uni.setStorageSync('roomName', '');
				uni.setStorageSync('penNo', '');

				uni.$emit('loginStatusEvent', {
					isLogin: false
				})

				uni.showToast({
					title: '退出登录成功',
					icon: 'success'
				})

				// 直接跳转到登录页面，避免延迟导致的重复导航
				setTimeout(function() {
					uni.redirectTo({
						url: '/pages/login/login'
					})
				}, 500);
			} catch (e) {
				console.error('清除存储失败:', e);
				uni.showToast({
					title: '退出失败，请稍后再试',
					icon: 'none'
				})
			}
		},
			callManage() {
			const _self = this;
			let managePhone = _self.managePhone
			if (managePhone == '') {
				uni.showToast({
					title: '暂无管理员联系方式',
					icon: 'none'
				})
				return;
			}

			uni.makePhoneCall({
				phoneNumber: managePhone
			})
			}
		}
	}
</script>

<style lang="scss">
	.container {
	min-height: 100vh;
	background-color: #f5f5f5;
	// padding-bottom: 120rpx; /* 增加底部内边距确保按钮可见 */
	box-sizing: border-box;
	overflow: auto;
}

/* 用户信息卡片样式 */
.user-card {
	margin: 20rpx;
	border-radius: 20rpx;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
	transition: all 0.3s ease;
	overflow: hidden;
}

.user-card:hover {
	box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.12);
	transform: translateY(-5rpx);
}

.cu-item {
	display: flex;
	align-items: center;
	padding: 30rpx;
}

.avatar-container {
	width: 120rpx;
	height: 100rpx;
	border-radius: 50%;
	overflow: hidden;
	background-color: #f0f0f0;
	margin-right: 30rpx;
}

.avatar {
	width: 100%;
	height: 100%;
}

.avatar-placeholder {
	width: 100%;
	height: 100%;
	display: flex;
	align-items: center;
	justify-content: center;
	background-color: #f0f0f0;
	color: #999;
	font-size: 60rpx;
}

.content {
	flex: 1;
}

.username {
	font-size: 36rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 10rpx;
}

.user-id {
	font-size: 28rpx;
	color: #666;
}

.cu-list.menu-avatar>.cu-item:after {
	border: 0;
}

/* 表单区域样式 */
.form-section {
	margin: 0px 20rpx;
	padding: 25rpx;
	background-color: #ffffff;
	border-radius: 16rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.form-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 25rpx 0;
	border-bottom: 1rpx solid #f0f0f0;
}

.form-item:last-child {
	border-bottom: none;
}

.label {
	font-size: 28rpx;
	color: #333;
}

.value {
	font-size: 28rpx;
	color: #666;
}

/* 保存按钮样式 */
.save-btn-container {
	padding: 20rpx;
}

.save-btn {
	background-color: #07c160;
	color: white;
	border-radius: 44rpx;
	height: 88rpx;
	line-height: 88rpx;
	font-size: 32rpx;
	margin: 30rpx 20rpx;
	transition: all 0.3s ease;
	width: calc(100% - 40rpx);
}

.save-btn:hover {
	background-color: #06ad56;
	transform: scale(1.02);
}

.save-btn:active {
	transform: scale(0.98);
}

/* 功能列表样式 */
.function-list {
	margin: 0 20rpx 20rpx; /* 减小边距 */
	border-radius: 16rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.03);
}

.cu-list.card-menu .cu-item {
	padding: 20rpx; /* 减小内边距适应小屏幕 */
	transition: all 0.2s ease;
}

.cu-list.card-menu .cu-item:hover {
	background-color: #f9f9f9;
}

/* 退出登录按钮样式 */
.logout-container {
	position: fixed;
	bottom: 120rpx; /* 增加底部距离避开导航栏 */
	left: 0;
	width: 100%;
	padding: 0 20rpx;
	box-sizing: border-box;
}

.logout-btn {
	background-color: #e64340;
	color: white;
	border-radius: 35rpx;
	height: 70rpx; /* 减小按钮高度 */
	line-height: 70rpx;
	font-size: 26rpx; /* 减小按钮字体 */
	transition: all 0.3s ease;
	width: 100%;
}

.logout-btn:hover {
	background-color: #d43835;
	transform: scale(1.02);
}

.logout-btn:active {
	transform: scale(0.98);
}

/* 未登录状态样式 */
.empty {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	height: 100vh;
	text-align: center;
	background-color: #ffffff;
	overflow: hidden; /* 防止未登录状态下滚动 */

	image {
		width: 35%;
		margin-bottom: 30rpx;
	}

	.text-gray {
		font-size: 28rpx;
		color: #999;
		margin-bottom: 40rpx;
	}

	.cu-btn {
		width: 65%;
		border-radius: 70rpx;
		height: 80rpx;
		line-height: 80rpx;
		font-size: 28rpx;
		background-color: #000000;
		color: white;
		transition: all 0.3s ease;
	}

	.cu-btn:hover {
		background-color: #333333;
		transform: scale(1.03);
	}

	.cu-btn:active {
		transform: scale(0.97);
	}
}

.nologin-content {
	text-align: center;
	padding: 80rpx 0; /* 减小上下内边距 */
	height: 100vh;
	margin-top: 0;
	background-color: #FFFFFF;

	image {
		width: 240rpx; /* 减小图片尺寸 */
		height: 240rpx;
		margin-bottom: 30rpx; /* 减小图片与文本间距 */
	}

	.text-gray {
		font-size: 28rpx; /* 减小文本大小 */
		margin-bottom: 30rpx; /* 减小文本与按钮间距 */
	}

	button {
		width: 70%; /* 增加按钮宽度占比 */
		margin: 0 auto;
		font-size: 28rpx; /* 减小按钮字体 */
		height: 70rpx; /* 减小按钮高度 */
		line-height: 70rpx;
	}
}
</style>
