<template>
	<view class="container">
		<image class="bg" src="https://ysrw-1395926010.cos.ap-chengdu.myqcloud.com/image/bg_invite.png" mode="aspectFill"></image>
		<!-- 状态栏占位（微信小程序原生适配） -->
		<view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
		<view class="return">
			<image class="return-img" @click="goBack" src="https://ysrw-1395926010.cos.ap-chengdu.myqcloud.com/image/back_white.png" mode="aspectFill"></image>

		</view>
		<!-- 核心内容区：居中布局 -->
		<view class="main-content">
			<!-- 页面大标题：讲者邀请 -->
			<view class="page-title">
				<image class="title-img" src="https://ysrw-1395926010.cos.ap-chengdu.myqcloud.com/image/img_title.png" mode="aspectFill"></image>
				<text class="title-txt">讲者邀请</text>
				<image class="title-img rotate180" src="https://ysrw-1395926010.cos.ap-chengdu.myqcloud.com/image/img_title.png" mode="aspectFill"></image>
			</view>
			<!-- 邀请卡片：白色背景+圆角+轻微阴影（1:1匹配UI） -->
			<view class="invite-card">

				<!-- 邀请人信息区 -->
				<view class="inviter-section">
					<image class="inviter-avatar" src="https://ysrw-1395926010.cos.ap-chengdu.myqcloud.com/image/my_heads_icon.png" mode="aspectFill"></image>
					<text class="inviter-name">王小明</text>
					<text class="invite-desc">邀请你成为讲者</text>
				</view>

				<!-- 二维码区域：白色边框+圆角 -->
				<view class="qrcode-box">
					<image class="qrcode-img" :src="qscode" @longpress="saveQrcode"></image>
				</view>
				<!-- 扫码提示文字 -->
				<view class="scan-tip">扫一扫，注册一咻学术</view>
			</view>
		</view>
	</view>
</template>

<script>
import { inviteDoctor } from '@/api/speaker.js'

	export default {
		data() {
			return {
				// 仅获取微信小程序状态栏高度，无多余逻辑
				statusBarHeight: uni.getSystemInfoSync().statusBarHeight,
				userInfo: {},
				qscode:''

			};
		},
		onLoad() {
				this.userInfo=uni.getStorageSync('userInfo')||{};
			console.log('userInfo:', this.userInfo);
			console.log('userInfo.userId:', this.userInfo.userId);
			console.log('userInfo.companyId:', this.userInfo.companyId);
			this.inviteDoctor();
		},
		methods: {
			goBack() {
				uni.navigateBack({
					delta: 1
				});
			},

			saveQrcode() {
				if (!this.qscode) {
					uni.showToast({
						icon: 'none',
						title: '二维码未加载'
					});
					return;
				}
				
				uni.showLoading({
					title: '保存中...'
				});
				
				// 如果是base64格式的图片，需要先转换为临时文件
				if (this.qscode.startsWith('data:image')) {
					const base64Data = this.qscode.replace(/^data:image\/\w+;base64,/, '');
					const filePath = `${wx.env.USER_DATA_PATH}/qrcode_${Date.now()}.png`;
					
					const fs = wx.getFileSystemManager();
					try {
						fs.writeFileSync(filePath, base64Data, 'base64');
						
						uni.saveImageToPhotosAlbum({
							filePath: filePath,
							success: () => {
								uni.hideLoading();
								uni.showToast({
									icon: 'success',
									title: '保存成功'
								});
							},
							fail: (err) => {
								uni.hideLoading();
								if (err.errMsg.includes('auth')) {
									uni.showModal({
										title: '提示',
										content: '需要您授权保存图片到相册',
										success: (modalRes) => {
											if (modalRes.confirm) {
												uni.openSetting({
													success: (settingRes) => {
														if (settingRes.authSetting['scope.writePhotosAlbum']) {
															this.saveQrcode();
														}
													}
												});
											}
										}
									});
								} else {
									uni.showToast({
										icon: 'none',
										title: '保存失败'
									});
								}
							}
						});
					} catch (e) {
						uni.hideLoading();
						uni.showToast({
							icon: 'none',
							title: '保存失败'
						});
					}
				} else {
					// 如果是网络图片URL
					uni.downloadFile({
						url: this.qscode,
						success: (res) => {
							if (res.statusCode === 200) {
								uni.saveImageToPhotosAlbum({
									filePath: res.tempFilePath,
									success: () => {
										uni.hideLoading();
										uni.showToast({
											icon: 'success',
											title: '保存成功'
										});
									},
									fail: (err) => {
										uni.hideLoading();
										if (err.errMsg.includes('auth')) {
											uni.showModal({
												title: '提示',
												content: '需要您授权保存图片到相册',
												success: (modalRes) => {
													if (modalRes.confirm) {
														uni.openSetting({
															success: (settingRes) => {
																if (settingRes.authSetting['scope.writePhotosAlbum']) {
																	this.saveQrcode();
																}
															}
														});
													}
												}
											});
										} else {
											uni.showToast({
												icon: 'none',
												title: '保存失败'
											});
										}
									}
								});
							}
						},
						fail: () => {
							uni.hideLoading();
							uni.showToast({
								icon: 'none',
								title: '下载失败'
							});
						}
					});
				}
			},

			inviteDoctor() {
				console.log('开始调用inviteDoctor');
				console.log('userId:', this.userInfo.userId);
				console.log('companyId:', this.userInfo.companyId);
				
				// 检查参数是否完整
				if (!this.userInfo.userId || !this.userInfo.companyId) {
					console.error('参数不完整:', { userId: this.userInfo.userId, companyId: this.userInfo.companyId });
					uni.showToast({
						icon: 'none',
						title: '用户信息不完整'
					});
					return;
				}
				
				uni.showLoading({
					title: '生成二维码中...'
				});
				
				console.log('调用API前的userId:', this.userInfo.userId);
				console.log('调用API前的companyId:', this.userInfo.companyId);
				
				inviteDoctor(this.userInfo.userId, this.userInfo.companyId).then(res => {
					uni.hideLoading();
					// console.log('inviteDoctor返回数据类型:', typeof res);
					console.log('inviteDoctor返回数据:', res);
					console.log('res是否为null/undefined:', res === null || res === undefined);
					
					// 处理各种可能的返回格式
					try {
						// 情况1：返回base64字符串
						if (typeof res === 'string') {
							console.log('处理直接返回的字符串，长度:', res.length);
							if (res.startsWith('data:image')) {
								console.log('处理直接返回的base64字符串');
								this.qscode = res;
							} else {
								// 尝试直接使用字符串作为图片URL
								console.log('处理返回的图片URL');
								this.qscode = res;
							}
						}
						// 情况2：标准API返回格式
						else if (res && typeof res === 'object') {
							console.log('处理对象类型返回值');
							console.log('res对象的keys:', Object.keys(res));
							
							// 子情况1：data为base64字符串
							if (typeof res.data === 'string') {
								console.log('处理API返回的base64字符串，长度:', res.data.length);
								if (res.data.startsWith('data:image')) {
									this.qscode = res.data;
								} else {
									// 尝试直接使用字符串作为图片URL
									this.qscode = res.data;
								}
							}
							// 子情况2：data为ArrayBuffer
							else if (res.data) {
								console.log('处理API返回的data，类型:', typeof res.data);
								try {
									const base64 = uni.arrayBufferToBase64(res.data);
									this.qscode = 'data:image/png;base64,' + base64;
									console.log('ArrayBuffer转换成功:', this.qscode.substring(0, 50) + '...');
								} catch (e) {
									console.error('ArrayBuffer转换失败:', e);
									uni.showToast({
										icon: 'none',
										title: '二维码转换失败'
									});
								}
							}
							// 子情况3：直接在响应对象中包含二维码信息
							else if (res.qrcode || res.qrCode) {
								console.log('处理API返回的qrcode字段');
								this.qscode = res.qrcode || res.qrCode;
							}
							// 子情况4：检查其他可能的字段
							else {
								console.log('检查其他可能的字段');
								// 尝试直接使用res作为图片URL
								this.qscode = JSON.stringify(res);
								console.log('尝试使用JSON字符串作为二维码:', this.qscode);
							}
						}
						// 情况3：直接返回ArrayBuffer
						else if (res) {
							console.log('处理直接返回的非对象非字符串数据');
							try {
								const base64 = uni.arrayBufferToBase64(res);
								this.qscode = 'data:image/png;base64,' + base64;
								console.log('ArrayBuffer转换成功:', this.qscode.substring(0, 50) + '...');
							} catch (e) {
								console.error('ArrayBuffer转换失败:', e);
								uni.showToast({
									icon: 'none',
									title: '二维码转换失败'
								});
							}
						}
						else {
							console.error('无法识别的返回格式:', res);
							uni.showToast({
								icon: 'none',
								title: '二维码格式错误'
							});
						}
						
						// 确保二维码值已设置
						if (this.qscode) {
							console.log('二维码设置成功:', this.qscode.substring(0, 100) + (this.qscode.length > 100 ? '...' : ''));
							// 强制组件更新，确保图片显示
							this.$forceUpdate();
							console.log('强制组件更新后');
							
							// 模拟延迟后再次更新，确保图片加载
							setTimeout(() => {
								console.log('延迟更新后qscode:', this.qscode);
								this.$forceUpdate();
							}, 100);
						}
					} catch (e) {
						console.error('二维码处理失败:', e);
						uni.showToast({
							icon: 'none',
							title: '二维码处理失败'
						});
					}
				}).catch(err => {
					uni.hideLoading();
					console.error('获取二维码失败:', err);
					uni.showToast({
						icon: 'none',
						title: '获取二维码失败'
					});
				});
			}
		}
	};
</script>

<style lang="scss" scoped>
	/* 小程序页面全局重置：消除默认样式 */
	page {
		margin: 0;
		padding: 0;
		background-color: #F8F7F5;
		font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
	}

	/* 根容器：全屏+垂直布局 */
	.container {
		min-height: 100vh;
		display: flex;
		flex-direction: column;
		background-color: #F8F7F5;
		position: relative;

		.bg {
			position: absolute;
			top: 0;
			width: 100%;
			height: 100%;
		}
	}

	/* 状态栏占位：透明背景，仅占高度 */
	.status-bar {
		width: 100%;
		background-color: transparent;
	}

	.return {
		position: relative;
		height: 88rpx;
		z-index: 2;
		line-height: 88rpx;
		.return-img {
			width: 40rpx;
			height: 40rpx;
			margin-left: 32rpx;
		}
	}

	/* 核心内容区：水平居中+顶部间距 */
	.main-content {
		width: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 52rpx 74rpx 0;
		box-sizing: border-box;
		position: relative;
		z-index: 2;

		/* 页面大标题：讲者邀请（匹配UI字体/大小/颜色） */
		.page-title {
			font-weight: 600;
			font-size: 48rpx;
			color: #FFFFFF;
			margin-bottom: 124rpx;
			display: flex;
			align-items: center;

			.title-img {
				width: 134rpx;
				height: 12rpx;
			}

			.title-txt {
				margin: 0 20rpx;

			}

			.rotate180 {
				transform: rotate(180deg);
			}

		}

		/* 邀请卡片：白色背景+圆角+轻微阴影（1:1匹配） */
		.invite-card {
			width: 100%;
			background-color: #FFFFFF;
			border-radius: 32rpx;
			box-shadow: 0rpx 16rpx 28rpx 0rpx rgba(45, 109, 199, 0.37);
			padding: 60rpx 40rpx 80rpx;
			position: relative;
			box-sizing: border-box;

			/* 邀请人信息区：头像+文字横向布局 */
			.inviter-section {
				position: absolute;
				top: -72rpx;
				left: 50%;
				transform: translateX(-50%);
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;

				.inviter-avatar {
					width: 144rpx;
					height: 144rpx;
					border-radius: 50%;
					margin-bottom: 18rpx;
				}

				/* 邀请人姓名 */
				.inviter-name {
					color: #000000;
					font-weight: 600;
					font-size: 36rpx;
					margin-bottom: 36rpx;
				}

				/* 邀请文案 */
				.invite-desc {
					font-size: 32rpx;
					color: #666666;
				}

			}

			.qrcode-box {
				width: 372rpx;
				height: 372rpx;
				background-color: #FFFFFF;
				display: flex;
				align-items: center;
				justify-content: center;
				margin: 200rpx auto 40rpx;

				.qrcode-img {
					width: 372rpx;
					height: 372rpx;

				}
			}

			/* 扫码提示文字：居中+浅灰色 */
			.scan-tip {
				text-align: center;
				font-size: 32rpx;
				color: #333333;
			}
		}
	}
</style>