<template>
	<view>
		<view class="padding bg radius margin">
			<view class="padding-top">发布内容</view>
			<view class="margin-tb-sm">
				<u-input v-model="form.describes" style="border-radius: 20rpx;" type="textarea" height="200"
					placeholde="请填写发布内容" maxlengt="200" :clearable="false" />
			</view>
		</view>
		<view class=" padding bg radius margin">
			<view class="margin-top-sm">上传视频</view>
			<view class="flex" style="overflow: hidden;flex-wrap: wrap;">
				<view class="margin-top flex margin-right-sm flex-wrap" v-if="videosList">
					<view class="flex" style="width: 200rpx;height: 200rpx;margin-right: 5rpx;position: relative;">
						<video style="width: 100%;height: 100%;" :src="videosList"></video>
						<view style="z-index: 9;position: absolute;top: -15rpx;right: -15rpx;" @click="headVideoremove">
							<u-icon name="close-circle-fill" color="#d81e06" size="50rpx"></u-icon>
						</view>
					</view>
				</view>
			</view>
			<view class="margin-top" @click="addvideo" v-if="videosList.length<=0">
				<view class="flex justify-center align-center video-img">
					<view>
						<view class="text-center">
							<image src="../../static/images/my/video.png" style="width: 80rpx;height: 80rpx;"></image>
						</view>
						<view class="text-center add-word">添加视频</view>
					</view>
				</view>
			</view>
		</view>
		<view class=" padding bg radius margin">
			<view class="margin-top-sm">视频封面</view>
			<view class="flex" style="overflow: hidden;flex-wrap: wrap;">
				<view class="margin-top flex margin-right-sm flex-wrap" v-if="form.headImg && form.headImg.length">
					<view class="flex" style="width: 200rpx;height: 200rpx;margin-right: 5rpx;position: relative;">
						<image :src="form.headImg" style="width: 100%;height: 100%;"></image>
						<view style="z-index: 9;position: absolute;top: -15rpx;right: -15rpx;"
							@click="headImgremove(index)">
							<u-icon name="close-circle-fill" color="#d81e06" size="50rpx"></u-icon>
						</view>
					</view>
				</view>
			</view>
			<view class="margin-top" @click="addImage" v-if="form.headImg.length<=0">
				<view class="flex justify-center align-center video-img">
					<view>
						<view class="text-center">
							<image src="../../static/images/my/avatar.png" style="width: 80rpx;height: 80rpx;"></image>
						</view>
						<view class="text-center add-word">添加封面</view>
					</view>
				</view>
			</view>
		</view>
		<view class="push-button">
			<view class="tabbar" @click="submit()">发布
			</view>
		</view>
		<!-- <view>
			<video
			      v-if="videoSrc" 
			      :src="videoSrc"
			      controls 
			      style="width: 0; height: 0"
			      id="myVideo"
			    ></video>
			    <canvas 
			      :style="{ border: '1px solid red' }"
			      canvas-id="myCanvas"
				  id="myCanvas"
			      :width="canvasWidth"
			      :height="canvasHeight"
			    ></canvas>
		</view> -->
	</view>
</template>

<script>
	import * as websocketUtils from 'utils/websocketUtils.js';

	export default {
		data() {
			return {
				form: {
					//头像上传
					headImg: '',

				},
				//头像上传
				headImg: [],
				videos: [],
				videosList: '',
				canvasWidth: 295,
				canvasHeight: 355,
				videoSrc: '',
			}
		},
		onLoad(e) {},
		methods: {
			headImgremove(index) {
				this.form.headImg = ''
			},
			headVideoremove() {
				this.videosList = ''
			},
			submit() {
				if (!this.videosList) {
					uni.showToast({
						title: '请上视频',
						icon: 'none',
						duration: 1000
					})
					return;
				}
				if (!this.form.describes) {
					uni.showToast({
						title: '请填发布内容',
						icon: 'none',
						duration: 1000
					})
					return
				}
				if (!this.form.headImg) {
					// uni.showToast({
					// 	title: '请上视频封面',
					// 	icon: 'none',
					// 	duration: 1000
					// })
					// return;
					this.form.headImg = "https://wx.sjajk.com/file/uploadPath/logo2.png";
				}
				let data = {
					createBy: uni.getStorageSync("userId"),
					filePath: this.videosList,
					picPath: this.form.headImg,
					content: this.form.describes,
				}
				this.$Request.postJson("/app/shipinquan/add", data).then(res => {
					if (res.code == 0) {
						uni.showToast({
							title: '操作成功！',
							icon: 'none'
						})
						setTimeout(function() {
							uni.navigateTo({
								url: '/pages/video/index'
							})
						}, 1000)
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				});
			},
			async addvideo(e) {
				let that = this
				uni.chooseVideo({
					count: 1,
					sourceType: ['album', 'camera'],
					success: res => {
						that.videos.push(res.tempFilePath);
						for (let i = 0; i < that.videos.length; i++) {
							that.$queue.showLoading("上传中...");
							uni.getFileInfo({
								filePath: that.videos[i],
								success: async (infoRes) => {
									const size = infoRes.size;
									if (size / 1024 / 1024 > 10) {
										// 图片大于2MB
										uni.showToast({
											icon: 'error',
											title: '视频超出10MB限制,请重新选择'
										})
									} else {
										this.videoSrc = res.tempFilePath; //2025-03-28
										//获取视频第一帧作为封面，ctx.drawImage时ctx.draw不回调
										// await this.onLoadedMetadata(); //2025-03-28
										
										// 图片小于等于2MB
										uni.uploadFile({ // 上传接口
											url: websocketUtils.uploadFileUrl(), //真实的接口地址
											filePath: that.videos[i],
											name: 'file',
											success: (uploadFileRes) => {
												that.videosList = JSON.parse(
													uploadFileRes.data).data
												console.log("that.videosList", that
													.videosList)
												uni.hideLoading();
											}
										});
									}
								},
								fail: () => {
									console.log("上传失败")
									// callback(false);
								}
							});
						}
					}
				})
			},

			async onLoadedMetadata() {
				let that = this
				const video = uni.createVideoContext('myVideo', that); //2025-03-28
				video.play()
				setTimeout(function(){
					video.pause();
				}, 100)
				const ctx = uni.createCanvasContext('myCanvas', that) //2025-03-28
				ctx.drawImage(video, 0, 0, 295, 355);
				ctx.draw(true, () => {
				  console.log('✅ 标准回调执行');
				  // 第三步：在绘制完成的回调中获取图片
					uni.canvasToTempFilePath({
					  canvasId: 'myCanvas',
					  quality: 0.8,
					  success: res => {
						that.checkImageSize(res.tempFilePath, (isValid) => {
							if (isValid) {
								// 图片校验通过后的逻辑
								console.log('图片校验通过，可以上传');
							} else {
								console.log('图片超出大小限制，请重新选择');
							}
						});
						resolve()
					  },
					  fail: err => {
						console.error('截图失败:', err)
						reject(err)
					  }
					}, this)
				});
				
			// 	  if (!this.checkCanvasReady()) return;
			
			// 	  // 绘制内容（必须包含可见元素）
			// 	  ctx.beginPath();
			// 	  ctx.arc(150, 150, 50, 0, Math.PI * 2);
			// 	  ctx.fillStyle = '#00ff00';
			// 	  ctx.fill();
			
			// 	  // H5 专用绘制方法
			// 	  await this.h5Draw(ctx);
			},
			
			checkCanvasReady() {
			  // DOM 级检测
			  const canvas = document.getElementById('myCanvas');
			  if (!canvas) {
				console.error('Canvas 元素未找到');
				return false;
			  }
			  return true;
			},
			
			async h5Draw(ctx) {
			  return new Promise((resolve) => {
				let callbackExecuted = false;
				
				// 标准回调
				ctx.draw(true, () => {
				  callbackExecuted = true;
				  console.log('✅ 标准回调执行');
				  resolve();
				});
		
				// 双重保障
				setTimeout(() => {
				  if (!callbackExecuted) {
					console.log('⏱️ 强制通过定时器完成');
					resolve();
				  }
				}, 100);
			  });
			},

			// 检查图片尺寸
			checkImageSize(filePath, callback) {
				let that = this
				uni.getFileInfo({
					filePath: filePath,
					success: (infoRes) => {
						const size = infoRes.size;
						if (size / 1024 / 1024 > 2) {
							// 图片大于2MB
							uni.showToast({
								icon: 'error',
								title: '图片超出2MB限制,请重新选择'
							})
							callback(false);
						} else {
							// 图片小于等于2MB
							this.uploadImage(filePath)
							callback(true);
						}
					},
					fail: () => {
						callback(false);
					}
				});
			},
			// 上传图片
			uploadImage(filePath) {
				console.log("filePath", filePath)
				let that = this
				uni.uploadFile({ // 上传接口
					url: websocketUtils.uploadFileUrl(), //真实的接口地址
					filePath: filePath,
					name: 'file',
					success: (uploadFileRes) => {
						that.form.headImg = JSON.parse(uploadFileRes.data).data
						uni.hideLoading();

					}
				});
			},
			addImage() {
				let that = this
				uni.chooseImage({
					count: 1,
					sourceType: ['album', 'camera'],
					success: res => {
						that.$queue.showLoading("上传中...");
						var tempFilePaths = res.tempFilePaths[0]
						that.checkImageSize(tempFilePaths, (isValid) => {
							if (isValid) {
								// 图片校验通过后的逻辑
								console.log('图片校验通过，可以上传');
							} else {
								console.log('图片超出大小限制，请重新选择');
							}
						});
					}
				})
			},
		}
	}
</script>

<style>
	page {
		background-color: #F7F7F7;
	}

	.bg {
		width: 94%;
		margin: 20rpx auto;
		background-color: #FFFFFF;
		padding: 20rpx 36rpx;
		border-radius: 26rpx;
	}

	.add-word {
		font-size: 26rpx;
		color: #afb5c1;
	}

	.skbox {}

	.skleft {
		width: 160rpx;
		font-size: 28rpx;
	}

	.u-form-item {
		padding: 10rpx !important;
	}

	.u-form-item--right__content__slot {
		flex: 200rpx 1 !important;
	}

	/*.footer {
		padding-left: 30upx;
		font-size: 24upx;
		color: #666666;
		text-align: center;
		display: flex;
		margin-bottom: 20rpx;
	}*/

	.u-input__input {
		color: balck !important;
	}

	.title_btn {
		height: 78upx;
		line-height: 78upx;
		/* background: #f7f7f7; */
	}

	.push-button {
		width: 100%;
		height: 48px;
		position: fixed;
		bottom: 0px;
		display: flex;
		flex-direction: column;
		align-items: center;
		margin: 0 auto;
	}

	.tabbar {
		display: inline-block;
		width: 92%;
		margin: 0 auto;
		text-align: center;
		background: linear-gradient(90deg, #019C88, #28BA92, #35C495);
		height: 40px;
		border-radius: 28px;
		color: #ffffff;
		line-height: 40px;
		margin-top: 4px;
		font-size: 17px;
	}

	.popup_pay {
		width: 100%;
		position: relative;
		padding-bottom: 0rpx;
		/* height: 160px; */
		/* #ifndef MP-WEIXIN */
		/* height: 130px; */
		/* #endif */

	}

	.pay_btn {
		width: 90%;
		margin: 0 auto;
		text-align: center;
		background: #1777FF;
		height: 80rpx;
		border-radius: 16rpx;
		color: #ffffff;
		line-height: 80rpx;

	}

	.hb {
		/* #ifdef H5 */
		padding-bottom: 180rpx;
		/* #endif */
	}

	.bgCol2 {
		color: #557EFD;
	}

	.video-img {
		width: 200rpx;
		height: 200rpx;
		background: #f7f8fa;
		border-radius: 20rpx;
	}
</style>