<template>
	<view class="promo-modal-page">
		<!-- 顶部导航栏 -->
		<!-- <view class="nav-bar">
			<view class="back" @tap="navigateBack">
				<uni-icons type="left" size="20" />
			</view>
			<text class="title">推广链接</text>
		</view> -->
		<navbar title="推广链接" leftClick 
		@leftClick="$utils.navigateBack" />

		<!-- 页面内容 -->
		<view class="content">
			<!-- 用户信息 -->
			<!-- <view class="user-info-modal">
				<view class="avatar-frame">
					<image class="avatar-img" :src="userInfo.headImage || '/static/avatar.png'" mode="aspectFill" />
				</view>
				<view class="nickname">{{ userInfo.nickName || '用户' }}</view>
			</view> -->
			<!-- 二维码区 -->
			<view class="qrcode-modal-section">
				<!-- 加载骨架屏 -->
				<view v-if="isLoading" class="qrcode-skeleton">
					<view class="skeleton-img"></view>
					<view class="skeleton-text"></view>
				</view>
				<!-- 二维码图片 -->
				<image 
					v-else-if="qrcodeUrl"
					class="qrcode-img" 
					:src="qrcodeUrl" 
					mode="widthFix"
					:show-menu-by-longpress="true"
					@error="onImageError"
					@load="onImageLoad"
				/>
				<view class="invite-code">邀请码：{{inviteCode}}</view>
				<view class="invite-code">长按二维码可保存到相册</view>
			</view>
			<!-- 底部按钮 -->
			<view class="bottom-btns-modal">
				<button class="btn gray" open-type="share">分享给好友</button>
				<!-- <button class="btn green" @tap="saveToAlbum">保存到本地</button> -->
			</view>
		</view>
	</view>
</template>

<script>
import pullRefreshMixin from '@/pages/mixins/pullRefreshMixin.js'
import config from '@/config.js'
import navbar from '@/compoent/base/navbar.vue'
import authorize from '@/utils/authorize.js'
export default {
	components : {
		navbar
	},
	mixins: [pullRefreshMixin],
	data() {
		return {
			userInfo: {},
			qrcodeUrl: '', // 二维码图片URL
			inviteCode: '888888',
			isLoading: true, // 加载状态，控制骨架屏显示
			retryCount: 0, // 重试次数
			maxRetries: 2, // 最大重试次数
		}
	},
	onLoad() {
		// 获取用户信息和二维码
		this.fetchUserInfo()
		this.getQrcode()
	},
	onUnload() {
		// 页面销毁时的清理逻辑
	},
	// 微信小程序分享配置
	// #ifdef MP-WEIXIN
	onShareAppMessage() {
		return {
			title: `${this.userInfo.nickName || '用户'}邀请您一起参与旧衣回收`,
			path: `/pages/component/home?shareId=${this.inviteCode}`,
			imageUrl: this.qrcodeUrl
		}
	},
	onShareTimeline() {
		return {
			title: `${this.userInfo.nickName || '用户'}邀请您一起参与旧衣回收，环保从我做起！`,
			query: `shareId=${this.inviteCode}`,
			imageUrl: this.qrcodeUrl
		}
	},
	// #endif
	methods: {
		async onRefresh() {
			// 重新获取用户信息和二维码
			this.retryCount = 0 // 重置重试计数
			this.isLoading = true // 重置加载状态，显示骨架屏
			this.fetchUserInfo()
			this.getQrcode()
			uni.stopPullRefresh()
		},
		navigateBack() {
			uni.navigateBack()
		},
		// 获取用户信息
		fetchUserInfo() {
			if (uni.getStorageSync('token')) {
				this.$api("getUserByToken", {}, (res) => {
					if (res.code == 200) {
						this.userInfo = res.result
						// 更新邀请码
						if (res.result.intentioCode) {
							this.inviteCode = res.result.intentioCode
						}
					}
				})
			}
		},

		getQrcode() {
			console.log('调用后端API生成二维码')
			uni.showLoading({
				title: '生成二维码中...'
			})
			this.generateQrcode()
		},

		// 生成二维码
		generateQrcode() {
			// 重置重试计数（仅在第一次调用时）
			if (this.retryCount === 0) {
				this.retryCount = 0
			}
			
			// 设置加载状态
			this.isLoading = true
			
			const token = uni.getStorageSync('token')
			const qrcodeUrl = `${config.baseUrl}/recycle-admin/applet/promotion/getInviteCode?token=${token}`
			// console.log('二维码URL:', qrcodeUrl)
			
			// 直接使用网络图片
			this.qrcodeUrl = qrcodeUrl
			if(this.qrcodeUrl){
				this.isLoading = false
			}
			uni.hideLoading()
		},

		// 保存到手机相册
		async saveToAlbum() {
			if (!this.qrcodeUrl) {
				uni.showToast({
					title: '二维码还未加载完成',
					icon: 'none'
				})
				return
			}

			try {
				// 请求相册权限
				await authorize('scope.writePhotosAlbum')
				
				// 获取图片信息并保存
				await this.imgApi(this.qrcodeUrl)
				
			} catch (error) {
				console.log('保存失败:', error)
				uni.showToast({
					title: '保存失败',
					icon: 'none'
				})
			}
		},
		// 获取图片信息并保存到相册
		imgApi(image) {
			uni.showLoading({
				title: '保存中...'
			})
			return new Promise((resolve, reject) => {
				
				// 先下载图片到本地临时路径
				  wx.downloadFile({
				    url: image,
				    success: (res) => {
				      if (res.statusCode === 200) {
				        const tempFilePath = res.tempFilePath;
				        // 保存到相册
				        wx.saveImageToPhotosAlbum({
				          filePath: tempFilePath,
				          success: () => {
							uni.hideLoading()
				            wx.showToast({ title: '保存成功', icon: 'success' });
				          },
				          fail: (err) => {
							uni.hideLoading()
				            console.error('保存失败:', err);
				            wx.showToast({ title: '保存失败', icon: 'none' });
				          }
				        });
				      }
				    },
				    fail: (err) => {
						uni.hideLoading()
				      console.error('下载失败:', err);
				      wx.showToast({ title: '图片下载失败', icon: 'none' });
				    }
				  });
				
				// // 获取图片的信息
				// uni.getImageInfo({
				// 	src: image,
				// 	success: (imageInfo) => {
				// 		// 保存图片到手机相册
				// 		uni.saveImageToPhotosAlbum({
				// 			filePath: imageInfo.path,
				// 			success: () => {
				// 				uni.showModal({
				// 					title: '保存成功',
				// 					content: '图片已成功保存到相册',
				// 					showCancel: false
				// 				})
				// 				resolve()
				// 			},
				// 			fail: (err) => {
				// 				console.log('保存失败', err)
				// 				reject(new Error('保存失败'))
				// 			},
				// 			complete: (res) => {
				// 				console.log('保存结果:', res)
				// 			}
				// 		})
				// 	},
				// 	fail: (err) => {
				// 		console.log('获取图片信息失败:', err)
				// 		reject(new Error('获取图片信息失败'))
				// 	}
				// })
			})
		},
		
		// 图片加载成功
		onImageLoad() {
			console.log('二维码图片加载成功')
			this.isLoading = false // 隐藏骨架屏
		},
		
		// 图片加载失败
		onImageError() {
			console.log('二维码图片加载失败，尝试重试')
			
			// 如果还有重试次数，则重试
			if (this.retryCount < this.maxRetries) {
				this.retryCount++
				console.log(`第${this.retryCount}次重试加载二维码`)
				
				// 延迟1秒后重试
				setTimeout(() => {
					this.generateQrcode()
				}, 1000)
				return
			}
			
			// 重试次数用完，显示错误提示并隐藏骨架屏
			console.log('重试次数用完，二维码加载失败')
			this.isLoading = false // 隐藏骨架屏
			uni.showToast({
				title: '二维码加载失败',
				icon: 'none'
			})
		}
	}
}
</script>

<style lang="scss" scoped>
.promo-modal-page {
	min-height: 100vh;
	background: #f8f8f8;
	// padding-bottom: calc(140rpx + env(safe-area-inset-bottom));
	overflow: hidden;
}

.nav-bar {
	display: flex;
	align-items: center;
	height: calc(150rpx + var(--status-bar-height));
	padding: 0 32rpx;
	padding-top: var(--status-bar-height);
	background: #fff;
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	z-index: 999;
	box-sizing: border-box;

	.back {
		padding: 20rpx;
		margin-left: -20rpx;
	}

	.title {
		flex: 1;
		text-align: center;
		font-size: 34rpx;
		font-weight: 500;
		color: #222;
	}
}

.content {
	// padding: 30rpx 0 0 0;
	padding: 20rpx;
	// margin-top: calc(150rpx + var(--status-bar-height) + 80rpx);
	height: 100%;
	display: flex;
	flex-direction: column;
	align-items: center;
	overflow: hidden;
	box-sizing: border-box;

	.user-info-modal {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-bottom: 48rpx;

		.avatar-frame {
			width: 104rpx;
			height: 104rpx;
			border-radius: 10rpx;
			overflow: hidden;
			background: #f2f2f2;
			box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.10);

			.avatar-img {
				width: 104rpx;
				height: 104rpx;
				object-fit: cover;
				display: block;
			}
		}

		.nickname {
			margin-top: 24rpx;
			font-size: 32rpx;
			font-weight: bold;
			color: #222;
			text-align: center;
		}
	}

	.qrcode-modal-section {
		width: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-bottom: 48rpx;

		.qrcode-skeleton {
			width: 100%;
			display: flex;
			flex-direction: column;
			align-items: center;
			
			.skeleton-img {
				width: 300rpx;
				height: 300rpx;
				border-radius: 20rpx;
				background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
				background-size: 200% 100%;
				animation: skeleton-loading 1.5s infinite;
				margin-bottom: 20rpx;
			}
			
			.skeleton-text {
				width: 200rpx;
				height: 32rpx;
				border-radius: 16rpx;
				background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
				background-size: 200% 100%;
				animation: skeleton-loading 1.5s infinite;
			}
			
			@keyframes skeleton-loading {
				0% {
					background-position: 200% 0;
				}
				100% {
					background-position: -200% 0;
				}
			}
		}

		.qrcode-img {
			width: 100%;
			height: 100%;
			background: #fff;
			border-radius: 24rpx;
			box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
		}

		.invite-code {
			margin-top: 32rpx;
			font-size: 30rpx;
			color: #222;
			font-weight: bold;
			text-align: center;
		}
	}

	.bottom-btns-modal {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		display: flex;
		justify-content: space-between;
		padding: 24rpx 32rpx calc(env(safe-area-inset-bottom) + 24rpx) 32rpx;
		background: #fff;
		z-index: 100;

		.btn {
			flex: 1;
			height: 88rpx;
			border-radius: 44rpx;
			font-size: 32rpx;
			font-weight: bold;
			margin: 0 12rpx;
			border: none;
			display: flex;
			align-items: center;
			justify-content: center;

			&.gray {
				background: linear-gradient(90deg, #b2f08d, #39e9d2);
				color: #fff;
			}

			&.green {
				background: linear-gradient(90deg, #b2f08d, #39e9d2);
				color: #fff;
			}
		}
	}
}
</style>