<template>
	<!-- 访客记录 -->
	<view class="container">
		<template v-if="!isEmployeeLogin">
			<!-- 未登录状态 -->
			<view class="no-login">
<!--				<image src="/static/images/no-login.png" mode="aspectFit" class="no-login-image"></image>-->
				<text class="no-login-text">请使用员工账号登录</text>
				<button class="login-btn" @click="goToLogin">授权登录</button>
			</view>
		</template>
		<template v-else>
			<!-- Visit list -->
			<scroll-view scroll-y class="visit-list" @scrolltolower="onReachBottom">
				<template v-if="visitList.length > 0">
					<view class="visit-item" v-for="(item, index) in visitList" :key="index" @click="goToDetail(item)">
						<view class="visit-date">
							<text class="date-num">{{item.date}}</text>
							<text class="date-month">{{item.year}}</text>
						</view>
						<view class="visit-content">
							<view class="visit-header">
								<view class="visitor-info">
									<text class="visitor-label">对接人 </text>
									<text class="visitor-name">{{item.employeeName}}</text>
								</view>
								<text class="visit-status" :class="getStatusClass(item.status)">{{item.status}}</text>
							</view>
							<view class="visit-desc">{{item.visitReason}}</view>
							<view class="visit-time">
								<u-icon name="clock" size="12" color="#999"></u-icon>
								<text>{{item.time}}</text>
							</view>
						</view>
					</view>
					<!-- Loading more -->
					<u-loadmore :status="loadMoreStatus" />
				</template>
				<template v-else>
					<!-- 暂无数据 -->
					<view class="flex-items-plus">
						<image src="../../static/images/empty.png" class="empty "></image>
					</view>
					<view class="font28 font-gray flex-items-plus">
						数据为空
					</view>
				</template>
			</scroll-view>
		</template>
	</view>
</template>

<script>
	import {
		mapGetters
	} from 'vuex';
	import {
		getVisitList, wxLogin
	} from '@/config/api.js';

	export default {
		data() {
			return {
				user: {},
				visitStatus: '0',
				visitList: [],
				loadMoreStatus: 'loadmore', // loadmore, loading, nomore
				params: {
					current: 1,
					size: 10000,
				},
				hasMore: true,
				isEmployeeLogin: false // 是否是员工登录
			};
		},
		computed: {
			...mapGetters(['isLogin'])
		},
		onLoad() {
			this.checkEmployeeLogin();
		},

		onShow() {
			console.log('onShow-----',this.isEmployeeLogin);
			// 每次显示页面时检查登录状态
			this.checkEmployeeLogin();
			if (this.isEmployeeLogin) {
				this.getList();
			}
			// 监听刷新列表事件
			uni.$on('refreshVisitList', () => {
				this.refresh();
			});
		},

		onUnload() {
			// 移除事件监听
			// uni.$off('refreshVisitList');
		},
		onPullDownRefresh() {
			this.refresh()
			uni.stopPullDownRefresh();
		},
		methods: {
			// 检查员工登录状态
			checkEmployeeLogin() {
				const user = uni.getStorageSync('user');
				console.log('检查员工登录状态，user:', user);
				
				if (user && Object.keys(user).length > 0) {
					// user 缓存有值，已登录
					this.isEmployeeLogin = true;
					this.user = user;
				} else {
					// user 缓存没有值，未登录
					this.isEmployeeLogin = false;
					this.user = {};
				}
			},

			// Refresh list
			refresh() {
				this.visitList = []
				this.params.current = 1
				this.hasMore = true
				this.loadMoreStatus = 'loadmore'
				this.getList()
			},

			// Handle reaching bottom of scroll
			onReachBottom() {
				if (!this.hasMore || this.loadMoreStatus === 'loading') return

				this.params.current++
				this.getList(true)
			},

			// Get status class for styling
			getStatusClass(status) {
				const statusMap = {
					'待访问': 'status-pending-visit',
					'待审核': 'status-pending-review',
					'已拒绝': 'status-rejected'
				}
				return statusMap[status] || 'status-default'
			},

			// 获取访客列表
			async getList(loadMore = false) {
				if (!loadMore) {
					uni.showLoading({
						title: '加载中...'
					});
				}

				this.loadMoreStatus = 'loading'

				try {


					// 调用接口获取数据
					const user = uni.getStorageSync('user');

					let  data={}

					// if  (user.userId=='1') {
					//
					// }else{
					// data.userId = user.userId
					// }
					// if  (this.visitStatus) {
					//
					// }

					const response = await getVisitList(

							{
						userId: user.userId, // 从缓存获取用户ID
						// visitStatus: this.visitStatus  // 传递状态参数
					}
					);

					console.log('访客列表接口返回:', response);

					if (response && response.code === 200) {
						// 处理返回的数据
						const statusMap = {
							'0': '待访问',
							'1': '已访问',
							'2': '待审核',
							'3': '已拒绝'
						};

						const list = response.rows.map(item => {
							// 解析创建时间
							const createTime = item.createTime || item.visitDate;

							return {
								id: item.id,
								employeeName: item.empName, // 对接人（员工姓名）
								visitReason: item.visitReson || item.visitReason, // 兼容字段拼写问题
								status: statusMap[item.visitStatus] || '未知', // 状态
								visitDate: item.visitDate, // 访问时间
								visitorName: item.visitPerson, // 访客姓名
								visDept: item.visDept, // 部门
								visitorPhone: item.visitorTel, // 访客电话
								visitorNum: item.visitorNum, // 访客人数
								accPerson: item.accPerson, // 随行人员（JSON字符串）
								createTime: createTime,
								// visitorCompany: item.visDept, // 访客单位
								// 格式化显示用的字段
								date: this.$u.timeFormat(createTime, 'dd'),
								year: this.$u.timeFormat(createTime, 'yyyy/mm'),
								time: this.$u.timeFormat(createTime, 'hh:MM')
							};
						});

						if (loadMore) {
							this.visitList = [...this.visitList, ...list];
						} else {
							this.visitList = list;
						}

						// 根据返回的数据判断是否还有更多数据
						// 这里简单处理，如果返回的数据少于每页数量，说明没有更多了
						this.hasMore = response.rows.length >= this.params.size;
						this.loadMoreStatus = this.hasMore ? 'loadmore' : 'nomore';
					} else {
						uni.showToast({
							title: response.msg || '获取数据失败',
							icon: 'none'
						});
						this.loadMoreStatus = 'nomore';
					}
				} catch (error) {
					console.error('获取访客列表失败:', error);
					uni.showToast({
						title: '获取数据失败',
						icon: 'none'
					});
					this.loadMoreStatus = 'nomore';
				} finally {
					if (!loadMore) {
						uni.hideLoading();
					}
				}
			},

			// 跳转到详情页面
			goToDetail(item) {
				// 将完整对象数据存储到缓存，用于详情页读取
				uni.setStorageSync('visitDetailData', item);
				uni.navigateTo({
					url: `/pagesA/task/detail?id=${item.id}`
				});
			},

			// 跳转到登录页面
			async goToLogin() {
				try {
					// 1. 尝试微信授权登录
					const loginRes = await new Promise((resolve, reject) => {
						uni.login({
							provider: 'weixin',
							success: (res) => {
								if (res.code) {
									resolve(res); // 成功获取 code
								} else {
									reject(new Error('未获取到微信授权码'));
								}
							},
							fail: (err) => {
								reject(new Error('微信授权失败'));
							}
						});
					});

					// 2. 调用微信登录接口
					const wxRes = await wxLogin({ code: loginRes.code });
					console.log('微信登录成功:', wxRes);
					if (wxRes.openid) {
						uni.setStorageSync('openid', wxRes.openid);
					}
					// 3. 登录成功后的逻辑（如存储用户信息、跳转首页等）
					if (wxRes && wxRes.message === "登录成功"&& wxRes.user) {
						uni.setStorageSync('user', wxRes.data);
						if (wxRes.user) {
							uni.setStorageSync('user', wxRes.user);
						}
						// 更新store状态
						this.$store.commit('isLogin', true);
						this.isEmployeeLogin = true
						this.getList(true)
						// uni.switchTab({
						// 	url: '/pages/tabbar/home' // 替换为实际首页路径
						// });
					} else {
						throw new Error('微信登录接口返回异常');
					}

				} catch (error) {
					console.error('登录失败:', error);

					// 4. 微信授权或登录失败，跳转到手机号登录页
					uni.navigateTo({
						url: '/pagesA/public/phone-login'
					});
				}
			}


		}
	};
</script>

<style lang="scss" scoped>
	.container {
		min-height: 100vh;
		background-color: #f5f5f5;

		.no-login {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			padding-top: 30vh;

			.no-login-image {
				width: 240rpx;
				height: 240rpx;
				margin-bottom: 40rpx;
			}

			.no-login-text {
				font-size: 32rpx;
				color: #999;
				margin-bottom: 60rpx;
			}

			.login-btn {
				width: 320rpx;
				height: 88rpx;
				background: #FF6B00;
				border-radius: 44rpx;
				color: #fff;
				font-size: 32rpx;
				font-weight: 500;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}
	}

	.visit-list {
		height: 100vh;
	}

	.visit-item {
		background-color: #fff;
		margin: 16rpx 20rpx;
		border-radius: 16rpx;
		padding: 24rpx;
		display: flex;
		align-items: flex-start;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	}

	.visit-date {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-right: 24rpx;
		min-width: 80rpx;

		.date-num {
			font-size: 48rpx;
			font-weight: bold;
			color: #333;
			line-height: 1;
		}

		.date-month {
			font-size: 24rpx;
			color: #999;
			margin-top: 4rpx;
		}
	}

	.visit-content {
		flex: 1;

		.visit-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 12rpx;

			.visitor-info {
				display: flex;
				align-items: center;

				.visitor-label {
					margin-right: 10rpx;
					font-size: 32rpx;
					color: #333;
					font-weight: normal;
				}

				.visitor-name {
					font-size: 36rpx;
					color: #333;
					font-weight: bold;
				}
			}

			.visit-status {
				font-size: 28rpx;
				padding: 4rpx 12rpx;
				border-radius: 12rpx;

				&.status-pending-visit {
					color: #4CAF50;
					background-color: rgba(76, 175, 80, 0.1);
				}

				&.status-pending-review {
					color: #2196F3;
					background-color: rgba(33, 150, 243, 0.1);
				}

				&.status-rejected {
					color: #F44336;
					background-color: rgba(244, 67, 54, 0.1);
				}
			}
		}

		.visit-desc {
			color: #666;
			font-size: 28rpx;
			line-height: 1.4;
			margin-bottom: 12rpx;
		}

		.visit-time {
			display: flex;
			align-items: center;
			gap: 8rpx;

			text {
				color: #999;
				font-size: 24rpx;
			}
		}
	}
</style>