<template>
	<view class="promo-modal-page">
		<!-- 顶部导航栏 -->
		<view class="nav-bar" :style="{height: navBarTotalHeight + 'px', paddingTop: statusBarHeight + 'px'}">
			<view class="nav-bar-inner">
				<view class="back-icon" @tap="navigateBack">
					<uni-icons type="left" size="22" color="#222" />
				</view>
				<view class="nav-bar-title">推广链接</view>
				<view class="nav-bar-right">
					<uni-icons type="more-filled" size="22" color="#222" />
				</view>
			</view>
		</view>
		<!-- 用户信息 -->
		<view class="user-info-modal" :style="{ marginTop: navBarTotalHeight + 'px' }">
			<view class="avatar-frame">
				<image class="avatar-img" :src="userInfo.avatar" mode="aspectFill" />
			</view>
			<view class="nickname">{{userInfo.name}}</view>
		</view>
		<!-- 二维码区 -->
		<view class="qrcode-modal-section">
			<image class="qrcode-img" :src="qrcodeUrl" mode="widthFix" />
			<!-- <view class="invite-code">邀请码：{{inviteCode}}</view> -->
		</view>
		<!-- 底部按钮 -->
		<view class="bottom-btns-modal">
			<button class="btn gray" open-type="share">分享给好友</button>
			<button class="btn green" @tap="saveToAlbum">保存到本地</button>
		</view>
	</view>
</template>

<script>
	import pullRefreshMixin from '@/pages/mixins/pullRefreshMixin.js'
	import config from '@/api/config.js'

	export default {
		mixins: [pullRefreshMixin],
		data() {
			return {
				statusBarHeight: 0,
				navBarHeight: 44,
				navBarTotalHeight: 44,
				userInfo: {
					avatar: '/static/avatar.png',
					name: '战斗世界',
				},
				qrcodeUrl: '/static/qrcode.png',
				inviteCode: '888888',
			}
		},
		onLoad() {
			const sysInfo = uni.getSystemInfoSync()
			this.statusBarHeight = sysInfo.statusBarHeight
			this.navBarHeight = 44
			this.navBarTotalHeight = this.statusBarHeight + this.navBarHeight
			// 可能要等待获取到数据
			this.getQrcode()
		},
		// 微信小程序分享配置
		// #ifdef MP-WEIXIN
		onShareAppMessage() {
			return {
				title: `${this.userInfo.name}邀请您一起参与旧衣回收`,
				path: `/pages/component/home?shareId=${this.inviteCode}`,
				imageUrl: this.qrcodeUrl || '/static/share-default.png'
			}
		},
		onShareTimeline() {
			return {
				title: `${this.userInfo.name}邀请您一起参与旧衣回收，环保从我做起！`,
				query: `shareId=${this.inviteCode}`,
				imageUrl: this.qrcodeUrl || '/static/share-default.png'
			}
		},
		// #endif
		methods: {
			async onRefresh() {
				// 模拟刷新数据
				await new Promise(resolve => setTimeout(resolve, 1000))
				uni.stopPullRefresh()
			},
			navigateBack() {
				uni.navigateBack()
			},
            getQrcode(){
                // 获取全局二维码路径
                if (getApp().globalData.qr_path) {
                    console.log('获取到二维码路径', getApp().globalData.qr_path)
                    this.qrcodeUrl = getApp().globalData.qr_path
                } else {
                    console.log('全局二维码路径不存在')
                    uni.getImageInfo({
						src: `${config.baseUrl}/recycle-admin/applet/promotion/getInviteCode?token=${uni.getStorageSync('token')}`,
						success: res => {
							getApp().globalData.qr_path = res.path
							console.log(getApp().globalData.qr_path, 'qr_path')
							this.qrcodeUrl = getApp().globalData.qr_path
						},
						fail: err => {
							console.log('QR code load failed:', err)
						}
					})
                }
            },

			// 保存到手机相册
			saveToAlbum() {
				if (!this.qrcodeUrl) {
					uni.showToast({
						title: '二维码还未加载完成',
						icon: 'none'
					})
					return
				}
				
				// 先授权相册权限
				uni.getSetting({
					success: (res) => {
						if (!res.authSetting['scope.writePhotosAlbum']) {
							// 没有权限，申请权限
							uni.authorize({
								scope: 'scope.writePhotosAlbum',
								success: () => {
									this.doSaveImage()
								},
								fail: () => {
									// 权限被拒绝，引导用户手动开启
									uni.showModal({
										title: '提示',
										content: '需要您授权保存相册权限',
										showCancel: false,
										success: () => {
											uni.openSetting()
										}
									})
								}
							})
						} else {
							// 已有权限，直接保存
							this.doSaveImage()
						}
					}
				})
			},
			// 执行保存图片
			doSaveImage() {
				uni.saveImageToPhotosAlbum({
					filePath: this.qrcodeUrl,
					success: () => {
						uni.showToast({
							title: '保存成功',
							icon: 'success'
						})
					},
					fail: (err) => {
						console.log('保存失败', err)
						uni.showToast({
							title: '保存失败',
							icon: 'none'
						})
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.promo-modal-page {
		min-height: 100vh;
		background: linear-gradient(to bottom, #f6fff2 0%, #fff 100%);
		display: flex;
		flex-direction: column;
		align-items: center;
		position: relative;

		.nav-bar {
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			z-index: 1000;
			width: 100vw;
			background: linear-gradient(to right, #b2f08d 0%, #39e9d2 100%);
			box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.03);

			.nav-bar-inner {
				display: flex;
				align-items: center;
				height: 44px;
				width: 100vw;
				position: relative;
			}

			.back-icon,
			.nav-bar-right {
				width: 44px;
				height: 44px;
				display: flex;
				align-items: center;
				justify-content: center;
				position: absolute;
				top: 0;
			}

			.back-icon {
				left: 0;
			}

			.nav-bar-right {
				right: 0;
			}

			.nav-bar-title {
				flex: 1;
				text-align: center;
				font-size: 36rpx;
				font-weight: bold;
				color: #222;
				letter-spacing: 2rpx;
				line-height: 44px;
			}
		}

		.user-info-modal {
			display: flex;
			flex-direction: column;
			align-items: center;

			.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 {
			margin-top: 48rpx;
			width: 300rpx;
			display: flex;
			flex-direction: column;
			align-items: center;

			.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;

				&.gray {
					background: linear-gradient(90deg, #f7f7f7, #f2f2f2);
					color: #888;
				}

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