<template>
	<view class="content">
		<view class="topbar" v-show="isIphone || isWeiXin">
		</view>
		<!-- #ifdef MP-WEIXIN -->
		<view class="topbar">
		</view>
		<!-- #endif -->
		<view class="status_bar">
			<view class="left" @click="goList">上报记录</view>
			<span style="font-size: 36rpx;">隐患上报</span>
			<view class="right"></view>
		</view>
		<view class="mainCont">
			<u-cell-group style="margin-bottom: 10px">
				<u-cell-item :arrow="false" :value-style="{textAlign: 'left',paddingLeft: '10px'}">
					<view slot="title"><span class="red"></span>所在位置：</view>
					<u-input placeholder="请填写详细位置" v-model="form.local" type="text" />
				</u-cell-item>
			</u-cell-group>
			<view class="card" style="width: 100%;border-radius: none;">
				<view class="top">
					<span style="color: #5976BA" @click="type = 'audio'" v-show="type == 'text'">
						<u-icon name="mic"></u-icon>切换语音录入
					</span>
					<span style="color: #5976BA" @click="type = 'text'" v-show="type == 'audio'">
						<u-icon name="edit-pen"></u-icon>切换文字输入
					</span>
				</view>
				<view class="bottom">
					<u-input v-show="type == 'text'" v-model="mstext" placeholder="请输入详情描述..." :height="300"
						type="textarea" />
					<view class="imgupload">
						<u-upload :show-progress="false" ref="upload" @on-remove="uploadRemove" @on-success="uploadSuccess"
							:header="uploadHeader" max-count="3" width="80px" height="80px" :custom-btn="true"
							:action="action" :file-list="fileList">
							<view slot="addBtn" class="slot-btn">
								<image style="width: 80px;height: 80px" src="/static/tjzp.png" alt="">
							</view>
						</u-upload>
					</view>
					<view class="audioBox" v-show="type == 'audio'">
						<view class="left">
							<view class="imgBox">
								<image style="width: 36px;height: 36px" src="/static/sj.png"
									v-show="audioType == '3' && !playIng" alt="" @click="playAudio">
								<image style="width: 36px;height: 36px" src="/static/bf.gif"
									v-show="audioType == '3' && playIng" alt="">
								<p v-show="audioType == '3'">我的录音</p>
							</view>
						</view>
						<view class="middle">
							<view class="outBox" v-show="audioType == '2'">
								<image style="width: 100%;height: 80px" src="/static/lyzb.gif" alt="">
								<p style="color: #CCCCCC;text-align: center;margin-top: -20px">录音中，松开结束录音</p>
							</view>
							<view class="imgBox" @click="submitAudio" @touchstart="toAudio" @touchend="audioEnd">
								<image style="margin-top: 15px;width: 33px;height: 45px" src="/static/ht.png" alt=""
									v-show="audioType == '1'">
								<image style="width: 80px;height: 80px" src="/static/lyz.gif" alt=""
									v-show="audioType == '2'">
								<image style="margin-top: 25px;width: 44px;height: 30px" src="/static/dh.png" alt=""
									v-show="audioType == '3'">
							</view>
							<p v-show="audioType == '1'">长按录音</p>
							<p v-show="audioType == '2'">录音中</p>
							<p v-show="audioType == '3'">提交</p>
						</view>
						<view class="right">
							<view class="imgBox">
								<image style="width: 24px;height: 33px" @click="reShow = true" src="/static/ht2.png"
									v-show="audioType == '3'" alt="">
								<p v-show="audioType == '3'">重新录音</p>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="bottomButton" @click="submitData" v-show="type == 'text'">
			<view>提交</view>
		</view>
		<u-modal v-model="reShow" @confirm="audioType = '1'" :show-cancel-button="true" content="请确认是否重录"></u-modal>
		<u-toast ref="uToast" />
	</view>

</template>

<script>
	const recorderManager = uni.getRecorderManager();
	// const UPL = require('@/utils/upload')
	const NET = require('@/utils/request')
	const API = require('@/config/api')
	export default {
		data() {
			return {
				isIphone: false,
				isWeiXin: false,
				audioType: '1',
				type: 'text',
				mstext: "",
				reShow: false,
				form: {
					local: "",
				},
				action: API.uploadFile,
				fileList: [],
				imgList: [],
				uploadHeader: {
					Authorization: 'Bearer ' + uni.getStorageSync('token')
				},
				// recorderManager: null,
				innerAudioContext: null,
				voicePath: '',
				soundPath: '',
				soundFile: null,
				playIng: false,
				recordTime: 0,
				recordDo: null
			}
		},
		onLoad(options) {
			// if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
			// 	this.isIphone = true;
			// }
			uni.getSystemInfo({
				success: (res) => {
					console.log(res)
					if (res.model == 'iPhone') {
						this.isIphone = true;
					}
				},
				fail: (err) => {
					console.log(err)
				}
			})
			let self = this;
			this.innerAudioContext = uni.createInnerAudioContext();
			// this.recorderManager = uni.getRecorderManager();
			recorderManager.onStop(function(res) {
				console.log(res)
				self.voicePath = res.tempFilePath;
			});
		},
		onReady() {
			if (this.isIphone) {
				document.getElementsByClassName('mainCont')[0].style.height = document.getElementsByClassName('mainCont')[
					0].clientHeight - 25 + 'px'
			}
		},
		methods: {
			goList() {
				uni.navigateTo({
					url: "/report/list"
				})
			},
			test() {
				uni.navigateTo({
					url: "/wasteCheck/list"
				})
			},
			uploadSuccess(data, index) {
				console.log(data, index)
				if (data.code == 200) {
					data.data[0].fileType = 2
					this.imgList.push(data.data[0])
					this.$refs.uToast.show({
						title: '上传成功',
						type: 'success',
					})
				} else {
					this.$refs.upload.remove(index)
					this.$refs.uToast.show({
						title: data.msg,
						type: 'warning',
					})
				}
			},
			uploadRemove(index) {
				console.log(index);
				this.imgList.splice(index, 1)
			},
			toAudio() {
				if (this.recordDo) {
					clearInterval(this.recordDo)
					this.recordDo = false
					this.recordTime = 0
				}
				this.recordDo = setInterval(() => {
					this.recordTime = this.recordTime + 1
				}, 1000)
				if (this.audioType == '1') {
					try {
						EbeiPlugins.startAudioRecord((res) => {
							// alert(res)
							// alert('成功')
							this.audioType = '2'
						}, (err) => {
							// alert('失败')
							// alert(err)
							this.$refs.uToast.show({
								title: '调取录音功能失败，请开启对应权限',
								type: 'warning',
							})
						})
					} catch {
						this.audioType = '2'
						recorderManager.start({
							format: 'mp3'
						});
					}
					// recorderManager.start();
				} else {}
			},
			audioEnd() {
				if (this.recordDo) {
					clearInterval(this.recordDo)
					this.recordDo = null
					console.log(this.recordTime)
					if (this.recordTime < 3) {
						this.$refs.uToast.show({
							title: '录音时间过短，请重新录制',
							type: 'warning',
						})
						this.audioType = '1'
						return false
					} else {
						this.recordTime = 0
					}
				}
				if (this.audioType == '1' || this.audioType == '3') {
					return false
				}
				try {
					EbeiPlugins.stopAudioRecord((res) => {
						// alert(res)
						this.voicePath = res.file
						this.audioType = '3'
						console.log('成功')
						// this.soundPath = res.file
					}, (err) => {
						console.log('失败')
						this.$refs.uToast.show({
							title: '录音失败，请打开录音权限再试',
							type: 'warning',
						})
						// this.audioType = '1'
					})
					// recorderManager.stop()
				} catch {
					recorderManager.stop()
					this.audioType = '3'
					// console.log('调取录音失败')
				}

			},
			playAudio() {
				if (this.isIphone) {
					this.playIng = true
					EbeiPlugins.playAudioRecord(this.voicePath, 1, (res) => {
						this.playIng = false
					}, (err) => {

					})
				} else {
					let innerAudioContext = uni.createInnerAudioContext();
					innerAudioContext.src = this.voicePath;
					innerAudioContext.play();
					this.playIng = true;
					innerAudioContext.onPlay(() => {
						console.log('开始播放');
					});
					innerAudioContext.onError((res) => {
						console.log('播放失败');
						console.log(res);
						console.log(res.errMsg);
						console.log(res.errCode);
					});
					innerAudioContext.onEnded(() => {
						this.playIng = false;
					});
				}
			},
			submitAudio() {
				if (this.audioType == '3') {
					// alert(this.voicePath)
					try {
						EbeiPlugins.uploadAudioRecord(this.voicePath, (re) => {
							NET.request(API.getFilePath, {
								fileId: re.fileId
							}).then(res => {
								this.soundFile = {
									fileId: re.fileId,
									filePath: res.msg,
									fileType: 1
								}
								this.$refs.uToast.show({
									title: '录音保存成功',
									type: 'success',
								})
							}).catch(error => {
								this.$refs.uToast.show({
									title: error.msg,
									type: 'warning',
								})
							})
						})
					} catch {
						console.log(uni.getStorageSync('token'))
						uni.uploadFile({
							url: API.uploadFile,
							filePath: this.voicePath,
							name: 'file',
							header: {
								Authorization: 'Bearer ' + uni.getStorageSync('token')
							},
							success: res => {
								console.log(JSON.parse(res.data))
								let resData = JSON.parse(res.data).data[0]
								this.soundFile = {
									fileId: resData.fileId,
									filePath: resData.filePath,
									fileType: 1
								}
								this.submitData()
								this.$refs.uToast.show({
									title: '录音保存成功',
									type: 'success',
								})
							},
							fail: err => {
								this.$refs.uToast.show({
									title: '录音上传失败',
									type: 'warning',
								})
							},
						})
					}
				}
			},
			submitData() {
				// if (!this.form.local) {
				// 	this.$refs.uToast.show({
				// 		title: '请填写位置',
				// 		type: 'warning',
				// 	})
				// 	return false
				// } else 
				if (!this.mstext && this.type == 'text') {
					this.$refs.uToast.show({
						title: '请填写详情描述',
						type: 'warning',
					})
					return false
				} else if (!this.soundFile && this.type == 'audio') {
					this.$refs.uToast.show({
						title: '未发现录音文件，请录音',
						type: 'warning',
					})
					return false
				}
				let postData = {
					description: this.mstext,
					fileList: this.imgList,
					location: this.form.local,
					sourceType: 1,
					troubleType: this.type == 'text' ? 1 : 2,
					userId: uni.getStorageSync('userId')
				}
				if (this.type == 'audio') {
					postData.fileList.push(this.soundFile)
				}
				NET.request(API.htroubleReport, postData, 'POST').then(res => {
					this.$refs.uToast.show({
						title: res.msg,
						type: 'success',
					})
					uni.navigateTo({
						url: "/report/list"
					})
				}).catch(error => {
					this.$refs.uToast.show({
						title: error.msg,
						type: 'warning',
					})
				})
			}
		}
	}
</script>

<style lang="scss">
	.mainCont {
		height: calc(100% - 80rpx);
		padding: 0px 0 60px 0;
		box-sizing: border-box;
		overflow-y: auto;
	}

	/deep/ .u-cell__value {
		color: #1c1c1c;
	}

	.imgupload {
		margin-bottom: 10px;
		padding: 10px;
		background: #fff;

		.imgbox {
			img {
				width: 80px;
				height: 80px;
				margin: 10px 10px 10px 0;
			}
		}
	}

	.audioBox {
		margin-top: 200px;
		margin-bottom: 50px;
		padding: 0 20px;
		display: flex;
		justify-content: space-between;
		align-items: flex-end;

		.left,
		.right {
			.imgBox {
				width: 65px;
				height: 71px;
				text-align: center;

				p {
					margin-top: 5px;
					text-align: center;
				}
			}
		}

		.middle {
			position: relative;

			.outBox {
				position: absolute;
				top: -140px;
				left: calc(-35vw + 40px);
				width: 70vw;
				height: 80px;
			}

			.imgBox {
				width: 80px;
				height: 80px;
				border-radius: 80px;
				text-align: center;
				background-color: #5976ba;
			}

			p {
				margin-top: 5px;
				text-align: center;
			}
		}

	}
</style>
