<template>
	<view>
		<mescroll-body ref="mescrollRef" @init="mescrollInit" @down="downCallback" @up="upCallback" :down="downOption"
			:up="upOption">
			<view class="live-list">
				<view v-for="(item,index) in dataList" :key="index" class="item">
					<view class="bottom-box">
						<view class="left">
							<image class="img" v-if="item.liveImgUrl" :src="item.liveImgUrl"></image>
							<text class="ml30 label">{{item.liveName}}</text>
						</view>
						<view class="btn-box">
							<view class="btn pay" @click.stop="showDetail(item)">
								分享直播间
							</view>

							<u-popup :show="show" @close="close">
								<view class="pop">
									<!-- 确保这里正确绑定方法 -->
									<view class="item" @click="generateAndCopyLink(currentItem)">
										<image class="w72 h72 mr20" src="/static/share_link.png"></image>
										<text>复制链接</text>
									</view>
									<view class="item">
										<button open-type="share" class="button"
											:data-item="JSON.stringify(currentItem)" @click="setShareItem(currentItem)">
											<image class="w72 h72 mr20" :src="imgPath+'/userapp/images/weixin1.png'">
											</image>
											<text>分享直播间</text>
										</button>
									</view>
									<view class="cancel" @click="close">取消</view>
								</view>
							</u-popup>
						</view>
					</view>
				</view>
			</view>
		</mescroll-body>
	</view>
</template>

<script>
	import {
		getGotoWxAppLiveLink,
		liveShareList
	} from '@/api/living.js'
	import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";
	export default {
		mixins: [MescrollMixin],
		data() {
			return {
				show: false,
				userinfo: {},
				currentShareItem: null,
				currentItem: null, // 添加当前项存储
				// searchKey: "",
				mescroll: null,
				// 上拉加载的配置
				upOption: {
					onScroll: true,
					use: true, // 是否启用上拉加载; 默认true
					page: {
						num: 0, // 当前页码,默认0,回调之前会加1,即callback(page)会从1开始
						size: 10 // 每页数据的数量,默认10
					},
					noMoreSize: 10, // 配置列表的总数量要大于等于5条才显示'-- END --'的提示
					empty: {
						icon: '/static/images/no_data.png',
						tip: '暂无数据'
					}
				},
				item: null,
				companyId: null,
				companyUserId: null,
				// 列表数据
				dataList: [],
			};
		},
		onLoad(options) {
			console.log("分享直播间options", options)
			var that = this;
			// uni.$on('refreshOrder', () => {
			that.mescroll.resetUpScroll()
			// })
			this.companyId = options.companyId;
			this.companyUserId = options.companyUserId;
			this.userinfo = uni.getStorageSync("userInfo")
		},
		computed: {
			appid() {
				return this.$store.state.appid
			},
			imgPath() {
				return this.$store.state.imgpath
			}
		},
		onShareAppMessage() {
			const item = this.currentShareItem || {};
			console.log("item.liveId", item.liveId)
			console.log("this.companyUserId", this.companyUserId)
			return {
				title: '邀请你来观看直播：' + item.liveName,
				path: `/pages_course/living?companyId=${this.companyId}&companyUserId=${this.companyUserId}&liveId=${item.liveId}`,
				// imageUrl: this.products.image,
				imageUrl: '/static/logo.png',
				success(res) {
					console.log("分享成功", res);
				},
				fail(err) {
					console.error("分享失败", err);
				}
			};
		},
		methods: {
			async generateAndCopyLink(item) {
			    console.log("复制链接被点击>>>", item);
			
			    if (!item) {
			        uni.showToast({
			            title: '请先选择直播项目',
			            icon: 'none'
			        });
			        return;
			    }
			
			    try {
			        // 等待获取短链接
			        const shareLink = await this.getGotoWxAppLiveLink(item);
			        console.log("获取到的分享链接:", shareLink);
			        
			        if (!shareLink) {
			            uni.showToast({
			                title: '暂无链接',
			                icon: 'none'
			            });
			            return;
			        }
			        
			        // 复制到剪贴板
			        await this.copyToClipboard(shareLink);
					this.close()
			        
			    } catch (error) {
			        console.error('获取短链接失败:', error);
			        uni.showToast({
			            title: '暂无链接',
			            icon: 'none'
			        });
			    }
			},

			getGotoWxAppLiveLink(item) {
			    return new Promise((resolve, reject) => {
			        if (!this.companyId) {
			            reject(new Error('companyId 不存在'));
			            return;
			        }
			
			        if (!item || !item.liveId) {
			            reject(new Error('直播项目信息不完整'));
			            return;
			        }
			        
			        const data = {
			            appid: this.appid,
			            linkStr: `/pages_course/living?companyId=${this.companyId}&companyUserId=${this.companyUserId}&liveId=${item.liveId}`
			        }
			        
			        console.log("请求短链接参数:", data);
			        
			        getGotoWxAppLiveLink(data).then(res => {
			            console.log("短链接口返回:", res);
			            if (res.code == 200) {
			                // 正确使用 resolve 返回数据
			                resolve(res.data || res.result || res.url || res);
			            } else {
			                uni.showToast({
			                    icon: 'none',
			                    title: "获取链接失败",
			                });
			                reject(new Error('请求失败: ' + (res.message || res.msg || '未知错误')));
			            }
			        }).catch(err => {
			            console.error("获取链接异常:", err);
			            reject(err);
			        });
			    });
			},

			// 复制到剪贴板
			copyToClipboard(text) {
			    return new Promise((resolve, reject) => {
			        
			        if (!text) {
			            uni.showToast({
			                title: '暂无链接',
			                icon: 'none'
			            });
			            reject(new Error('链接为空'));
			            return;
			        }
			        
			        uni.setClipboardData({
			            data: text,
			            success: () => {
			                uni.showToast({
			                    title: '链接已复制',
			                    icon: 'success'
			                });
			                resolve();
							
			            },
			            fail: (err) => {
			                uni.showToast({
			                    title: '复制失败',
			                    icon: 'none'
			                });
			                reject(err);
			            }
			        });
			    });
			},

			close() {
				this.show = false
				this.currentItem = null; // 关闭时清空当前项
			},

			// 记录当前要分享的item
			setShareItem(item) {
				console.log("setShareItem接收到的参数:", item);

				// 如果item是字符串，需要解析；如果是对象，直接使用
				if (typeof item === 'string') {
					try {
						this.currentShareItem = JSON.parse(item);
					} catch (error) {
						console.error("JSON解析失败:", error);
						this.currentShareItem = null;
					}
				} else if (typeof item === 'object' && item !== null) {
					// 如果已经是对象，直接赋值
					this.currentShareItem = item;
				} else {
					console.error("setShareItem接收到无效的参数:", item);
					this.currentShareItem = null;
				}

				console.log("设置后的currentShareItem:", this.currentShareItem);
			},

			// goSearch(e) {
			// 	this.searchKey = e.detail.value;
			// 	this.mescroll.resetUpScroll()
			// },
			mescrollInit(mescroll) {
				this.mescroll = mescroll;
			},
			/*下拉刷新的回调 */
			downCallback(mescroll) {
				mescroll.resetUpScroll()
			},
			upCallback(page) {
				//联网加载数据
				var that = this;
				if (!this.companyId) return;
				var data = {
					pageNum: page.num,
					pageSize: page.size,
				};
				liveShareList( data).then(res => {
					if (res.code == 200) {
						//设置列表数据
						if (page.num == 1) {
							that.dataList = res.rows;

						} else {
							that.dataList = that.dataList.concat(res.rows);

						}
						that.mescroll.endBySize(res.rows.length, res.total);

					} else {
						uni.showToast({
							icon: 'none',
							title: "请求失败",
						});
						that.dataList = null;
						that.mescroll.endErr();
					}
				});
			},
			showDetail(item) {
				console.log(item)
				this.currentItem = item; // 存储当前点击的item
				this.show = !this.show
			},
		}
	}
</script>

<style lang="scss">
	.search-cont {
		padding: 16rpx 30rpx;
		background-color: #FFFFFF;

		.inner {
			box-sizing: border-box;
			width: 100%;
			height: 72rpx;
			background: #F7F7F7;
			border-radius: 36rpx;
			display: flex;
			align-items: center;
			padding: 0 30rpx;

			.icon-search {
				width: 28rpx;
				height: 28rpx;
				margin-right: 20rpx;
			}

			input {
				height: 60rpx;
				line-height: 60rpx;
				flex: 1;
			}
		}
	}

	.live-list {
		padding: 20rpx;

		.item {
			background: #FFFFFF;
			border-radius: 16rpx;
			padding: 20rpx 30rpx;
			margin-bottom: 20rpx;

			.bottom-box {
				display: flex;
				align-items: center;
				justify-content: space-between;

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

					.img {
						width: 140rpx;
						height: 140rpx;
					}

					.label {
						max-width: 300rpx;
						font-size: 28rpx;
						font-weight: 500;
						color: #999999;
						line-height: 1;
					}



					.price-box {
						display: flex;
						align-items: flex-end;

						.unit {
							font-size: 24rpx;
							font-family: PingFang SC;
							font-weight: 500;
							color: #FF6633;
							line-height: 1.2;
							margin-right: 4rpx;
						}

						.num {
							font-size: 32rpx;
							font-family: PingFang SC;
							font-weight: bold;
							color: #FF6633;
							line-height: 1;
						}
					}
				}

				.btn-box {
					box-sizing: border-box;
					display: flex;
					align-items: center;

					.btn {
						font-size: 28rpx;
						color: #F7F7F7;
						padding: 12rpx 20rpx;
						background-color: #2BC7B9;
						font-weight: 500;
						border-radius: 15rpx;
					}

					button {
						background-color: transparent !important;
						width: 100% !important;
						display: flex;
						justify-content: flex-start;
						padding: 0;
						font-size: 30rpx;
					}

					button:after {
						border: none !important;
						border-radius: 10px;
						box-sizing: border-box;
					}




					.pop {
						display: flex;
						flex-direction: column;
						background-color: #f1f1f1;
						padding: 40rpx 30rpx;

						.item {
							display: flex;
							align-items: center;
							padding: 20rpx;
							font-size: 30rpx;
						}

						.cancel {
							width: 100%;
							height: 100rpx;
							line-height: 100rpx;
							text-align: center;
							background-color: #FFFFFF;
							border-radius: 50rpx;
							font-weight: 500;
							font-size: 34rpx;

						}
					}
				}
			}

		}
	}
</style>