<template>
	<view class="container" :class="{noscroll: buyShow}">
		<view class="pay-wall" v-show="loginShow">
			<view class="title">
				{{ report.title }}
			</view>
		</view>
		<u-parse :html="report.content"></u-parse>
		<view class="bottom-box">
			<view class="menu-box">
				<button class="menu-item" @click="changeApplaud">
					<i class="iconfont icon-dianzan" :class="report.hasApplaud?'active':''"></i>
				</button>
				<button class="menu-item" @click="changeFavi">
					<i class="iconfont icon-shoucang1" :class="report.hasFavi?'active':''"></i>
				</button>
				<button class="menu-item" open-type="share">
					<i class="iconfont icon-zhuanfa"></i>
				</button>
				<!-- <button class="menu-item">
					<i class="iconfont icon-pengyouquan"></i>
				</button> -->
				<!-- <button class="menu-item">
					<i class="iconfont icon-xiaoxi"></i>
				</button> -->
			</view>
		</view>
		<u-popup v-model="buyShow" :mask="false" :closeable='false' mode="bottom" :mask-close-able='false'
			safe-area-inset-bottom>
			<view style="height: 70vh;padding: 40rpx;position: relative;">
				<view style="text-align: center;color: #cccccc;margin: 50rpx 0;">正文需付费后才可阅读</view>
				<view style="text-align: center;">
					<u-button size="medium" type="error" @click="toBuy">￥{{ payForm.amount }} 阅读全部</u-button>
				</view>
				<view style="text-align: center;
					color: #ff0000;
					position: absolute;
					bottom: 20%;
					left: 50%;
					width: 80%;
					transform: translateX(-50%);" @click="toJoin">个人会员或单位会员免费，点击现在入会></view>
			</view>
		</u-popup>
		<u-popup v-model="loginShow" :mask="false" :closeable='false' mode="bottom" :mask-close-able='false'
			safe-area-inset-bottom>
			<view style="height: 70vh;padding: 40rpx;position: relative;">
				<!-- <view style="text-align: center;color: #cccccc;margin: 50rpx 0;">正文需付费后才可阅读</view> -->
				<view style="text-align: center;margin: 70rpx 0;">
					<u-button size="medium" type="error" @click="toLogin">登录阅读原文</u-button>
				</view>
			</view>
		</u-popup>
		<canvas style="position: absolute; top: -1000px; left: -1000px; width: 875px; height: 700px; background: #fff;"
			canvas-id="canvas"></canvas>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted
	} from 'vue'
	import {
		onLoad,
		onShareAppMessage,
		onShareTimeline
	} from '@dcloudio/uni-app'
	import {
		getToken
	} from '@/utils/auth.js'
	import {
		getReportDetail,
		reportFavi,
		cancelReportFavi,
		reportApplaud,
		cancelReportApplaud,
		payReport
	} from '@/api/report.js'
	import {
		msgError,
		msgSuccess
	} from "@/utils/common.js"
	import {
		useAuthStore
	} from '@/store/authStore'
	const authStore = useAuthStore();
	const isMember = computed(() => {
		authStore.loadUserInfo()
		return authStore.userInfo.isMember == '0' ? false : true
	})
	const openid = computed(() => {
		authStore.loadOpenid()
		// console.log(authStore.openid, 1111)
		return authStore.openid
	})
	const buyShow = ref(false)
	const loginShow = ref(true)
	const webview = ref();
	const id = ref()
	const title = ref()
	const hasPermission = ref(false);
	const imgurl = ref(null)
	const report = ref({
		id: '01',
		title: '2025年2月从化区二手住宅市场交易简报',
		summary: "2025年2月从化区二手住宅市场交易简报",
		price: '9.9',
		memberFree: 1,
		free: 0,
		status: 0,
		markdown: ``
	})

	const compileMarkDown = computed(() => {
		if (!report.value.markdown) {
			return;
		}
		let htmlString = "";
		// 判断markdown中代码块标识符的数量是否为偶数
		if (report.value.markdown.split("```").length % 2) {
			let content = report.value.markdown;
			if (content[content.length - 1] != "\n") {
				content += "\n";
			}
			htmlString = content;
		} else {
			htmlString = report.value.markdown;
		}
		return htmlString;
	})

	// 是否登录
	const isLogin = computed(() => {
		// return false
		return getToken() ? true : false
	})

	// 是否购买/免费
	const free = computed(() => {
		return false
	})

	const showMask = computed(() => {
		// 是否登录

		// 是否已购买或者免费
		if (report.value.status || report.value.free) {
			return false
		}
		// 判断用户是否为会员免费
		if (report.value.memberFree) {
			// 
		}

		return false
	})
	const payForm = ref({
		"id": null,
		"title": "",
		"desc": "",
		"amount": null,
		"openid": ""
	})

	function parseLoaded() {
		setTimeout(() => {
			this.$refs.uReadMore1.init();
		}, 10);
	}

	function changeFavi() {
		console.log(report.value.hasFavi)
		if (report.value.hasFavi) {
			cancelReportFavi(id.value).then(res => {
				if (res?.code == 0) {
					report.value.hasFavi = false
				}
			})
		} else {
			reportFavi(id.value).then(res => {
				if (res?.code == 0) {
					report.value.hasFavi = true
				}
			})
		}
	}

	function changeApplaud() {
		console.log(report.value.hasApplaud)
		if (report.value.hasApplaud) {
			cancelReportApplaud(id.value).then(res => {
				if (res?.code == 0) {
					report.value.hasApplaud = false
				}
			})
		} else {
			reportApplaud(id.value).then(res => {
				if (res?.code == 0) {
					report.value.hasApplaud = true
				}
			})
		}
	}

	function toBuy() {
		// console.log("点击购买")
		// 修改一下，如果是会员，用会员价格，
		// 如果不是会员就用普通价格
		payForm.value.openid = openid.value
		payReport(payForm.value).then(res => {
			if (res && res.code === 0) {
				const params = res.data
				wx.requestPayment({
					nonceStr: params.nonceStr,
					package: params.package,
					paySign: params.paySign,
					signType: params.signType,
					timeStamp: params.timeStamp,
					success(res) {
						buyShow.value = false
						msgSuccess("支付成功")
					},
					fail(res) {
						buyShow.value = true
						msgError("支付失败")
					}
				})
			}
		})
	}

	function toLogin() {
		let url = {
			url: '/pages/reportDetail/reportDetail',
			id: id.value,
			title: title.value
		}
		// const decodedRedirect = decodeURIComponent(url);
		uni.setStorageSync("redirect", url)
		uni.navigateTo({
			url: `/pages/login/login`
		})
	}

	const toJoin = () => {
		uni.navigateTo({
			url: "/pages/swiperDetail/swiperDetail?id=12117"
		})
	}

	function init(id) {
		// 测试图片
		getReportDetail(id).then(res => {
			if (res.code === 0) {
				report.value = res.data
				payForm.value.id = res.data.id
				payForm.value.title = res.data.title
				payForm.value.desc = res.data.title
				payForm.value.amount = isMember.value ? report.value.priceMember : report.value.price
				report.value.content = ""
				if (!report.value.hasBuy && res.data.viewMode === '3') {
					buyShow.value = true
				} else if (!report.value.hasBuy && !isMember.value && res.data.viewMode === '2') {
					buyShow.value = true
				}
				// console.log(report.value.hasBuy, res.data.viewMode, buyShow.value, 100)
				if (res.data.imgData) {
					const path = res.data.imgData.path
					const type = res.data.imgData.type
					const size = res.data.imgData.size
					for (let i = 1; i <= size; i++) {
						let image = `${path}/${i}.${type}`
						report.value.content = report.value.content + `<img style='-webkit-touch-callout: none; -webkit-user-select: none; user-select: none; pointer-events: none;' src='${image}'></img>`
					}
				} else {
					report.value.content = ''
				}
				imgurl.value = report.value.cover
			}
		})
	}

	function cutShareImg(imgUrl) {
		return new Promise((resolve) => {
			wx.getImageInfo({
				src: imgUrl, // 原图路径
				success: (res) => {
					let ctx = wx.createCanvasContext("canvas")
					let canvasW = 0
					let canvasH = res.height
					// 把比例设置为 宽比高 5:4
					canvasW = (res.height * 5) / 4
					// 为画框设置背景色，注意要放在画图前，图会覆盖在背景色上
					ctx.fillStyle = "#fff"
					ctx.fillRect(0, 0, canvasW, canvasH)
					// ctx.drawImage(res.path, (res.width - canvasW) / 2, 0, canvasW, canvasH, 0, 0, canvasW, canvasH)
					ctx.drawImage(
						res.path,
						0,
						0,
						canvasW,
						canvasH,
						(canvasW - res.width) / 2, // 宽度从中间向两边填充
						0,
						canvasW,
						canvasH
					)
					ctx.draw(false, () => {
						wx.canvasToTempFilePath({
							width: canvasW,
							height: canvasH,
							destWidth: 750, // 标准的iphone6尺寸的两倍，生成高清图
							destHeight: 600,
							canvasId: "canvas",
							fileType: "jpg", // 注意jpg默认背景为透明
							success: (res) => {
								// 设置分享图片路径
								resolve(res.tempFilePath)
							},
						})
					})
				}
			})
		})
	}
	onLoad((load) => {
		if (load.id) {
			id.value = load.id
			title.value = load.title
			// console.log(openid.value, 2222)
			if (openid.value) {
				init(id.value)
				loginShow.value = false
			} else {
				loginShow.value = true
			}
			// loginShow.value = true
		}
		uni.setNavigationBarTitle({
			title: title.value
		})
	})
	onMounted(() => {
		console.log(uni.createSelectorQuery().select("#webview"))
	})


	onShareAppMessage(async (res) => {
		// if (res.from === 'button') {
		// 	console.log('来自按钮分享');
		// }
		// console.log(imgurl.value)
		return {
			title: title.value,
			path: `/pages/reportDetail/reportDetail?id=${id.value}&title=${title.value}`,
			imageUrl: imgurl.value
		};
	})

	onShareTimeline(async () => {
		// console.log(imgurl.value)
		return {
			title: title.value,
			query: `id=${id.value}&title=${title.value}`,
			imageUrl: imgurl.value
		};
	})
</script>
<style>
	/* 新增样式 */
	.noscroll {
		height: 100vh;
		overflow: hidden;
		position: fixed;
		width: 100%;
	}

	/* 兼容H5和小程序 */
	/* #ifdef H5 */
	.noscroll {
		touch-action: none;
	}

	/* #endif */
</style>
<style lang="scss" scoped>
	.container {
		height: 100vh;
		width: 100vw;
		background-color: $uni-bg-color;

		.title {
			font-size: 38rpx;
			text-align: center;
			width: 60%;
			margin: 0 auto;
			padding: 20rpx 0;
		}

		.content {
			padding: 0 20rpx;
		}

		.mask {
			height: 75vh;
			padding: 0 20rpx;
			background-color: $uni-bg-color-grey;

			-webkit-box-shadow: 0px -1rpx 5rpx 0px rgba(50, 50, 50, 0.25);
			-moz-box-shadow: 0px -1rpx 5rpx 0px rgba(50, 50, 50, 0.25);
			box-shadow: 0px -1rpx 5rpx 0px rgba(50, 50, 50, 0.25);

			border-radius: 20rpx 20rpx 0 0;

			@include bottomMagnet();

			.mask-box {
				height: 100%;
				width: 100%;
				position: relative;

				.button {
					margin: 0 auto;
					width: 45%;
				}
			}

			.member-box {
				padding-top: 210rpx;

				.remark {
					height: 90rpx;
					text-align: center;
					letter-spacing: 3rpx;
					font-size: 32rpx;
					color: $uni-text-color-grey;
				}

				.link {
					position: absolute;
					top: 70%;
					width: 100%;
					font-size: 32rpx;
					color: $uni-color-error;
					font-size: $uni-title-font-size-2;
					font-weight: bold;

					.text {
						text-align: center;
						letter-spacing: 5rpx;

						&:active {
							text-decoration: underline;
						}
					}
				}
			}

			.login-box {
				padding-top: 300rpx;
			}
		}

		.disable-scroll {
			position: fixed;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
		}

		.bottom-block {
			height: 110rpx;
		}

		.bottom-box {
			padding: 5rpx 25rpx;
			background-color: $uni-bg-color-grey;

			@include bottomMagnet();

			-webkit-box-shadow: 0px -1rpx 5rpx 0px rgba(50, 50, 50, 0.25);
			-moz-box-shadow: 0px -1rpx 5rpx 0px rgba(50, 50, 50, 0.25);
			box-shadow: 0px -1rpx 5rpx 0px rgba(50, 50, 50, 0.25);


			.menu-box {
				height: 100rpx;
				display: flex;
				align-items: center;
				justify-content: flex-end;
				gap: 50rpx;

				.menu-item {
					background-color: transparent;
					margin: 0;
					border: none;
					padding: 0;
				}

				.menu-item::after {
					border: none !important;
				}

				.iconfont {
					font-size: 42rpx;
					color: $uni-text-color-grey;
				}

				.active {
					color: yellow;
				}
			}
		}
	}
</style>