<template>
	<view class="container">
		<view class="title">维修日期</view>
		<uni-datetime-picker placeholder="请选择日期" type="date" v-model="repairDate" />
		<view class="title">维修内容</view>
		<view class="textarea">
			<textarea placeholder-style="color:#CCCCCC" placeholder="请输入维修内容" v-model="repairContent"></textarea>
		</view>
		<view class="title">维修结果</view>

		<!-- 录音区域 -->
		<view class="voice">
			<view class="voice_box" v-if="!recordingPath" @click="handleRecording">
				<img src="../../static/images/repairsImg/voice.png" />
			</view>
			<view v-if="!recordingPath" @click="handleRecording">点击录音</view>

			<view class="item_recording" v-if="recordingPath" @click="handlePlayRecording">
				<img :src="recordingImg" />
				{{ recordingTime }}″
			</view>
			<view class="recording_icon" v-if="recordingPath" @click="handleDeleteRecording">×</view>
		</view>

		<!-- 录音弹窗区域 -->
		<uni-popup :safe-area="true" background-color="#fff" ref="popup_recording">
			<view class="popup_recording">
				<recording @getTempFilePath="getTempFilePath" />
			</view>
		</uni-popup>

		<view class="title">关联耗材</view>

		<!-- 每一个耗材盒子区域 -->
		<!-- <view class="detail_box">
			<view class="detail_box_item">
				<view class="item_key">耗材名称</view>
				<view class="item_value">螺丝钉</view>
			</view>
			<view class="detail_box_item">
				<view class="item_key">耗材数量</view>
				<view class="item_value">
					<uni-number-box v-model="count" :min="0" @change="bindChange"></uni-number-box>
				</view>
			</view>
			<view class="detail_box_item">
				<view class="item_key">耗材单价</view>
				<view class="item_value">0.5</view>
			</view>
		</view> -->

		<!-- 每一个耗材盒子区域 -->
		<view class="detail_box" v-for="(item, index) in goodList" :key="index">
			<view class="detail_box_item">
				<view class="item_key">耗材名称</view>
				<view class="item_value">{{ item.name }}</view>
			</view>
			<view class="detail_box_item">
				<view class="item_key">耗材数量</view>
				<view class="item_value">
					<uni-number-box v-model="item.num" :min="0" @change="bindChange($event, index)"></uni-number-box>
				</view>
			</view>
			<view class="detail_box_item">
				<view class="item_key">耗材单价</view>
				<view class="item_value">
					<input type="number" placeholder="请输入耗材单价" v-model="item.price" @blur="handleChangePrice($event, item)" />
				</view>
			</view>
		</view>

		<!-- 添加耗材区域 -->
		<view class="add" @click="handleAdd">
			<text>＋</text>
			添加耗材
		</view>

		<!-- 合计费用区域 -->
		<view class="total">
			<view>合计费用</view>
			<view>{{ countMoney }}元</view>
		</view>

		<view class="title">维修师傅</view>

		<view class="box">
			<img src="../../static/images/repairsImg/people.png" />
			{{ worker }}
		</view>

		<view class="title">手机</view>

		<view class="box">
			<img src="../../static/images/repairsImg/phone2.png" />
			{{ phone }}
		</view>

		<view class="title">现场拍照</view>

		<uni-file-picker
			ref="filePicker"
			limit="3"
			v-model="imgList"
			fileMediatype="image"
			:image-styles="imageStyles"
			mode="grid"
			@select="select"
			@delete="handleDelete"
		></uni-file-picker>

		<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 recording from '../components/recording.vue'
const innerAudioContext = uni.createInnerAudioContext()
export default {
	components: {
		recording
	},
	data() {
		return {
			// 维修日期
			repairDate: '',
			// 维修内容
			repairContent: '',
			// 维修师傅
			worker: '张三',
			// 手机号码
			phone: '13659854589',
			// 耗材列表
			goodList: [],
			count: 6,
			// 显示的图片数据
			imgList: [],
			// 上传的图片数据
			subImgList: [],
			// 图片上传框的样式
			imageStyles: {
				width: 60,
				height: 60,
				border: {
					color: '#ccc',
					width: 1,
					style: 'dashed',
					radius: '9px'
				}
			},
			//画板边长默认是屏幕宽度，正方形画布
			cw: uni.getSystemInfoSync().windowWidth,
			// 录音文件路径
			recordingPath: '',
			// 录音图片地址
			recordingImg: '../../static/images/repairsImg/recording.jpg',
			// 录音时长
			recordingTime: 0,
			// 播放状态
			playStatus: false,
			// 定时器标识
			timer: null
		}
	},
	computed: {
		// 合计费用
		countMoney() {
			let countMoney = 0
			this.goodList.forEach((ele) => {
				countMoney += Number(ele.num) * Number(ele.price)
			})
			if (countMoney) {
				return countMoney
			} else {
				return 0
			}
		}
	},
	mounted() {
		//在ios下静音时播放没有声音，默认为true，改为false就好了。
		uni.setInnerAudioOption({
			obeyMuteSwitch: false
		})
		uni.$on('addConsumable', this.addConsumable)
	},
	methods: {
		// 单价输入框输入回调
		handleChangePrice(e, item) {
			// 验证输入单价格式 只能是数字，小数点最多两位
			const reg = /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/

			if (!reg.test(e.detail.value)) {
				uni.showToast({
					title: '请确定单价为数字，并且只能保留两位小数点',
					icon: 'none'
				})
				item.price = 0
			}
		},
		// 全局自定义事件
		addConsumable(e) {
			// console.log(e)

			// 判断是否存在相同的耗材
			let flag = this.goodList.some((ele) => {
				return ele.name === e.data
			})

			if (!flag) {
				this.goodList.push({
					name: e.data,
					num: 1,
					price: ''
				})
			}
		},
		// 确认提交按钮回调
		handleSub() {
			if (!this.goodList.length) {
				uni.showToast({
					title: '请添加耗材',
					icon: 'none'
				})
				return
			}
			if (this.countMoney <= 0) {
				uni.showToast({
					title: '合计费用不能小于0元',
					icon: 'none'
				})
				return
			}
			uni.showModal({
				title: '提示',
				content: '确认提交吗？',
				success: (res) => {
					if (res.confirm) {
						console.log(this.repairDate)
						console.log(this.repairContent)
						console.log(this.recordingPath)
						console.log(this.goodList)
						console.log(this.countMoney)
						console.log(this.worker)
						console.log(this.phone)
						console.log(this.subImgList)
						uni.showToast({
							title: '提交成功',
							icon: 'success'
						})
						setTimeout(() => {
							uni.reLaunch({
								url: '/pagesRepairs/box/box'
							})
						}, 1500)
					}
				}
			})
		},
		// 耗材数量计数器改变回调
		bindChange(e, index) {
			// console.log(e)
			// console.log(index)
			if (e === 0) {
				this.goodList.splice(index, 1)
			}
		},
		// 添加耗材按钮回调
		handleAdd() {
			uni.navigateTo({
				url: '/pagesRepairs/addGoods/addGoods'
			})
		},
		// 选择图片回调
		select(e) {
			console.log(e)
			e.tempFiles.forEach((item) => {
				//这里的id和页面中写的html代码的canvas的id要一致
				let canvasId = 'zipCanvas'
				//原图的路径
				let imagePath = item.path
				//大小限制1024kb
				let limitSize = 1024
				//初始绘画区域是画布自身的宽度也就是屏幕宽度
				let drawWidth = uni.getSystemInfoSync().windowWidth

				getLessLimitSizeImage(canvasId, imagePath, limitSize, drawWidth, (resPath) => {
					uni.showLoading({
						title: '上传中'
					})
					uni.uploadFile({
						url: `https://jiangxih3cpartner.com/reporting/file/fileUpDown`,
						filePath: resPath,
						name: 'file',
						success: (uploadFileRes) => {
							this.subImgList.push(JSON.parse(uploadFileRes.data).data.join())
							this.imgList.push({
								url: item.path,
								name: ''
							})
							uni.hideLoading()
						},
						fail: () => {
							uni.showToast({
								title: '上传失败',
								icon: 'error'
							})
						}
					})
				})
			})
		},
		// 删除图片回调
		handleDelete(e) {
			// console.log(e);
			const num = this.imgList.findIndex((v) => v.url === e.tempFilePath)
			this.subImgList.splice(num, 1)
			this.imgList.splice(num, 1)
		},
		// 点击录音按钮回调
		handleRecording() {
			uni.getSetting({
				success: (res) => {
					if (!res.authSetting['scope.record']) {
						uni.authorize({
							scope: 'scope.record',
							success(res) {
								// 授权成功
								uni.showToast({
									title: '授权成功',
									icon: 'none'
								})
							},
							fail() {
								uni.showModal({
									content: '检测到您没打开麦克风权限，是否去设置打开？',
									confirmText: '确认',
									cancelText: '取消',
									success: (res) => {
										if (res.confirm) {
											uni.openSetting({
												success: (res) => {}
											})
										} else {
											uni.showToast({
												title: '获取麦克风权限失败',
												icon: 'none'
											})
										}
									}
								})
							}
						})
					} else {
						this.$refs.popup_recording.open('bottom')
					}
				},
				fail() {
					uni.showToast({
						title: '获取麦克风权限失败',
						icon: 'none'
					})
				}
			})
		},
		// 点击录音播放回调
		handlePlayRecording() {
			innerAudioContext.src = this.recordingPath
			if (!this.playStatus) {
				this.playStatus = true
				innerAudioContext.play()

				this.timer = setInterval(() => {
					if (this.recordingImg == '../../static/images/repairsImg/recording.jpg') {
						this.recordingImg = '../../static/images/repairsImg/recording2.jpg'
					} else if (this.recordingImg == '../../static/images/repairsImg/recording2.jpg') {
						this.recordingImg = '../../static/images/repairsImg/recording3.jpg'
					} else if (this.recordingImg == '../../static/images/repairsImg/recording3.jpg') {
						this.recordingImg = '../../static/images/repairsImg/recording.jpg'
					}
				}, 300)

				//播放结束
				innerAudioContext.onEnded(() => {
					clearInterval(this.timer)
					this.timer = null
					this.recordingImg = '../../static/images/repairsImg/recording.jpg'
					this.playStatus = false
				})
			} else {
				clearInterval(this.timer)
				this.recordingImg = '../../static/images/repairsImg/recording.jpg'
				this.playStatus = false
				innerAudioContext.stop()
			}
		},
		// 删除录音回调
		handleDeleteRecording() {
			if (this.playStatus) {
				uni.showToast({
					title: '播放中不能删除',
					icon: 'none',
					mask: true
				})
			} else {
				uni.showModal({
					title: '提示',
					content: '确定删除录音吗？',
					success: (res) => {
						if (res.confirm) {
							this.recordingPath = ''
							this.recordingTime = 0
						}
					}
				})
			}
		},
		// 自定义事件回调,获取录音文件路径
		getTempFilePath(path, time) {
			this.recordingPath = path
			this.recordingTime = time
			this.$refs.popup_recording.close()
		}
	}
}
</script>

<style lang="scss" scoped>
.container {
	box-sizing: border-box;
	padding: 0 30rpx;
	width: 100%;
	height: 100vh;
	overflow-y: auto;

	.title {
		display: flex;
		align-items: center;
		height: 107rpx;
		font-size: 36rpx;
		font-weight: bold;
	}

	.textarea {
		height: 310rpx;
		border-radius: 10rpx;
		border: 1rpx solid #cccccc;

		textarea {
			box-sizing: border-box;
			padding: 25rpx 35rpx;
			width: 100%;
			font-size: 32rpx;
		}
	}

	.voice {
		display: flex;
		align-items: center;
		height: 94rpx;
		font-size: 32rpx;
		color: #cccccc;
		border-radius: 10rpx;
		border: 1rpx solid #cccccc;

		.voice_box {
			display: flex;
			justify-content: center;
			align-items: center;
			margin: 0 38rpx 0 33rpx;
			width: 101rpx;
			height: 47rpx;
			border-radius: 33rpx;
			box-shadow: 0px 0px 4rpx rgba(0, 0, 0, 0.25);

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

		.item_recording {
			margin-left: 35rpx;
			display: flex;
			align-items: center;
			width: 230rpx;
			height: 65rpx;
			color: #000;
			border-radius: 100rpx;
			border: 1rpx solid #cccccc;

			img {
				margin: 0 12rpx;
				width: 40rpx;
				height: 40rpx;
			}
		}

		.recording_icon {
			margin-left: auto;
			margin-right: 35rpx;
			font-size: 40rpx;
		}
	}

	.popup_recording {
		width: 100%;
		height: 460rpx;
		background-color: #fff;
	}

	.detail_box {
		box-sizing: border-box;
		margin-bottom: 46rpx;
		padding: 5rpx 30rpx 0;
		width: 690rpx;
		height: 284rpx;
		border-radius: 9rpx;
		box-shadow: 0px 0px 4px rgba(0, 0, 0, 0.25);

		.detail_box_item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			height: 92rpx;
			font-size: 32rpx;
			border-bottom: 1rpx solid #e5e5e5;

			.item_key {
				width: 150rpx;
				color: #808080;
			}

			.item_value {
				font-weight: bold;

				input {
					text-align: right;
				}
			}
		}
	}

	.add {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 690rpx;
		height: 90rpx;
		color: #6fb6b8;
		font-size: 32rpx;
		border-radius: 9rpx;
		background-color: #ebf2f2;

		text {
			margin-right: 10rpx;
			font-size: 48rpx;
		}
	}

	.total {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin: auto;
		width: 622rpx;
		height: 100rpx;
		font-size: 32rpx;
		font-weight: bold;
		border-bottom: 1rpx solid #e5e5e5;
	}

	.box {
		display: flex;
		align-items: center;
		height: 94rpx;
		font-size: 32rpx;
		border-radius: 10rpx;
		border: 1rpx solid #cccccc;

		img {
			margin: 0 14rpx 0 30rpx;
			width: 40rpx;
			height: 40rpx;
		}
	}

	.btn {
		display: flex;
		justify-content: center;
		align-items: center;
		margin: 65rpx 0 60rpx;
		height: 100rpx;
		color: #fff;
		font-size: 32rpx;
		border-radius: 12rpx;
		background-color: #6fb6b8;
	}
}
</style>
