<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="taskList.length > 0">
					<view class="visit-item" v-for="(item, index) in taskList" :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>

			<!-- Floating button -->
			<view class="floating-button" @click="showApplyPopup">
				<text class="floating-text">申请<br>访问</text>
			</view>
		</template>

		<!-- Application method popup -->
		<uni-popup ref="popup" type="center" border-radius="16rpx">
			<view class="popup-content">
				<view class="popup-title">
					选择申请方式
					<text class="close-icon" @click="closePopup">×</text>
				</view>
				<view class="apply-methods">
					<view class="method-item" @click="handleApply('self')">
						<view class="method-icon green-bg">
							<image src="/static/images/apply.png" mode="aspectFit"></image>
						</view>
						<text class="font-bold">发起申请</text>
					</view>
					<view class="method-item" @click="handleApply('proxy')">
						<view class="method-icon orange-bg">
							<image src="/static/images/behalf.png" mode="aspectFit"></image>
						</view>
						<text class="font-bold">代客申请</text>
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		orderList,
		userLogin
	} from '@/config/api.js';
	import {
		mapGetters
	} from 'vuex';
	import {
		shareImg
	} from '@/common/config.js'
	export default {
		data() {
			return {
				taskList: [],
				loadMoreStatus: 'loadmore', // loadmore, loading, nomore
				params: {
					current: 1,
					size: 10,
				},
				hasMore: true
			}
		},
		computed: {
			...mapGetters(['isLogin'])
		},
		onLoad(options) {
			this.getList();
		},
		// 微信小程序分享配置
		onShareAppMessage() {
			return {
				title: `邀请您加入知己访客`,
				path: `/pages/index/index`,
				imageUrl: shareImg // 分享图片，需要添加
			}
		},
		onShareTimeline(res) {
			let that = this;
			let shareInfo = store.state.vuex_shareInfo;
			let query = shareInfo.query;
			//携带当前页面资源ID参数
			let currentPage = getCurrentPages()[getCurrentPages().length - 1];
			let options = currentPage.options;
			if (JSON.stringify(options) != '{}' && options.id) {
				query += `&id=${options.id}`;
			}

			return {
				title: shareInfo.title,
				query: query,
				imageUrl: shareImg,
				success(res) {
					uni.showToast({
						title: '分享成功'
					})
				},
				fail(res) {
					uni.showToast({
						title: '分享失败',
						icon: 'none'
					})
				},
			}
		},
		onShow() {
			// #ifdef H5
			this.login()
			// #endif

		},


		onPullDownRefresh() {
			this.refresh()
			uni.stopPullDownRefresh();
		},


		methods: {

			// Refresh list
			refresh() {
				this.taskList = []
				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)
			},

			// Show apply popup
			showApplyPopup() {
				console.log('显示申请弹窗');
				this.$refs.popup.open()
			},

			// Close popup
			closePopup() {
				this.$refs.popup.close()
			},

			// Handle apply method selection
			handleApply(type) {
				if (!this.isLogin) {
					uni.navigateTo({
						url: '/pagesA/public/login'
					});
					return
				}
				console.log('选择申请方式:', type);
				this.$refs.popup.close()
				if (type === 'self') {
					uni.navigateTo({
						url: '/pagesA/task/edit?type=1'
					})
				} else {
					uni.navigateTo({
						url: '/pagesA/task/edit?type=2'
					})
				}
			},

			// Login method
			login() {
				let params = {
					username: "USER082927",
					grant_type: "web",
					memberId: "1957060037088083973"
				}
				userLogin(params).then((loginData) => {
					uni.setStorageSync('access_token', loginData.access_token);
					uni.setStorageSync('refresh_token', loginData.refresh_token);
					uni.setStorageSync('user', loginData);

					this.$store.commit('isLogin', true);
					this.$store.commit('refresh_token', loginData.refresh_token);
				})
			},

			// Get visit list with mock data
			getList(loadMore = false) {
				if (!loadMore) {
					uni.showLoading({
						title: '加载中...'
					});
				}

				this.loadMoreStatus = 'loading'

				// 模拟接口延迟
				setTimeout(() => {
					// 模拟数据
					const mockData = Array(10).fill(0).map((_, index) => {
						const currentIndex = (this.params.current - 1) * 10 + index;
						const date = new Date();
						date.setDate(date.getDate() - currentIndex); // 每条数据日期递减

						const statusList = ['待访问', '待审核', '已拒绝'];
						const descList = [
							'我是访问事由我是访问事由我是访问事由...',
							'需要进行业务对接商谈...',
							'产品展示与技术交流...',
							'项目合作洽谈...'
						];

						return {
							id: currentIndex,
							employeeName: `范海洋${currentIndex + 1}`,
							createTime: date,
							status: statusList[Math.floor(Math.random() * statusList.length)],
							visitReason: descList[Math.floor(Math.random() * descList.length)]
						};
					});

					const list = mockData.map(item => ({
						...item,
						date: this.$u.timeFormat(item.createTime, 'DD'),
						year: this.$u.timeFormat(item.createTime, 'YYYY/MM'),
						time: this.$u.timeFormat(item.createTime, 'hh:mm')
					}));

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

					// 模拟总共有5页数据
					this.hasMore = this.params.current < 5;
					this.loadMoreStatus = this.hasMore ? 'loadmore' : 'nomore';

					if (!loadMore) {
						uni.hideLoading();
					}
				}, 500); // 增加500ms延迟模拟网络请求
			},

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

			// 跳转到详情页面
			goToDetail(item) {
				uni.navigateTo({
					url: `/pagesA/task/detail?id=${item.id}&status=${item.status}`
				});
			},

			// 跳转到登录页面
			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;
			}
		}
	}

	.floating-button {
		position: fixed;
		bottom: 120rpx;
		right: 40rpx;
		width: 120rpx;
		height: 120rpx;
		background-color: #FF6B00;
		border-radius: 16rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 8rpx 20rpx rgba(255, 107, 0, 0.3);
		z-index: 999;

		.floating-text {
			color: #fff;
			font-size: 28rpx;
			text-align: center;
			line-height: 1.2;
		}
	}

	.popup-content {
		width: 600rpx;
		padding: 70rpx 40rpx;
		background-color: #fff;
		border-radius: 16rpx;

		.popup-title {
			font-size: 36rpx;
			color: #333;
			text-align: center;
			position: relative;
			margin-bottom: 60rpx;
			font-weight: 500;

			.close-icon {
				position: absolute;
				right: 0;
				top: 50%;
				transform: translateY(-50%);
				font-size: 50rpx;
				color: #999;
				width: 60rpx;
				height: 60rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}

		.apply-methods {
			display: flex;
			justify-content: space-around;
			padding: 0 20rpx;

			.method-item {
				display: flex;
				flex-direction: column;
				align-items: center;
				gap: 30rpx;
				cursor: pointer;

				.method-icon {
					width: 120rpx;
					height: 120rpx;
					border-radius: 20rpx;
					display: flex;
					align-items: center;
					justify-content: center;

					image {
						width: 80rpx;
						height: 80rpx;
					}

					&.green-bg {
						background-color: #39833b;
					}

					&.orange-bg {
						background-color: #FF6B00;
					}
				}

				text {
					font-size: 32rpx;
					color: #333;
					font-weight: 500;
				}
			}
		}
	}
</style>