<template>
	<view>
		<view v-if="!loginShow" class="container" :style="{ height : `${loginShow ? '100vh' : 'auto' }`,
		overflow: `${loginShow ? 'hidden' : 'auto' }` }">
			<view class="container-poster" style="width: 100%;padding: 0 20rpx;">
				<channel-live v-if="feedShow" :feed-id="feedId" :finder-user-name="finderId"></channel-live>
				<image v-else show-menu-by-longpress :src="courseDetail.poster?courseDetail.poster:''" mode="widthFix"
					style="width: 100%;"></image>
			</view>
			<view class="course-tab-list">
				<view class="course-tab-item" v-for="(data, index) in items" :key="index" @click="onClickItem(index)"
					:class="currentTab === index ? 'tab-active' : ''">
					{{ data }}
				</view>
			</view>
			<view class="content" v-if="currentTab === 0" style="overflow: hidden;">
				<view class="content-text"
				:style="{
					marginBottom: `${videoShow?'140rpx':'0'}`,
					paddingBottom: `${videoShow?'150rpx':'0'}`
				}"
				style="height: 100%;overflow: scroll;padding-left: 20rpx;padding-right: 20rpx;">
					<view class="text-title">{{courseDetail.title}}</view>
					<view class="text-title">课程概述</view>
					<view class="text-content">{{courseDetail.summary}}</view>
					<view class="text-title">课程时间</view>
					<view class="text-content">{{courseDetail.date ? getDateWeek(courseDetail.date) : ''}}</view>
					<view class="text-title">培训地点</view>
					<view class="text-content">{{courseDetail.loc}}</view>
					<view class="text-title" style="color: red;font-weight: 500;font-size: 30rpx;">如需取消报名，请联系教育培训部工作人员13332876414/13302262603</view>
					<view class="text-tip" v-if="!isMember && courseDetail.viewMode === '2'" @click="toJoin">个人会员或单位会员免费，点击现在入会></view>
					<view style="width: 100%;height: 200rpx;"></view>
				</view>
				<view class="section-bottom-fixed" @click="toVideo" v-show="videoShow">
					<text>预约课程</text>
				</view>
				<view :class="['section-bottom-fixed', `${courseDetail.hasReg ? 'bg-blue' : ''}`]" v-show="regShow" @click="toReg">
					<text>{{ courseDetail?.hasReg ? '报名成功' : '点击报名' }}</text>
				</view>
			</view>
			<view class="content" v-if="currentTab === 1" style="overflow: hidden;">
				<view class=""
					style="margin-bottom: 140rpx;padding-bottom: 150rpx;height: 100%;overflow: scroll;padding-left: 20rpx;padding-right: 20rpx;">
					<view v-for="(comment, index) in sortedCommentList" :key="index" class="comment-list-item">
						<view class="comment-list-left">
							<image :src="comment.icon" class="comment-list-avator"></image>
						</view>
						<view class="comment-list-right">
							<view style="margin-bottom: 15rpx;">
								<text class="comment-list-username">{{ comment.username }}</text>
								<text class="comment-list-moment">{{ formatTime(comment.commentTime) }}</text>
							</view>
							<view>{{ comment.content }}</view>
						</view>
					</view>
				</view>
				<view class="section-bottom " style="background-color: #f2f2f2;">
					<view class="comment-input-box">
						<u-input :custom-style="inputStyle" class="comment-input" v-model="comment" :border="false"
							placeholder="写留言" height="60" adjust-position />
						<u-button class="comment-button" :hair-line="false" :custom-style="customStyle"
							@click="toSend">发送</u-button>
					</view>
				</view>
			</view>
		</view>
		<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;background:none;">
				<view style="text-align: center;margin: 70rpx 0;">
					<u-button size="medium" type="error" @click="toLogin">登录查看</u-button>
				</view>
			</view>
		</u-popup>
		<canvas canvas-id="shareCanvas"
			:style="{ position: 'absolute', top: '-10000px', width: '750px', height: '600px' }"></canvas>
	</view>

</template>

<script setup>
	import {
		loadCourseDetail,
		loadCommentList,
		sendComment,
		regCourse
	} from "@/api/edu.js"
	import {
		getToken
	} from '@/utils/auth.js'
	import {
		useAuthStore
	} from '@/store/authStore'
	import dayjs from 'dayjs'
	dayjs.locale('zh-cn')
	const authStore = useAuthStore();
	// const isMember = ref(false)
	const feedShow = ref(false)
	import {
		ref,
		computed
	} from 'vue'
	import {
		onLoad,
		onShow,
		onShareAppMessage,
		onShareTimeline
	} from '@dcloudio/uni-app'

	const courseDetail = ref({});
	const courseId = ref(null);
	const courseName = ref(null);
	const items = ref(['课程简介', '观看评论']);
	const currentTab = ref(0);
	const comment = ref("");
	const feedId = ref(null);
	const finderId = "sphIfs9sYiL5RB3"
	// 评论发送按钮样式
	const customStyle = ref({
		backgroundColor: '#e6e6e6',
		color: '#333333',
		fontWeight: 'bold',
		height: '60rpx',
		marginLeft: '20rpx',
		border: 'none',
		fontSize: '26rpx'
	})
	// 评论输入框样式
	const inputStyle = ref({
		backgroundColor: '#e6e6e6',
		color: '#333333',
		borderRadius: '5px',
		padding: '0 20rpx',
		fontSize: '26rpx'
	})
	// 评论列表
	const commentList = ref([])

	// 点击tabs，切换
	function onClickItem(e) {
		if (currentTab.value != e) {
			currentTab.value = e;
			if (e === 2) {
				getComment(courseId.value)
			}
		}
	}
	const toJoin = () =>{
		uni.navigateTo({
			url: "/pages/swiperDetail/swiperDetail?id=12117"
		})
	}
	// 初始化
	function init(id) {
		loadCourseDetail(id).then(res => {
			if (res?.data) {
				courseDetail.value = res.data;
				showBuy.value = showBuyAction()
				if(courseDetail.value.regType === '1'
				&& (courseDetail.value.status === '2' ||
				courseDetail.value.status === '3')){
					// console.log(123456)
					getVideo()
				}
				// console.log(courseDetail, "课程详情")
			}
		})
	}

	function getComment(id) {
		loadCommentList(id).then(res => {
			if (res?.data) {
				commentList.value = res.data;
			}
		})
	}
	// 购买课程
	function toBuy() {
		uni.navigateTo({
			url: "/pages/goOnEdu/course/courseDetail/courseOrder?id=" + courseId.value
		})
		// console.log("购买该课程", courseDetail.value.id)
	}

	// 获取图片信息
	const getImageInfo = (imgUrl) => {
		return new Promise((resolve) => {
			uni.getImageInfo({
				src: imgUrl,
				success: (res) => resolve(res),
				fail: () => resolve(null)
			});
		});
	};


	function toSend() {
		sendComment({
			courseId: courseId.value,
			content: comment.value,
			commentTime: formatDate(new Date())
		}).then(res => {
			getComment(courseId.value)
			comment.value = ""
		})
	}

	function formatDate(date) {
		const pad = (num) => num.toString().padStart(2, '0');

		const year = date.getFullYear();
		const month = pad(date.getMonth() + 1); // 月份从0开始，需加1
		const day = pad(date.getDate());

		const hours = pad(date.getHours());
		const minutes = pad(date.getMinutes());
		const seconds = pad(date.getSeconds());

		return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
	}

	function showBuyAction() {
		if (courseDetail.value.viewMode === '2' &&
			!isMember.value &&
			!courseDetail.value.hasBuy &&
			currentTab.value === 0) {
			// console.log(1)
			return true
		}
		// 付费，不管是不是会员，并且没买的
		if (courseDetail.value.viewMode === '3' &&
			!courseDetail.value.hasBuy &&
			currentTab.value === 0) {
			// console.log(2)
			return true
		}
		// console.log(3)
		return false
	}
	const showBuy = ref(false)
	const isMember = computed(() => {
		return authStore.userInfo.isMember == '0' ? false : true
	})
	const isLogin = computed(() => {
		if (getToken() && authStore.isAuthenticated) {
			return true
		} else {
			return false
		}
	})
	const loginShow = ref(true)

	function toLogin() {
		// loginShow.value = false
		let url = {
			url: '/pages/goOnEdu/course/courseDetail/courseDetail',
			id: courseId.value,
			title: courseName.value
		}
		uni.setStorageSync("redirect", url)
		uni.navigateTo({
			url: `/pages/login/login`
		})
	}
	// 初始化页面
	onLoad((option) => {
		const {
			id,
			title
		} = option;
		courseId.value = id
		courseName.value = title
		uni.setNavigationBarTitle({
			title: title
		});
		if (isLogin.value) {
			loginShow.value = false
		} else {
			loginShow.value = true
		}
		// toVideo()
		// loginShow.value = true
	})
	onShow(() => {
		if (isLogin.value) {
			init(courseId.value)
			getComment(courseId.value)
		}
	})

	function formatDateS(dateStr) {
		return dateStr.replace(" ", "T");
	}

	// 日期格式：xxxx年xx月xx日（星期x）
	function getDateWeek(dateStr) {
		console.log(dateStr,"dateStr")
		// 将日期字符串转换为 Date 对象
		  const date = new Date(dateStr.replace(/-/g, '/'));
		  // 检查日期是否有效
		  if (isNaN(date.getTime())) {
		    return dateStr; // 如果无效，返回原字符串
		  }
		  // 获取年月日
		  const year = date.getFullYear();
		  const month = String(date.getMonth() + 1).padStart(2, '0');
		  const day = String(date.getDate()).padStart(2, '0');
		  // 获取星期几
		  const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
		  const weekday = weekdays[date.getDay()];
		  // 获取时分
		  const hours = String(date.getHours()).padStart(2, '0');
		  const minutes = String(date.getMinutes()).padStart(2, '0');
		  // 组合成新格式
		  return `${year}-${month}-${day}(星期${weekday}) ${hours}:${minutes}`;
	}

	function formatTime(timeString) {
		const commentDate = new Date(formatDateS(timeString));
		const now = new Date();
		const diff = now - commentDate;

		const minutes = Math.floor(diff / 60000);
		const hours = Math.floor(diff / 3600000);
		const days = Math.floor(diff / 86400000);

		if (minutes < 1) { // 修改这里以处理0分钟
			return "刚刚";
		} else if (minutes < 60) {
			return `${minutes}分钟前`;
		} else if (hours < 24) {
			return `${hours}小时前`;
		} else {
			return commentDate.toISOString().split('T')[0];
		}
	}

	const sortedCommentList = computed(() => {
		return commentList.value.sort((a, b) =>
			new Date(formatDateS(b.commentTime)) - new Date(formatDateS(a.commentTime))
		);
	});

	onShareAppMessage(async (res) => {
		// console.log(processedImage)
		return {
			title: courseName.value,
			path: `/pages/goOnEdu/course/courseDetail/courseDetail?id=${courseId.value}&title=${courseName.value}`,
			imageUrl: courseDetail.value.cover
		};
	})

	onShareTimeline(async () => {
		return {
			title: courseName.value,
			query: `id=${courseId.value}&title=${courseName.value}`,
			imageUrl: courseDetail.value.cover
		};
	})


	// 线上-点击预约-跳转预告
	function toVideo(){
		wx.getChannelsLiveNoticeInfo({
			'finderUserName': "sphIfs9sYiL5RB3",
			success: (res)=>{
				let noticeId = null;
				if(res.otherInfos.length > 0){
					let date1 = new Date(formatDateS(courseDetail.value.date))
					res.otherInfos.forEach(item=>{
						let date = new Date(item.startTime*1000);
						// console.log(item,date1, date)
						if(date1.getTime()===date.getTime()){
							noticeId = item.noticeId;
						}
					})
				}
				// console.log(noticeId)
				if(!noticeId){
					noticeId = res.noticeId
				}
				// console.log(res)
				wx.reserveChannelsLive({
					"noticeId": noticeId,
					success: (resp)=>{
						console.log(resp)
					},
					fail: (err)=>{
						console.log(err)
					}
				})
			},
			fail(err) {
				console.error('调用失败:', err);
			}
		})
	}
	// 线上课程-获取视频号回放
	function getVideo(){
		const startDate = dayjs(courseDetail.value.date).format("YYYY-MM-DD");
		const endDate = dayjs(startDate).add(1, 'day').format("YYYY-MM-DD");
		// 获取时间戳
		const startTime = new Date(startDate).getTime();
		const endTime = new Date(endDate).getTime();
		wx.getChannelsLiveInfo({
			'finderUserName': "sphIfs9sYiL5RB3",
			startTime: startTime,
			endTime: endTime,
			success: (res)=>{
				feedId.value = res.feedId;
				// console.log("直播信息", res)
				feedShow.value = true
			},
			fail(err) {
				console.error('调用失败:', err);
			}
		})
	}
	// 线上课程-进来后-是否显示预约按钮
	const videoShow = computed(()=>{
		// regType = 1 是线上课程
		// feedShow为true是回放
		if(courseDetail.value?.status==='2' || courseDetail.value?.status==='3'){
			return false;
		}
		return (courseDetail.value?.regType ==='1') && !feedShow.value
	})
	// 线下课程-是否显示报名按钮
	const regShow = computed(()=>{
		// regType = 0 是线上课程
		// 缺少判断是否购买
		if(courseDetail.value?.status === '2' || courseDetail.value?.status === '3' ){
			return false
		}
		return courseDetail.value?.regType ==='0'
	})
	function toReg(){
		let isReg = courseDetail.value.hasReg ?? false;
		let viewMode = courseDetail.value.viewMode
		if(isReg){
			return;
		}
		if(viewMode==='1' || (isMember.value && viewMode==='2')){
			// 直接报名
			console.log("直接报名")
			regCourse(courseId.value).then(res=>{
				if(res.code===0){
					init(courseId.value)
				}
			})
			return
		}
		uni.navigateTo({
			url: "/pages/goOnEdu/course/courseDetail/courseOrder?id=" + courseId.value
		})
		return
	}
</script>
<style lang="scss">
	.u-drawer-bottom {
		background-color: transparent !important;
	}
</style>
<style lang="scss" scoped>
	.container {
		// height: 100vh;
		width: 100vw;
		background-color: #fff;
		// padding: 0 20rpx;
	}

	.course-tab-list {
		display: flex;
		background-color: #f2f2f2;
		flex: 0 0 auto;
		margin: 0 20rpx;

		.course-tab-item {
			width: 100%;
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
		}

		.tab-active {
			border-bottom: 1px solid #0069f6;
		}
	}

	// .container-poster{
	// 	height: calc(100vh - 500rpx - env(safe-area-inset-bottom, 0));
	// }
	.content {
		overflow: scroll;
		// height: calc(100vh - 500rpx - env(safe-area-inset-bottom, 0));
		height: 700rpx;
		position: relative;

		.content-text {
			// env(safe-area-inset-bottom, 0)
			// padding: 0 20rpx 0;
			font-size: 38rpx;

			.text-title {
				font-weight: bold;
				margin-bottom: 15rpx;
				margin-top: 15rpx;
			}

			.text-content {
				font-size: 32rpx;
				margin-bottom: 20rpx;
			}

			.text-tip {
				color: red;
				// margin-bottom: 20rpx;
				margin-bottom: env(safe-area-inset-bottom, 0);
			}
		}
		.content-button-hold{
			width: 100%;
			height: 120rpx;
		}
		.content-button{
			width: 100%;
			// height: 100rpx;
			// line-height: 100rpx;
			text-align: center;
			background-color: #fe0000;
			color: #fff;
			// position: absolute;
			// bottom: 0; calc(20rpx + env(safe-area-inset-bottom, 0))
			padding:20rpx  0 20rpx;
		}
	}

	.section-bottom-fixed {
		height: 90rpx;
		color: #fff;
		font-size: 34rpx;
		text-align: center;
		line-height: 80rpx;
		background-color: #fe0000;
		width: 100%;
		position: fixed;
		bottom: 0;
		box-sizing: content-box;
		// padding-bottom: env(safe-area-inset-bottom, 0);
	}
	.section-bottom {
		height: 90rpx;
		color: #fff;
		font-size: 34rpx;
		text-align: center;
		line-height: 80rpx;
		background-color: #fe0000;
		width: 100%;
		position: absolute;
		bottom: 0;
		box-sizing: content-box;
		padding-bottom: env(safe-area-inset-bottom, 0);
	}
	.bg-blue{
		background-color: #3097ff;
	}

	.comment-input-box {
		width: 100%;
		height: 100%;
		display: flex;
		box-sizing: border-box;
		padding: 0 20rpx;
		align-items: center;

		.comment-input {
			flex: 1;
		}

		.comment-button {
			flex: 0 0 auto;
		}
	}

	.comment-list-item {
		display: flex;
		padding: 20rpx 0;
		font-size: 28rpx;

		.comment-list-left {
			flex: 0 0 auto;
			padding-right: 20rpx;
			padding-left: 10rpx;

			.comment-list-avator {
				width: 100rpx;
				height: 100rpx;
				border-radius: 50%;
			}
		}

		.comment-list-right {
			flex: 1;

			.comment-list-username {
				padding-right: 25rpx;
				font-size: 32rpx;
				font-weight: bold;
			}
		}
	}
</style>
