<template>
	<view class="page">
		<!-- <u-navbar title="发布动态" :border-bottom="false" :background="bgc" back-icon-color="#262B37" title-color='#262B37'
					title-size='36' height='46' id="navbar">
				</u-navbar>
		        <view class="topcont">
		        	<view class="title">
		        		<input type="text" v-model="title" placeholder="添加标题"/>
		        	</view>
					<textarea class="cont" name="" v-model="cont" placeholder="写下自己的感受，分享给更多的人" id="" cols="30" rows="10"></textarea>
					<view class="imglist">
						<view class="mediaitem" v-for="(item,index) in mediaList" :key="index">
							<image v-if="item.type === 'image'" class="media-preview" :src="item.url" mode="aspectFill" @click="previewMedia(index)"></image>
							<video v-else-if="item.type === 'video'" class="media-preview" :src="item.url" :poster="item.poster" controls="true" :show-play-btn="true" :show-center-play-btn="true" :enable-progress-gesture="true" :enable-fullscreen="true" @click="previewMedia(index)">
							</video>
							<view class="delete-btn" @click="deleteMedia(index)">
									<text class="delete-icon">×</text>
							</view>
						</view>
						<view class="upload-btn" @click="btnsc">
							<image class="sc" src="https://api.ccttiot.com/smartmeter/img/static/u3z28zohbXoJ5kWcR6X1" mode=""></image>
						</view>
					</view>
		        </view>
		        <view class="botanniu">
		        	<view class="an" @click="btnfb">
		        		发布
		        	</view>
		        </view> -->
	</view>
</template>

<script>
	export default {
		data() {
			return {
                bgc: {
                	backgroundColor: "#fff",
                },
				title:null,
				cont:null,
				token:'',
				mediaList:[] ,// 改为媒体列表，包含图片和视频
				xqdz:null,
				latitude:null,
				longitude:null,
				jlflag:true,
				domain:''
			}
		},
		onLoad() {
            this.getqiniuyun()
		},
		methods: {
			// 点击发布动态
			btnfb(){
				if(this.jlflag == false){
					return
				}
				this.jlflag = false
				const picture = this.mediaList.map(item => item.url).join(',')
				let data = {
					picture:picture,
					content:this.cont,
					title:this.title,
					// latitude:this.latitude,
					// longitude:this.longitude,
					// location:this.xqdz
				}
				this.$u.post("/app/feed/add",data).then((res) => {
					if (res.code == 200) {
						uni.showToast({ title: '发布成功', icon: 'success',duration:3000 })
						setTimeout(()=>{
							uni.navigateBack()
							this.jlflag = true
						},1500)
					}else{
						uni.showToast({ title: res.msg, icon: 'none',duration:3000 })
						this.jlflag = true
					}
				})
			},
			// 点击选择位置
			btnweizhi(){
				uni.chooseLocation({
					success: (res) => {
						this.latitude = res.latitude
						this.longitude = res.longitude
						this.xqdz = res.name
					},
					fail: function(err) {
						console.log('选择位置失败', err)
					},
					complete: (res) => {
						if (res.errMsg === 'chooseLocation:ok') {} else if (res.errMsg.indexOf('chooseLocation:cancel') === 0) {
							uni.showToast({
								title: '您取消了位置选择',
								icon: 'none',
								duration:3000
							})
						}
					}
				})
			},
			// 获取七牛云上传token
			getqiniuyun(){
				this.$u.get("common/qiniu/uploadInfo").then((res) => {
					if (res.code == 200) {
						this.token = res.token
						this.domain = res.domain
					}
				})
			},
			// 点击上传媒体文件
			btnsc(){
				if(this.mediaList.length >= 9){
					return uni.showToast({ title: '最多选择九张图片或视频', icon: 'none',duration:3000 })
				}
				let _this = this
				// 使用 uni.chooseMedia 从手机相册选择图片和视频
				uni.chooseMedia({
					count: 9 - this.mediaList.length, // 剩余可选择的数量
					mediaType: ['image', 'video'], // 允许选择图片和视频
					sourceType: ['album', 'camera'], // 允许从相册和相机选择
					camera: 'back', // 默认后置摄像头
					success(res) {
						const tempFiles = res.tempFiles
						tempFiles.forEach(file => {
							wx.uploadFile({
								url: 'https://up-z2.qiniup.com',
								name: 'file',
								filePath: file.tempFilePath, //文件路径
								formData: {
									token: _this.token, //后端返回的token
									key: _this.getUploadFileName(file.tempFilePath) //传的文件名称
								},
								success: function(res) {
									let str = JSON.parse(res.data)
									let fileUrl = _this.domain + '/' + str.key
									// 根据文件后缀名判断类型
									let fileType = _this.getFileType(file.tempFilePath)
									// 添加到媒体列表
									_this.mediaList.push({
										url: fileUrl,
										type: fileType,
										poster: fileType === 'video' ? null : null // 视频不设置poster，避免加载失败
									})
								}
							})
						})
					},
					fail(err) {
						console.log('选择媒体失败:', err)
						uni.showToast({
							title: '选择失败',
							icon: 'none',
							duration: 3000
						})
					}
				})
			},
			// 获取上传的文件名
			getUploadFileName(fileName) {
			    return fileName.slice(fileName.lastIndexOf("/") + 1, fileName.length);
			},
			// 根据文件路径判断文件类型
			getFileType(filePath) {
				const extension = filePath.toLowerCase().split('.').pop()
				const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']
				const videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'webm', 'mkv']
				if (imageExtensions.includes(extension)) {
					return 'image'
				} else if (videoExtensions.includes(extension)) {
					return 'video'
				} else {
					return 'image' // 默认当作图片处理
				}
			},
			// 预览媒体文件 - 图文混合预览
			previewMedia(index) {
				const media = this.mediaList[index]
				console.log('预览媒体:', media)
				console.log('当前索引:', index)
				// 统一在微信小程序端使用 previewMedia 实现图文混合预览
				// #ifdef MP-WEIXIN
				const sources = this.mediaList.map((item) => {
					if (item.type === 'video') {
						return { 
							url: item.url, 
							type: 'video', 
							poster: item.poster || '' 
						}
					}
					return { 
						url: item.url, 
						type: 'image' 
					}
				})
				console.log('预览源数据:', sources)
				uni.previewMedia({
					current: index, 
					sources,
					success: (res) => {
						console.log('预览成功:', res)
					},
					fail: (err) => {
						console.error('预览失败:', err)
						uni.showToast({
							title: '预览失败',
							icon: 'none',
							duration:3000
						})
					}
				})
				return
				// #endif
				// 其他平台回退为仅图片可预览
				if (media.type === 'video') {
					// 视频全屏播放
					this.playVideo(index)
					return
				}
				// 图片预览
				const urls = this.mediaList.filter(item => item.type === 'image').map(item => item.url)
				if (!urls.length) return
				uni.previewImage({
					urls: urls,
					current: media.url
				})
			},
			// 播放视频
			playVideo(index) {
				const media = this.mediaList[index]
				console.log(media);
				if (media.type == 'video') {
					// 使用uni.previewVideo进行全屏播放
					uni.previewVideo({
						sources: [{
							src: media.url,
							type: 'mp4'
						}],
						autoplay: true,
						loop: false,
						defaultMuted: false,
						showPlayBtn: true,
						showCenterPlayBtn: true,
						enableProgressGesture: true,
						showFullscreenBtn: true,
						showMuteBtn: true
					})
				}
			},
			// 删除媒体文件
			deleteMedia(index) {
				uni.showModal({
					title: '确认删除',
					content: '确定要删除这个文件吗？',
					success: (res) => {
						if (res.confirm) {
							this.mediaList.splice(index, 1)
						}
					}
				})
			},
		}
	}
</script>

<style lang="scss">
	::v-deep .u-iconfont,
	::v-deep .u-title{
		padding-bottom: 22rpx !important;
	}
	.botanniu{
		width: 750rpx;
		height: 152rpx;
		background: #FFFFFF;
		border-radius: 0rpx 0rpx 0rpx 0rpx;
		position: fixed;
		left: 0;
		bottom: 0;
		padding-top: 34rpx;
		.an{
			width: 698rpx;
			height: 86rpx;
			background: #48893B;
			border-radius: 12rpx 12rpx 12rpx 12rpx;
			font-weight: 600;
			font-size: 36rpx;
			color: #FFFFFF;
			margin: auto;
			text-align: center;
			line-height: 86rpx;
		}
	}
	.weizhi{
		width: 698rpx;
		height: 112rpx;
		background: #FFFFFF;
		border-radius: 20rpx 20rpx 20rpx 20rpx;
		margin: auto;
		margin-top: 24rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 40rpx;
		box-sizing: border-box;
		.lt{
			display: flex;
			align-items: center;
			text{
				margin-left: 10rpx;
				margin-right: 10rpx;
			}
			image{
				width: 40rpx;
				height: 40rpx;
			}
			input{
				width: 530rpx;
			}
		}
		.rt{
			image{
				width: 36rpx;
				height: 36rpx;
				margin-top: 4rpx;
			}
		}
	}
	.topcont{
		width: 698rpx;
		max-height: 2580rpx;
		background: #FFFFFF;
		border-radius: 20rpx 20rpx 20rpx 20rpx;
		margin: auto;
		margin-top: 24rpx;
		padding-top: 20rpx;
		padding-bottom: 40rpx;
		box-sizing: border-box;
		.imglist{
			display: flex;
			width: 620rpx;
			margin: auto;
			gap: 32rpx;
			flex-wrap: wrap;
			margin-top: 30rpx;
			.upload-btn{
				.sc{
					width: 180rpx;
					height: 180rpx;
					border-radius: 20rpx;
					border: 2rpx dashed #E0E0E0;
				}
			}
			
			.mediaitem{
				position: relative;
				width: 180rpx;
				height: 180rpx;
				border-radius: 20rpx;
				
				.media-preview{
					width: 100%;
					height: 100%;
					border-radius: 20rpx;
					object-fit: cover;
				}
				
				.play-icon{
					position: absolute;
					top: 50%;
					left: 50%;
					transform: translate(-50%, -50%);
					width: 60rpx;
					height: 60rpx;
					background: rgba(0, 0, 0, 0.6);
					border-radius: 50%;
					display: flex;
					align-items: center;
					justify-content: center;
					color: #fff;
					font-size: 24rpx;
					font-weight: bold;
				}
				
				.delete-btn{
					position: absolute;
					top: -8rpx;
					right: -8rpx;
					width: 32rpx;
					height: 32rpx;
					background: #ff4757;
					border-radius: 50%;
					display: flex;
					align-items: center;
					justify-content: center;
					
					.delete-icon{
						color: #fff;
						font-size: 20rpx;
						font-weight: bold;
						line-height: 1;
					}
				}
			}
		}
		.cont{
			width: 644rpx;
			margin: auto;
			margin-top: 24rpx;
		}
		.title{
			input{
				width: 644rpx;
				height: 100rpx;
				font-size: 36rpx;
				border-bottom: 1px dashed #D8D8D8;
				margin: auto;
			}
		}
	}
	page {
		background: #F6F6F6;
		padding-bottom:500rpx;
	}

</style>