<template>
	<!-- 访客记录 -->
	<view class="container">
		<template v-if="!isLogin">
			<!-- 未登录状态 -->
			<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
	} from '@/config/api.js';

	export default {
		data() {
			return {
				user: {},
				visitStatus: '0',
				visitList: [],
				loadMoreStatus: 'loadmore', // loadmore, loading, nomore
				params: {
					current: 1,
					size: 10,
				},
				hasMore: true
			};
		},
		computed: {
			...mapGetters(['isLogin'])
		},
		onLoad() {
			this.user = uni.getStorageSync("user")
			console.log(uni.getStorageSync("user"), "usususuus")
			this.getList();

		},

		onShow() {

			// 监听刷新列表事件
			uni.$on('refreshVisitList', () => {
				this.refresh();
			});
		},

		onUnload() {
			// 移除事件监听
			// uni.$off('refreshVisitList');
		},
		onPullDownRefresh() {
			this.refresh()
			uni.stopPullDownRefresh();
		},
		methods: {
			// 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 response = await getVisitList({
						userId: 100,
						// visitStatus: this.visitStatus || '0' // 可以根据需要传递状态参数，空字符串表示获取所有状态
					});

					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, // 访问事由
								status: statusMap[item.visitStatus] || '未知', // 状态
								visitDate: item.visitDate, // 访问时间
								visitorName: item.visitPerson, // 访客姓名
								visitorCompany: item.visDept, // 访客单位
								visitorPhone: item.visitorTel, // 访客电话
								visitorNum: item.visitorNum, // 访客人数
								accPerson: item.accPerson, // 随行人员（JSON字符串）
								createTime: createTime,
								// 格式化显示用的字段
								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}`
				});
			},

			// 跳转到登录页面
			goToLogin() {
				uni.navigateTo({
					url: '/pagesA/public/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>