<template>
	<view class="container">
		<!-- 标题区域 -->
		<view class="title">
			<view class="title_key">标题</view>
			<view class="title_value">
				<input maxlength="10" type="text" placeholder="请输入标题，不要超过10个字哦~" placeholder-style="color:#B3B3B3;fontSize:28rpx;" v-model="inputValue" />
			</view>
		</view>

		<!-- 评价上传图片视频区域 -->
		<view class="operation">
			<!-- 输入框区域 -->
			<view class="operation_input">
				<textarea
					maxlength="1000"
					class="textarea"
					placeholder-style="color:#B3B3B3;font-size:24rpx"
					placeholder="写出你的相关问题"
					v-model="textareaValue"
					@input="handleInput"
				/>
				<view class="operation_count">（{{ textareaValuelength }}/1000）</view>
			</view>

			<!-- 上传区域 -->
			<view class="operation_uploading">
				<view class="uploading_box" @click="handleUpLoad">
					<img class="img" src="../../static/index/photo.png" />
					<view class="msg">照片/视频</view>
				</view>
				<view class="uploading_box" v-for="(ele, index) in viewImgList" :key="index">
					<img class="img2" mode="aspectFill" v-if="ele.fileType === 'image'" :src="ele.url" @click="handleLook(ele.url, index)" />
					<video
						id="myVideo"
						class="video"
						:show-fullscreen-btn="false"
						:show-play-btn="false"
						v-if="ele.fileType === 'video'"
						:src="ele.url"
						@fullscreenchange="fullscreenchange"
						@click="handleClickVideo('myVideo')"
					></video>
					<view class="icon" @click="handleDelete(index)">
						<img src="../../static/index/close2.png" />
					</view>
				</view>
			</view>
		</view>

		<!-- 提交按钮区域 -->
		<view class="btn" @click="handleSub">提交</view>

		<!-- 用于图片压缩的canvas画布 -->
		<canvas
			:style="{
				width: cw + 'px',
				height: cw + 'px',
				position: 'absolute',
				zIndex: -1,
				left: '-10000rpx',
				top: '-10000rpx'
			}"
			canvas-id="zipCanvas"
		></canvas>
		<!--画布结束-->
	</view>
</template>

<script>
import getLessLimitSizeImage from '../../util/imageCompress.js'
var dayjs = require('dayjs')
export default {
	data() {
		return {
			// 标题输入框绑定数据
			inputValue: '',
			// 评价绑定数据
			textareaValue: '',
			// 评价文字长度
			textareaValuelength: 0,
			// 上传的图片数据
			subImgList: [],
			// 显示的图片数据
			viewImgList: [],
			// 订单id
			bookingId: '',
			// 民宿id
			hotelId: '',
			// 房间id
			houseId: '',
			//画板边长默认是屏幕宽度，正方形画布
			cw: uni.getSystemInfoSync().windowWidth,
			// video 上下文 videoContext 对象
			videoContext: null,
			// 是否是全屏状态
			isFullScreen: false
		}
	},
	onLoad(options) {
		this.bookingId = options.bookingId
		this.hotelId = options.hotelId
		this.houseId = options.houseId
	},
	methods: {
		// 进入全屏和退出全屏时触发的回调
		fullscreenchange(e) {
			this.isFullScreen = e.detail.fullScreen
		},
		// 点击视频控件时触发的回调
		handleClickVideo(id) {
			this.videoContext = uni.createVideoContext(id)
			if (this.isFullScreen) {
				this.videoContext.stop()
				this.videoContext.exitFullScreen()
			} else {
				this.videoContext.requestFullScreen()
				this.videoContext.play()
			}
		},
		// 评价输入框输入回调
		handleInput(e) {
			this.textareaValuelength = e.detail.cursor
		},
		// 上传图片回调
		handleUpLoad() {
			uni.chooseMedia({
				count: 6 - this.subImgList.length,
				mediaType: ['mix'],
				maxDuration: 10,
				success: (res) => {
					// 判断视频文件不能超过1个
					let temList = [...this.viewImgList, ...res.tempFiles]
					let temList2 = temList.filter((ele) => ele.fileType === 'video')
					if (temList2.length > 1) {
						uni.showToast({
							title: '最多只能上传1个视频',
							icon: 'none'
						})
						return
					}

					res.tempFiles.forEach((ele) => {
						if (ele.fileType === 'image' && ele.size > 1024 * 1024 * 3) {
							//这里的id和页面中写的html代码的canvas的id要一致
							let canvasId = 'zipCanvas'
							//原图的路径
							let imagePath = ele.tempFilePath
							//大小限制1024kb
							let limitSize = 1024 * 3
							//初始绘画区域是画布自身的宽度也就是屏幕宽度
							let drawWidth = uni.getSystemInfoSync().windowWidth
							// 图片过大压缩
							getLessLimitSizeImage(canvasId, imagePath, limitSize, drawWidth, (resPath) => {
								this.handleUploadMini({ tempFilePath: resPath, fileType: ele.fileType })
							})
						} else if (ele.fileType === 'video' && ele.size > 1024 * 1024 * 5) {
							// 视频过大压缩
							uni.compressVideo({
								src: ele.tempFilePath,
								quality: 'low',
								// bitrate: 60000,
								// fps: 30,
								// resolution: 1,
								success: (res) => {
									// console.log('压缩后', res)
									this.handleUploadMini({ tempFilePath: res.tempFilePath, fileType: ele.fileType })
								},
								fail: (err) => {
									// console.log(err)
									uni.showToast(
										{
											title: '视频压缩失败',
											icon: 'none'
										},
										2000
									)
								}
							})
						} else {
							this.handleUploadMini(ele)
						}
					})
				},
				fail: (err) => {
					console.log(err)
					uni.showToast({
						title: '选择文件失败',
						icon: 'none',
						mask: true
					})
				}
			})
		},
		handleUploadMini(ele) {
			// console.log(ele)
			// 开始上传
			uni.showLoading({
				title: '上传中'
			})
			uni.uploadFile({
				url: `https://chtech.ncjti.edu.cn/homestay/file/cos/upload`,
				filePath: ele.tempFilePath,
				name: 'files',
				success: (uploadFileRes) => {
					// console.log(JSON.parse(uploadFileRes.data))
					let temRes = JSON.parse(uploadFileRes.data)
					if (temRes.code === 200 || temRes.code === 1) {
						this.subImgList.push(temRes.data)
						// console.log(this.subImgList)
						this.viewImgList.push({
							url: temRes.data,
							fileType: ele.fileType === 'image' ? 'image' : 'video'
						})
						// console.log(this.viewImgList)
					} else {
						uni.showToast({
							title: temRes.message || '上传失败',
							icon: 'none'
						})
					}
					uni.hideLoading()
				},
				fail: () => {
					uni.showToast({
						title: '上传失败',
						icon: 'error'
					})
				}
			})
		},
		// 提交按钮回调
		async handleSub() {
			const reg = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>《》/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？ ]")
			if (!this.inputValue) {
				uni.showToast({
					title: '请输入标题',
					icon: 'none',
					mask: true
				})
				return
			}
			if (reg.test(this.inputValue)) {
				uni.showToast({
					title: '标题不能含有特殊字符和标点符号',
					icon: 'none',
					mask: true
				})
				return
			}
			if (!this.textareaValue) {
				uni.showToast({
					title: '请输入投诉内容',
					icon: 'none',
					mask: true
				})
				return
			}
			let time = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')
			const res = await this.$myRequest({
				url: '/mhotel/complaintorderComplaint.action',
				method: 'post',
				data: {
					bookingId: this.bookingId,
					hotelId: this.hotelId,
					houseId: this.houseId,
					title: this.inputValue,
					content: this.textareaValue,
					createId: uni.getStorageSync('userInfo').id,
					createDate: time,
					modifyDate: time,
					pictureList: this.subImgList
				}
			})
			// console.log(res)
			if (res.code === 200) {
				uni.navigateTo({
					url: `/pages/complaintStatus/complaintStatus?status=1`
				})
			} else {
				uni.navigateTo({
					url: `/pages/complaintStatus/complaintStatus?status=2`
				})
			}
		},
		// 删除图片回调
		handleDelete(index) {
			this.subImgList.splice(index, 1)
			this.viewImgList.splice(index, 1)
		},
		handleLook(url, current) {
			if (this.videoContext) {
				this.videoContext.stop()
			}
			uni.previewImage({
				urls: [url],
				current
			})
		}
	}
}
</script>

<style lang="scss" scoped>
.container {
	display: flex;
	flex-direction: column;
	min-height: 100vh;
	background-color: #f2f3f5;

	.title {
		display: flex;
		align-items: center;
		margin: 20rpx 0;
		padding: 0 20rpx;
		height: 144rpx;
		background-color: #fff;

		.title_key {
			font-size: 28rpx;
			font-weight: bold;
		}

		.title_value {
			display: flex;
			align-items: center;
			box-sizing: border-box;
			padding: 0 26rpx;
			margin-left: 30rpx;
			width: 625rpx;
			height: 80rpx;
			border-radius: 11rpx;
			background-color: #f2f2f2;

			input {
				width: 100%;
			}
		}
	}

	.operation {
		padding: 20rpx 20rpx 33rpx;
		margin-bottom: 20rpx;
		background-color: #fff;

		.operation_input {
			box-sizing: border-box;
			padding: 20rpx;
			width: 710rpx;
			height: 282rpx;
			border-radius: 9rpx;
			background-color: #f2f2f2;

			.textarea {
				width: 100%;
				height: 203rpx;
			}

			.operation_count {
				height: 39rpx;
				text-align: end;
				color: #b3b3b3;
				font-size: 24rpx;
			}
		}

		.operation_uploading {
			display: grid;
			gap: 21rpx;
			grid-template-columns: repeat(auto-fill, 124rpx);
			margin-top: 20rpx;

			::v-deep .uni-file-picker__item {
				background-color: red;
			}

			.uploading_box {
				position: relative;
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				width: 124rpx;
				height: 124rpx;
				border-radius: 7rpx;
				background-color: #f2f2f2;

				.img {
					width: 40rpx;
					height: 40rpx;
				}

				.msg {
					margin-top: 5rpx;
					color: #a6a6a6;
					font-size: 20rpx;
				}

				.img2 {
					width: 124rpx;
					height: 124rpx;
					border-radius: 7rpx;
				}

				.video {
					width: 124rpx;
					height: 124rpx;
					border-radius: 7rpx;
				}

				.icon {
					position: absolute;
					top: 0;
					right: 0;
					display: flex;
					justify-content: center;
					align-items: center;
					width: 30rpx;
					height: 30rpx;
					border-radius: 7rpx;
					background-color: rgba(000, 000, 000, 0.5);

					img {
						width: 30rpx;
						height: 30rpx;
					}
				}
			}
		}
	}

	.btn {
		display: flex;
		justify-content: center;
		align-items: center;
		margin: 368rpx auto 78rpx;
		width: 710rpx;
		height: 96rpx;
		color: #fff;
		font-size: 32rpx;
		border-radius: 64rpx;
		background-color: #096562;
	}
}
</style>