<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="content">
			<!-- 问题分类选择 -->
			<view class="category-section">
				<view class="category-grid">
					<view 
						v-for="(category, index) in categories" 
						:key="index"
						class="category-item"
						:class="{ 'active': selectedCategory == index }"
						@click="selectCategory(index)">
						<view class="category-icon">
							<image class="icon" :src="category.icon" mode=""></image>
						</view>
						<text class="category-text">{{ category.name }}</text>
					</view>
				</view>
			</view>
			<!-- 问题描述 -->
			<view class="description-section">
				<text class="section-title">请描述具体问题</text>
				<textarea 
					v-model="problemDescription"
					class="description-textarea"
					placeholder="尽量详细描述您遇到的问题和现象、具体位置及表现形式等"
					maxlength="1000"
					@input="onDescriptionInput"
				></textarea>
				<text class="char-count">{{ descriptionLength }}/1000</text>
			</view>
			<!-- 图片补充 -->
			<view class="image-section">
				<text class="section-title">图片补充: <text class="hint">(相关图或录屏能快速解决问题)</text></text>
				<view class="media-grid">
					<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)">
							<!-- <cover-view class="play-icon" @click.stop="previewMedia(index)">▶</cover-view> -->
						</video>
						<!-- 删除按钮 -->
						<view class="delete-btn" @click="deleteMedia(index)">
							<text class="delete-icon">×</text>
						</view>
					</view>
					<view class="upload-btn" @click="btnsc" v-if="mediaList.length < 9">
						<image class="sc" src="https://api.ccttiot.com/smartmeter/img/static/u3z28zohbXoJ5kWcR6X1" mode=""></image>
					</view>
				</view>
			</view>
			<!-- 联系方式 -->
			<view class="contact-section">
				<text class="section-title">联系方式: <text class="required">(必填)</text></text>
				<input 
					v-model="contactInfo"
					class="contact-input"
					placeholder="手机号/邮箱/QQ/微信号,方便我们与您联系"
				/>
			</view>
		</view>
		<view class="" style="width: 100%;height: 86rpx;background-color: #F6F6F6;"></view>
		<!-- 提交按钮 -->
		<view class="submit-section">
			<view class="submit-btn" @click="submitFeedback">提交</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
                bgc: {
                	backgroundColor: "#fff",
                },
				// 问题分类数据
				categories: [
					{ name: '页面闪退', icon: 'https://api.ccttiot.com/smartmeter/img/static/uCZ2dcjDqtIAVZWgNCvn' },
					{ name: '操作体验', icon: 'https://api.ccttiot.com/smartmeter/img/static/uGbK1qzBx2eoJs3Whvqv' },
					{ name: '账号问题', icon: 'https://api.ccttiot.com/smartmeter/img/static/uuF3bCqzqO5ifMGcjC21' },
					{ name: '平台帖子', icon: 'https://api.ccttiot.com/smartmeter/img/static/u35iPJBXonm3jkHztxq6' },
					{ name: '吐槽', icon: 'https://api.ccttiot.com/smartmeter/img/static/uUfgRTkGCD07tAg0n7hn' },
					{ name: '其他反馈', icon: 'https://api.ccttiot.com/smartmeter/img/static/uWsN7D9O89cVibjD6x0q' }
				],
				selectedCategory: 0, // 默认选中第一个
				problemDescription: '',
				descriptionLength: 0,
				uploadedImage: '',
				contactInfo: '',
				mediaList: [], // 媒体文件列表
				token: '' // 七牛云上传token
			}
		},
		computed: {
			canSubmit() {
				return this.contactInfo.trim() !== ''
			}
		},
		onLoad() {
            this.getqiniuyun()
		},
		methods: {
			// 获取七牛云上传token
			getqiniuyun(){
				this.$u.get("/common/qiniuToken").then((res) => {
					if (res.code == 200) {
						this.token = res.data
					}
				})
			},
			// 选择问题分类
			selectCategory(index) {
				this.selectedCategory = index
			},
			// 问题描述输入
			onDescriptionInput(e) {
				this.descriptionLength = e.detail.value.length
			},
			// 点击上传媒体文件
			btnsc(){
				if(this.mediaList.length >= 9){
					return uni.showToast({ title: '最多选择九张图片或视频', icon: 'none',duration:3000 })
				}
				let _this = this
				uni.chooseMessageFile({
					count: 9,
					type: 'all',
					success(res) {
						const tempFilePaths = res.tempFiles
						tempFilePaths.forEach(file => {
							wx.uploadFile({
								url: 'https://up-z2.qiniup.com',
								name: 'file',
								filePath: file.path, //文件路径
								formData: {
									token: _this.token, //后端返回的token
									key: _this.getUploadFileName(file.path) //传的文件名称
								},
								success: function(res) {
									let str = JSON.parse(res.data)
									let fileUrl = 'https://api.ccttiot.com/' + str.key
									// 根据文件后缀名判断类型
									let fileType = _this.getFileType(file.path)
									// 添加到媒体列表
									_this.mediaList.push({
										url: fileUrl,
										type: fileType,
										poster: fileType === 'video' ? null : null // 视频不设置poster，避免加载失败
									})
								}
							})
						})
					}
				})
			},
			// 获取上传的文件名
			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)
						}
					}
				})
			},
			// 提交反馈
			submitFeedback() {
				if (!this.canSubmit) {
					uni.showToast({
						title: '请填写联系方式',
						icon: 'none',
						duration:3000
					})
					return
				}
				// 构建提交数据
				const imageUrls = this.mediaList.map(item => item.url).join(',')
				const data = {
					// category: this.categories[this.selectedCategory].name,
					content: this.problemDescription,
					image: imageUrls,
					contact: this.contactInfo,
					// timestamp: new Date().getTime(),
					type:Number(this.selectedCategory) + 1
				}
				this.$u.post(`/app/complaint/add`,data).then(res =>{
					if(res.code == 200){
					    uni.showToast({
					    	title: '提交成功',
					    	icon: 'success',
					    	duration:3000
					    })
					    setTimeout(() => {
					    	uni.navigateBack()
					    }, 1500)
					}else if(res.code == 401){
						uni.reLaunch({
							url:'/pages/login/login'
						})
					} else{
						uni.showToast({
							title: res.msg,
							icon: 'none',
							duration:3000
						})
					}
				})
			}
		}
	}
</script>

<style lang="scss">
	::v-deep .u-icon__icon,
	::v-deep .u-title{
		padding-bottom: 22rpx !important;
	}
	.page {
		background: #fff;
		min-height: 100vh;
		padding-bottom: 200rpx;
	}
	.content {
		padding: 40rpx 30rpx;
	}
	// 问题分类选择区域
	.category-section {
		margin-bottom: 60rpx;
		.category-grid {
			display: grid;
			grid-template-columns: repeat(3, 1fr);
			gap: 20rpx; 
			.category-item {
				display: flex;
				flex-direction: column;
				align-items: center;
				padding: 30rpx 20rpx;
				border: 2rpx solid #E5E5E5;
				border-radius: 12rpx;
				background: #F8F8F8;
				transition: all 0.3s ease;
				&.active {
					background: #E2FFF5 !important;
					border: 2rpx solid #1EC28B !important;
					.category-icon {
						.icon {
							color: #3D3D3D;
						}
					}
					.category-text {
						color: #3D3D3D;
						font-weight: 600;
					}
				}
				.category-icon {
					margin-bottom: 16rpx;
					
					.icon {
						font-size: 48rpx;
						color: #666;
						width: 52rpx;
						height: 52rpx;
					}
				}
				
				.category-text {
					font-size: 24rpx;
					color: #333;
					text-align: center;
					line-height: 1.2;
				}
			}
		}
	}
	
	// 问题描述区域
	.description-section {
		margin-bottom: 60rpx;
		position: relative;
		
		.section-title {
			font-size: 32rpx;
			color: #333;
			font-weight: 600;
			margin-bottom: 24rpx;
			display: block;
		}
		
		.description-textarea {
			width: 100%;
			height: 230rpx;
			padding: 24rpx;
			border: 2rpx solid #E5E5E5;
			border-radius: 12rpx;
			background: #fff;
			font-size: 28rpx;
			color: #333;
			line-height: 1.5;
			box-sizing: border-box;
			
			&::placeholder {
				color: #999;
			}
		}
		
		.char-count {
			position: absolute;
			bottom: 16rpx;
			right: 24rpx;
			font-size: 24rpx;
			color: #999;
		}
	}
	
	// 图片上传区域
	.image-section {
		margin-bottom: 60rpx;
		
		.media-grid {
			display: flex;
			flex-wrap: wrap;
			gap: 20rpx;
		}
		
		.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;
				}
			}
		}
		.section-title {
			font-size: 32rpx;
			color: #333;
			font-weight: 600;
			margin-bottom: 24rpx;
			display: block;
			.hint {
				font-size: 24rpx;
				color: #999;
				font-weight: normal;
			}
		}
		.upload-btn {
			width: 180rpx;
			height: 180rpx;
			border: 2rpx dashed #E5E5E5;
			border-radius: 20rpx;
			background: #FAFAFA;
			display: flex;
			align-items: center;
			justify-content: center;
			.sc {
				width: 180rpx;
				height: 180rpx;
			}
		}
		.image-upload {
			width: 200rpx;
			height: 200rpx;
			border: 2rpx dashed #E5E5E5;
			border-radius: 12rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			background: #FAFAFA;
			.upload-placeholder {
				display: flex;
				align-items: center;
				justify-content: center;
				.plus-icon {
					font-size: 80rpx;
					color: #CCC;
					font-weight: 300;
				}
			}
			.uploaded-image {
				width: 100%;
				height: 100%;
				border-radius: 10rpx;
			}
		}
	}
	// 联系方式区域
	.contact-section {
		margin-bottom: 80rpx;
		.section-title {
			font-size: 32rpx;
			color: #333;
			font-weight: 600;
			margin-bottom: 24rpx;
			display: block;
			.required {
				font-size: 24rpx;
				font-weight: normal;
			}
		}
		.contact-input {
			width: 100%;
			height: 88rpx;
			padding: 0 24rpx;
			border: 2rpx solid #E5E5E5;
			border-radius: 12rpx;
			background: #fff;
			font-size: 28rpx;
			color: #333;
			box-sizing: border-box;
			&::placeholder {
				color: #999;
			}
		}
	}
	// 提交按钮区域
	.submit-section {
		width: 750rpx;
		height: 152rpx;
		background: #FFFFFF;
		border-radius: 0rpx 0rpx 0rpx 0rpx;
		position: fixed;
		left: 0;
		bottom: 0;
		.submit-btn {
			width: 670rpx;
			height: 86rpx;
			margin: auto;
			margin-top: 34rpx;
			background-color: #1EC28B;
			border-radius: 43rpx 43rpx 43rpx 43rpx;
			font-weight: 500;
			font-size: 36rpx;
			color: #FFFFFF;
			text-align: center;
			line-height: 86rpx;
		}
	}
</style>