<template>
	<view class="padding-top container">
		<!-- #ifdef APP -->
		<text class="iconfont icon-youjiantou zuojiantou" @click="goBack()" style="top: 20rpx;"></text>
		<!-- #endif -->

		<!-- #ifdef H5 -->
		<view class="generateImageBox" v-if="!generatedImage">
			<view class="imgBox" ref="captureElement">
				<img v-if="posterImg" class="posterImg" @load="handleBgImageLoad" @error="handleBgImageError"
					style="display: block;" src="@/static/images/sharePoster.png" crossorigin="anonymous" alt="防缓存图片" />
				<view class="qrcode-container">
					<canvas canvas-id="qrcode" class="qrcode-canvas"
						:style="{width: qrCodeSize + 'px', height: qrCodeSize + 'px'}"></canvas>
				</view>
			</view>
		</view>
		<!-- #endif -->
		<view class="tabTitle">
			<text :class="{'actived': tabType===1}" @click="switchTab(1)">基本信息</text>
			<text :class="{'actived': tabType===2}" @click="switchTab(2)">邀请信息</text>
		</view>
		<!-- tab内容 -->
		<view class="tabContent">
			<!-- 基本信息 -->
			<view v-if="tabType===1">
				<view class="ulBox">
					<view class="liBox">
						<text>昵称 <text style="font-size: 22rpx;">(被邀请人可修改)</text> ：</text>
						<text>
							<input v-model="dataForm.name" class="uni-input" maxlength="10" placeholder="昵称"
								style="width: 300rpx;" />
						</text>
					</view>
					<view class="liBox">
						<text>手机号：</text>
						<text><input v-model="dataForm.mobileNumber" class="uni-input" type="number" maxlength="11"
								placeholder="手机号" /></text>
					</view>
				</view>
				<!-- <share></share> -->
				<button type="primary" plain="true" class="sendInvite" @click="shareToggle()">
					<loadingIcon :loading="isLoading" v-if="isLoading" />
					<text style="margin-left: 5rpx;">发出邀请</text>
				</button>
			</view>
			<!-- 邀请信息 -->
			<view class="inviteListsBox" v-if="tabType===2">
				<h4 class="noListTip" v-if="!inviteLists || inviteLists.length<=0">暂无邀请记录！</h4>
				<view class="listUl ulBox" v-for="(item,index) in inviteLists" :key="index">
					<view class="liBox">
						<text>昵称：</text>
						<text>{{item.name}}</text>
					</view>
					<view class="liBox">
						<text>手机号：</text>
						<text>{{item.mobileNumber}}</text>
					</view>
					<view class="liBox">
						<text>邀请状态：</text>
						<text v-if="item.approvalStatus=='0'">邀请中</text>
						<text v-else-if="item.approvalStatus=='1'">审核中</text>
						<text v-else-if="item.approvalStatus=='3'" class="success">邀请成功</text>
						<text v-else class="fail">邀请失败</text>
					</view>
					<view class="liBox-footer" v-if="item.approvalStatus == 0 || item.approvalStatus== '2'"
						@click="reinvite(item.id)">
						<text>重新邀请</text>
					</view>
				</view>
			</view>
		</view>
		<!-- 分享信息 -->
		<view>
			<uni-popup ref="share" type="bottom" backgroundColor="#fff">
				<view class="popup-content">
					<view class="shareBox">
						<view class="shareOptionItem" @click="uniShare(1)">
							<view class="imgBox">
								<image src="../../static/app-plus/sharemenu/wechatfriend.png" mode="widthFix"></image>
							</view>
							<text>微信好友</text>
						</view>
						<view class="shareOptionItem" @click="uniShare(2)">
							<view class="imgBox">
								<image src="../../static/app-plus/sharemenu/wechatmoments.png" mode="widthFix"></image>
							</view>
							<text>分享朋友圈</text>
						</view>
					</view>
				</view>
				<view class="popup-footer" @click="closeShare()">
					<view>取消</view>
				</view>
			</uni-popup>
		</view>
		<view class="markBox" @click="shareTipsFlag=false" v-if="shareTipsFlag">
			<view class="guideImgBox">
				<image src="../../static/Group132.png" mode="widthFix"></image>
				<view class="tips">
					<view style="margin-bottom:30rpx">请点击右上角菜单</view>
					<view>分享给朋友</view>
				</view>
			</view>
		</view>
		<!-- 海报弹窗 -->
		<sharePosterPop ref="sharePosterPop" :generatedImage="generatedImage" @closePoster="closePoster"
			btnBottom="-15%"></sharePosterPop>
	</view>
</template>

<script>
	import dataHandling from "@/util/dataHandling";
	import api from "@/api/api"
	import common from '../../common/common';
	import { hshare, setWechatShare, initJssdkShare } from '@/util/fiveshare';
	import { baseURL, apiURL, cffpURL, companyInfo, shareURL } from "@/environments/environment";
	import sharePosterPop from '@/components/commonPopup/sharePosterPop.vue';
	import UQRCode from 'uqrcodejs';
	import { elementToImage } from '@/util/htmlToImage';
	import loadingIcon from '@/components/loading/loading.vue';
	export default {
		components: {
			sharePosterPop,
			loadingIcon
		},
		data() {
			return {
				companyType: companyInfo.companyType,
				ydLogoShare: `${shareURL}/static/suplogo.png`,
				dataForm: {
					applyType: '1', //申请类型邀请加盟传 1 申请加盟传 2
					operatStep: '1', // 99:最后一步,1:第一步,2:为第二步该obj 为第一步
					name: '', //姓名
					mobileNumber: '', //被邀请人手机号
					b1Name: '', // 工作室
					partnerLevel: '', //被邀请人身份
					hasCrossDistrict: '', //是否跨区邀请
					areaId: '', //所属组织Id
					areaName: '' //所属组织名称
				},
				userId: uni.getStorageSync('cffp_userId'),
				tabType: 1,
				identityArr: ['工作室', '事业伙伴'],
				applyIdentity: 0,
				index: 0,
				isCross: false,
				inviteLists: [],
				orgList: [],
				orgdataList: [],
				queryList: [],
				queryorgList: [],
				shareId: '',
				realName: '',
				partnerLevel: '',
				invitationCode: '',
				shareTipsFlag: false,
				qrCodeUrl: '/myPackageA/applyFranchise/applyFranchise',
				qrCodeSize: 80, //二维码的尺寸
				generatedImage: '', //生成的海报图片
				companyLogo: '../../static/suplogo.png',
				posterImg: '',
				isLoading: false
			};

		},

		onLoad(option) {
			//this.partnerLevel = option.levelCode
			this.partnerLevel = 'P1'
			//this.getqueryOrgList()
			if (this.companyType == '1') {
				this.ydLogoShare = `${shareURL}/static/cffp_logo.jpg`;
			} else {
				this.ydLogoShare = `${shareURL}/static/suplogo.png`;
			}
			if (companyInfo.companyType == '1') {
				this.companyLogo = '../../static/myteam/Group1633.png';
			} else if (this.companyType == '2') {
				this.companyLogo = '../../static/suplogo.png';
			}
			let dataForm = JSON.parse(uni.getStorageSync('cffp_userInfo'))
			this.realName = dataForm.realName || dataForm.nickName;
			this.invitationCode = dataForm.invitationCode
			if (!this.realName) {
				this.queryInfo();
			}
		},
		onShow() {
			this.isLoading = false
			this.posterImg = ''
			this.generatedImage = ''
			// #ifdef H5
			initJssdkShare(() => {
				setWechatShare();
			}, window.location.href);
			// #endif
		},
		onHide() {
			this.$nextTick(() => {
				this.$refs.sharePosterPop.closeDropdown()
			})
		},
		methods: {
			goBack() {
				uni.navigateBack({
					delta: 1
				})
			},
			queryInfo() {
				api.queryInfo({ userId: uni.getStorageSync('cffp_userId') }).then(res => {
					if (res['success']) {
						delete res.data.commonResult
						const cffp_userInfo = {
							...res.data
						}
						uni.setStorageSync('cffp_userInfo', JSON.stringify(cffp_userInfo))
						this.realName = res.data.realName || res.data.nickName;
						this.invitationCode = res.data.invitationCode;
					}
				})
			},
			queryorgchange(e) {
				this.orgindex = e.detail.value
			},
			bindPChange(e) {
				this.index = e.detail.value
			},
			// 查询组织list
			getqueryOrgList() {
				let CffpAreaQueryReqVO = {
					userId: this.userId,
					partnerLevel: ''
				}
				api.queryOrgList(CffpAreaQueryReqVO).then(res => {
					if (res['success']) {
						this.queryorgList = res.data.cffpAreaQuerys
						this.orgList = res.data.cffpAreaQuerys
						this.changeorgkey()
					}
				})
			},
			switchTab(type) {
				this.tabType = type;
				if (this.tabType === 2) {
					this.queryInviteList()
				}
			},
			bindPickerChange: function(e) {
				this.applyIdentity = e.detail.value
				this.changeorgkey()
			},
			changeorgkey() {
				let that = this
				let orgKey = that.applyIdentity == 0 ? 'B1' : 'A1'
				that.queryList = that.orgList.map((item) => {
					if (item.partnerLevel == orgKey || item.partnerLevel == 'ALL') {
						return item
					}
				}).filter(item2 => item2 != undefined)
				that.orgdataList = that.queryList.map((x) => x.areaName)
			},
			// 发起邀请事件
			shareToggle() {

				//this.dataForm.partnerLevel = this.applyIdentity == 0 ? 'B1' : 'A1'
				this.dataForm.partnerLevel = 'P1'
				this.dataForm.hasCrossDistrict = this.isCross == true ? '1' : '0'
				this.dataForm.userId = this.userId
				this.dataForm.inviteUserId = this.userId
				// this.dataForm.areaId = this.isCross == true ? null : this.queryList[this.index].areaId
				// this.dataForm.areaName = this.isCross == false ? this.queryList[this.index].areaName : this.dataForm.areaName
				this.dataForm.areaId = 1;
				this.dataForm.areaName = '默认';
				if (this.dataForm.name == "" || this.dataForm.mobileNumber == "" || this.dataForm.areaName == '') {
					uni.showToast({
						title: '请将信息补充完整',
						duration: 2000,
						icon: 'none'
					});
					return false
				}
				// if(!common.nameValid(this.dataForm.name)){
				// 	uni.showToast({title: '请填写真实姓名',duration: 2000,icon: 'none'})
				// 	this.dataForm.name = ''
				// 	return
				// }
				this.dataForm.remarkName = this.dataForm.name
				if (common.mobileNoValid(this.dataForm.mobileNumber)) {
					api.saveApplyInfo(this.dataForm).then(res => {
						if (res['success']) {
							this.shareId = res.data.id;

							// #ifdef APP-PLUS
							this.$refs.share.open()
							// #endif
							// if (typeof wx !== 'undefined' && wx.miniProgram) {
							// 	console.log('wx',wx.miniProgram);
							// 	wx.miniProgram.postMessage({
							// 		data: {
							// 			type: 'requestShare',
							// 			title: '银盾家办家庭财务策划师联盟邀您加入',
							// 			desc: `${this.realName}邀您加入【家庭财策师联盟】，资源+伙伴，共赢未来！`,
							// 			path: shareURL +
							// 				"/myPackageA/applyFranchise/applyFranchise?shareId=" + this
							// 				.shareId + '&invitationCode=' + this.invitationCode +
							// 				'&inviteUserId=' + this.userId, //分享链接
							// 		}
							// 	});
							// 	return
							// }
							//#ifdef H5
							// 小程序跳cffp得分享
							if (uni.getStorageSync('mpCffp')) {
								this.qrCodeUrl = shareURL +
									"/myPackageA/applyFranchise/applyFranchise?shareId=" +
									this.shareId + '&invitationCode=' + this.invitationCode + '&inviteUserId=' +
									this.userId, //分享链接
									this.posterImg = '@/static/images/sharePoster.png'
								this.isLoading = true
								return
							}
							this.shareTipsFlag = true;
							this.getshareData()
							// #endif
						} else {
							uni.showToast({
								title: res['message'],
								duration: 2000,
								icon: 'none'
							});
						}
					})
				} else {
					common.errorDialog(2, '手机号校验错误')
				}

			},
			getshareData() {
				if (!this.realName) {
					this.realName = ""
				}
				let data = {
					title: '银盾家办家庭财务策划师联盟邀您加入',
					//desc: `我是家庭财务策划师${this.realName}正在使用银盾家办，点击即刻加入！`,
					desc: `${this.realName}邀您加入【家庭财策师联盟】，资源+伙伴，共赢未来！`,
					link: shareURL +
						"/myPackageA/applyFranchise/applyFranchise?shareId=" +
						this.shareId + '&invitationCode=' + this.invitationCode + '&inviteUserId=' + this
						.userId, //分享链接
					imgUrl: this.ydLogoShare, //图片
					//imgUrl: `${baseURL}/static/cffp_logo.jpg`, //图片
				}
				//安卓机型获取当前页面路径
				let url = window.location.href.split('#')[0];

				//ios机型获取当前页面路径
				let ua = navigator.userAgent.toLowerCase();
				let isWeixin = ua.indexOf('micromessenger') !== -1;
				if (isWeixin) {
					let isiOS = /(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent); //ios终端
					if (isiOS && window.sessionStorage.getItem('firstEntryUrl')) {
						url = window.sessionStorage.getItem('firstEntryUrl').split('#')[0];
					}
				}
				hshare(data, url)
				dataHandling.pocessTracking(
					'邀请',
					`发出邀请`,
					'点击',
					2,
					'邀请加盟',
					'pages/inviteJoin/inviteJoin'
				)
				// setTimeout(()=>{
				// 	// #ifdef H5
				// 		initJssdkShare(() => {
				// 		  setWechatShare();
				// 		}, window.location.href);
				// 	// #endif
				// },500)

			},
			closeShare() {
				this.$refs.share.close()
			},
			reinvite(id) {
				//debugger;
				this.shareId = id
				// #ifdef APP-PLUS
				this.$refs.share.open()
				// #endif
				//#ifdef H5
				if (uni.getStorageSync('mpCffp')) {
					this.qrCodeUrl = shareURL +
						"/myPackageA/applyFranchise/applyFranchise?shareId=" +
						this.shareId + '&invitationCode=' + this.invitationCode + '&inviteUserId=' +
						this.userId, //分享链接
						this.posterImg = '@/static/images/sharePoster.png'
					this.isLoading = true
					return
				}
				this.shareTipsFlag = true;
				this.getshareData()
				// #endif
			},
			uniShare(type) {
				if (!this.realName) {
					this.realName = ""
				}
				let typeName = type == 1 ? '微信好友' : '朋友圈'
				dataHandling.pocessTracking(
					'邀请',
					`向${typeName}发出邀请`,
					'点击',
					2,
					'邀请加盟',
					'pages/inviteJoin/inviteJoin'
				)
				uni.share({
					provider: "weixin",
					scene: type === 1 ? "WXSceneSession" : "WXSceneTimeline",
					type: 0,
					href: `${shareURL}/myPackageA/applyFranchise/applyFranchise?shareId=${this.shareId}&invitationCode=${this.invitationCode}&inviteUserId=${this.userId}`,
					// href: `${shareURL}/pages/invitationRegister/invitationRegister?shareId=${this.shareId}&invitationCode=${this.invitationCode}&inviteUserId=${this.userId}`,
					title: "银盾家办家庭财务策划师联盟邀您加入",
					//summary: `我是家庭财务策划师${this.realName}正在使用银盾家办，点击下载即刻加入！`,
					summary: `${this.realName}邀您加入【家庭财策师联盟】，资源+伙伴，共赢未来！`,
					imageUrl: this.ydLogoShare, //图片
					//imageUrl: `${baseURL}/static/cffp_logo.jpg`,
					success: function(res) {
						console.log("success:" + JSON.stringify(res));
					},
					fail: function(err) {
						console.log("fail:" + JSON.stringify(err));
					}
				});
			},
			queryInviteList() {
				api.queryInviteList({
					userId: this.userId
				}).then(res => {
					if (res['success']) {
						this.inviteLists = res['data']['data']
					}
				})
			},


			// 分享海报代码
			// 背景图片加载成功
			handleBgImageLoad() {
				console.log('产品图片加载成功');
				this.generateQrcodeAndCapture();
			},

			// 背景图片加载失败
			handleBgImageError() {
				console.log('产品图片加载失败');
				// 即使失败也继续流程，可能会有默认背景
				// this.generateQrcodeAndCapture();
			},

			// 顺序执行：生成二维码 -> 截图
			async generateQrcodeAndCapture() {
				try {
					uni.showLoading({
						title: '准备生成分享图...'
					});

					// 1. 先生成二维码
					console.log('开始生成二维码...');
					await this.makeQrcode();
					console.log('二维码生成完成');

					// 2. 等待500ms确保渲染完成
					await new Promise(resolve => setTimeout(resolve, 1500));

					// 3. 执行截图
					console.log('开始截图...');
					await this.captureImage();
					console.log('截图完成');

					uni.hideLoading();
				} catch (error) {
					console.error('生成分享图失败:', error);
					uni.hideLoading();
					// this.retryGenerate();
				}
			},

			// 重试机制
			// retryGenerate() {
			//   if (this.retryCount < this.maxRetryCount) {
			//     this.retryCount++;
			//     const delay = 1000 * this.retryCount;
			//     console.log(`第${this.retryCount}次重试，${delay}ms后重试...`);



			//     setTimeout(() => {
			//       this.generateQrcodeAndCapture();
			//     }, delay);
			//   } else {
			//     // uni.showToast({
			//     //   title: '生成分享图失败，请稍后再试',
			//     //   icon: 'none'
			//     // });
			//   }
			// },

			// 生成二维码
			makeQrcode() {
				return new Promise((resolve, reject) => {
					// 创建实例
					const qr = new UQRCode();

					// 设置二维码内容
					qr.data = this.qrCodeUrl;

					// 设置二维码大小
					qr.size = this.qrCodeSize;

					// 设置前景色（二维码颜色）
					qr.foregroundColor = '#000000';

					// 设置背景色
					qr.backgroundColor = '#FFFFFF';

					// 设置边距
					qr.margin = 10;

					// 设置纠错等级
					qr.errorCorrectLevel = UQRCode.errorCorrectLevel.H;

					try {
						// 调用制作二维码方法
						qr.make();

						// 获取canvas上下文
						const ctx = uni.createCanvasContext('qrcode', this);

						// 清空画布
						ctx.clearRect(0, 0, this.qrCodeSize, this.qrCodeSize);

						// 将二维码绘制到canvas上
						qr.canvasContext = ctx;
						qr.drawCanvas();

						// 绘制完成
						ctx.draw(true, () => {
							console.log('二维码绘制完成');
							resolve();
						});
					} catch (err) {
						reject(err);
					}
				});
			},

			// 截图方法
			async captureImage() {
				try {
					uni.showLoading({
						title: '正在生成图片...'
					});

					// 获取DOM元素（在H5环境下）
					const element = this.$refs.captureElement.$el;
					// 调用工具函数生成图片
					const imageData = await elementToImage(element);
					this.generatedImage = imageData
					this.isLoading = false
					this.$refs.sharePosterPop.toggleDropdown()

					// 压缩图片
					// const compressedImage = await this.compressImage(imageData);

					// this.generatedImage = compressedImage;
				} catch (error) {
					console.error('截图失败:', error);
					throw error; // 抛出错误以便外部捕获
				} finally {
					uni.hideLoading();
				}
			},
			// 关闭海报弹窗
			closePoster() {
				this.posterImg = ''
				this.generatedImage = ''
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		position: relative;
		height: 100vh;

		.generateImageBox {
			position: absolute;
			top: -100%;
			z-index: -1;
			border-radius: 20rpx;
			width: 100%;
			box-sizing: border-box;
			background-color: #fff;
			height: 900rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			flex-direction: column;

			.imgBox {
				position: relative;
				width: 500rpx;
				height: 900rpx;
				box-sizing: border-box;

				.posterImg {
					width: 100%;
					height: 100%;
					object-fit: cover;
				}

				.qrcode-container {
					position: absolute;
					bottom: 1%;
					right: 1%;
					background: #fff;
					padding: 10rpx;
					border-radius: 10rpx;
					box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.1);

					.qrcode-canvas {
						display: block;
					}
				}

			}


		}

		.tabTitle {
			color: #666666;
			background-color: #fff;
			display: flex;
			align-items: center;
			justify-content: space-around;
			padding: 30rpx;
			box-sizing: border-box;

			text {
				font-size: 26rpx;

				&.actived {
					color: #333;
					border-bottom: 4rpx solid #20269B;
					font-size: 24rpx;
				}
			}
		}

		.tabContent {
			margin-top: 10rpx;

			.ulBox {
				width: 95%;
				margin: 0 auto 20rpx;
				padding: 10rpx 20rpx;
				color: #333;
				border-radius: 10rpx;
				background-color: #fff;
				box-sizing: border-box;
				position: relative;

				.describeLabel {
					padding: 20rpx 0;
					font-size: 28rpx;
					color: #777;
				}

				.liBox {
					border-bottom: 1px solid #F0F0F0;
					height: 76rpx;
					display: flex;
					justify-content: space-between;
					align-items: center;
					font-size: 26rpx;

					&:last-child {
						border: none;
					}

					.uni-input {
						text-align: right;
						font-size: 26rpx;
						width: 400rpx;
					}

					text {
						&.success {
							color: #78C06E;
						}

						&.fail {
							color: #FF0000;
						}
					}

					.isCrossBox {
						display: flex;
						align-items: center;

						view {
							display: flex;
							align-items: center;

							&:first-child {
								margin-right: 20rpx;
							}

							.circle {
								display: block;
								width: 28rpx;
								height: 28rpx;
								border: 2rpx solid #20269B;
								border-radius: 50%;
								position: relative;
								margin: 4rpx 10rpx 0 10rpx;
							}

							&.checked {
								.circle {
									&::before {
										position: absolute;
										content: '';
										width: 20rpx;
										height: 20rpx;
										border-radius: 50%;
										left: 50%;
										top: 50%;
										background-color: #20269B;
										transform: translate(-50%, -50%);
									}
								}
							}

						}


					}

				}

				// &.listUl::before {
				// 	display: block;
				// 	content: '';
				// 	position: absolute;
				// 	left: 10rpx;
				// 	top: 20rpx;
				// 	width: 8rpx;
				// 	height: 20rpx;
				// 	background-color: #FA882F;
				// 	border-radius: 8rpx;
				// }
			}

			.sendInvite {
				position: absolute;
				left: 0;
				top: 80%;
				width: 60%;
				transform: translateX(30%);
				border-radius: 80rpx;
				background-color: #20269B;
				color: #fff;
				font-size: 36rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}

		.popup-content {
			font-size: 32rpx;
			color: #666;
			padding-bottom: 40rpx;

			.shareBox {
				display: flex;
				justify-content: space-around;
				align-items: center;

				.shareOptionItem {
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;

					.imgBox {
						width: 100rpx;
					}
				}

			}
		}

		.liBox-footer {
			width: 200rpx;
			height: 50rpx;
			color: #FFFFFF;
			margin-top: 10rpx;
			text-align: center;
			line-height: 50rpx;
			border-radius: 30rpx;
			background: #20269B;
			font-size: 25rpx;
		}

		.popup-footer {
			color: #666;
			font-size: 36rpx;
			border-top: 2rpx solid #f0f0f0;
			display: flex;
			justify-content: center;
			align-items: center;
			padding-top: 36rpx;
		}

		.markBox {
			position: fixed;
			left: 0;
			top: 0;
			bottom: 0;
			right: 0;
			width: 100%;
			height: 100%;
			color: #fff;
			display: flex;
			justify-content: flex-end;
			z-index: 100000;
			background: rgba(0, 0, 0, 0.8);

			.guideImgBox {
				margin: 20px auto;

				uni-image {
					width: 25% !important;
					position: absolute;
					right: 0;
					top: 0;
				}
			}

			.tips {
				margin-top: 30%;
				padding: 0 30px;
			}
		}
	}
</style>