<template>
	<view class="jinji">
		<view class="text-center" style="padding-top: 80rpx;font-weight: bold;font-size: 40rpx;color: #222222;">
			<view class="datt">严重危害生命财产安全 </view>
			<view class="datt margin-top-sm">求助专属通道</view>
			<view style="margin-top: 28rpx;font-size: 28rpx;">平台将为您，保留录音证据，实时位置，通知平台联系人</view>
		</view>

		<!-- <view style="background: #fff;width: 200rpx;text-align: center;margin: 30rpx auto;padding: 20rpx 0;"
			@touchstart.stop.prevent="voiceBegin" @touchmove.stop.prevent="voiceIng" @touchend.stop.prevent="voiceEnd"
			@touchcancel.stop.prevent="voiceCancel">开始录音</view> -->

		<view class="text-center" style="margin-top: 152rpx;" v-if="checkLuYin != '否'" @touchstart.stop.prevent="voiceBegin"
			@touchmove.stop.prevent="voiceIng" @touchend.stop.prevent="voiceEnd"
			@touchcancel.stop.prevent="voiceCancel">
			<image src="/static/images/index/yuyin.png" style="width: 252rpx;height: 252rpx;pointer-events: none;"></image>
		</view>
		<view class="text-center" style="margin-top: 120rpx;" v-if="checkLuYin === '否'" @tap="setChatSave">
			<image src="/static/images/index/yuyin.png" style="width: 252rpx;height: 252rpx;pointer-events: none;"></image>
		</view>

		<!-- 录音UI效果 -->
		<view class="record" :class="recording?'':'hidden'">
			<view class="ing" :class="willStop?'hidden':''">
				<view class="icon luyin2"></view>
			</view>
			<view class="cancel" :class="willStop?'':'hidden'">
				<view class="icon chehui"></view>
			</view>
			<view class="tis" :class="willStop?'change':''">{{recordTis}}</view>
		</view>

		<view class="text-center" style="margin-top:238rpx;" @touchstart.stop.prevent="voiceBegin" v-if="checkLuYin != '否'"
			@touchmove.stop.prevent="voiceIng" @touchend.stop.prevent="voiceEnd"
			@touchcancel.stop.prevent="voiceCancel">
			<image src="/static/images/index/sos.png" style="width: 200rpx;height: 200rpx;pointer-events: none;"></image>
		</view>
		
		<view class="text-center" style="margin-top:238rpx;" v-if="checkLuYin === '否'" @tap="setChatSave">
			<image src="/static/images/index/sos.png" style="width: 200rpx;height: 200rpx;pointer-events: none;"></image>
		</view>
	</view>
</template>

<script>
	import configdata from '@/common/config.js';
	var innerAudioContext; //播放
	// #ifdef H5
	var recorder; // 定义一个MediaRecorder对象
	var stream; //定义一个音频流的对象
	var chunks = []; // 定义一个用于存储音频数据片段的数组
	// #endif

	export default {
		data() {
			return {
				checkLuYin: this.$queue.getData('checkLuYin'),
				latitude: '',
				longitude: '',
				content: '',
				//录音相关参数

				//H5不能录音
				RECORDER: uni.getRecorderManager(),

				isVoice: false,
				voiceTis: '按住 说话',
				recordTis: "手指上滑 取消发送",
				recording: false,
				willStop: false,
				initPoint: {
					identifier: 0,
					Y: 0
				},
				recordTimer: null,
				recordLength: 0,

				//播放语音相关参数
				AUDIO: uni.createInnerAudioContext(),
				playMsgid: null,
				VoiceTimer: null,
				blobData: '',
				voicePaths: '',
				voicePath: '',
			}
		},
		onLoad: function(option) {
			// #ifndef H5
			//录音开始事件
			this.RECORDER.onStart((e) => {
				this.recordBegin(e);
			})
			//录音结束事件
			this.RECORDER.onStop((e) => {
				this.recordEnd(e);
			})
			// #endif
			let that = this;
			uni.getLocation({
				type: 'wgs84',
				success: function(res) {
					console.log('当前位置的经度：' + res.longitude);
					console.log('当前位置的纬度：' + res.latitude);
					that.latitude = res.latitude
					that.longitude = res.longitude
				}
			});
		},
		onBackPress() {
			this.AUDIO.stop();
		},
		onHide() {
			this.AUDIO.stop();
		},
		mounted() {
			innerAudioContext = uni.createInnerAudioContext(); //播放
			let _this = this;

			// #ifndef H5
			//录音停止事件
			// recorderManager.onStop(function(res) {
			// 	console.log('recorder stop' + res.tempFilePath);
			// 	// _this.recordEnd(res);
			// 	_this.voicePath = res.tempFilePath;
			// });
			// #endif

		},
		beforeDestroy() {
			innerAudioContext.destroy();
			// var recorder; // 定义一个MediaRecorder对象
			// chunks = [];
		},
		methods: {
			// 切换语音/文字输入
			switchVoice() {
				this.isVoice = this.isVoice ? false : true;
			},
			setChatSave() {
				let userId = this.$queue.getData('userId');
				let userName = this.$queue.getData('nickName');
				let data = {
					image: this.content,
					state: 9,
					typeId: this.longitude,
					typeName: this.latitude,
					userId: userId,
					userName: userName
				}
				this.$Request.postJson('/app/message/insertMessage', data).then(
					res => {
						if (res.code == 0) {
							this.$queue.showToast('求助成功！');
						} else {
							this.$queue.showToast(res.msg);
						}
					});
			},
			// 录音开始
			voiceBegin(e) {

				// #ifdef H5
				if (stream) {
					stream.getTracks().forEach((track) => track.stop())
					stream = null
				}
				if (recorder) {
					recorder = null
				}
				this.recordLength = 0
				this.voicePaths = '';
				this.voicePath = '';
				this.startRecord()
				// #endif

				if (e.touches.length > 1) {
					return;
				}
				this.initPoint.Y = e.touches[0].clientY;
				this.initPoint.identifier = e.touches[0].identifier;
				// #ifndef H5
				this.RECORDER.start({
					format: "mp3"
				}); //录音开始,
				// #endif

			},
			//开始录音
			startRecord: async function() {
				
				let _this = this
				// 获取麦克风音频数据流
				stream = await navigator.mediaDevices.getUserMedia({
					audio: true
				})


				// 初始化MediaRecorder对象
				recorder = new MediaRecorder(stream);
				console.log('asdsad___' + recorder)
				// alert('asdsad___' + recorder)
				// 将 stream 转成 blob 来存放
				recorder.ondataavailable = (blobEvent) => {
					chunks.push(blobEvent.data);
				}
				// 停止时生成预览的 blob url
				recorder.onstop = () => {
					const blob = new Blob(chunks, {
						type: 'audio/mp3'
					})
					// const mediaUrl = URL.createObjectURL(blob);
					_this.voicePaths = blob;
					_this.blobData = blob;
					// that.voicePath = mediaUrl;
					// const newbold = new File([recordPath]),{type:'audio/mp3'}
					// alert(that.voicePaths,URL.createObjectURL(blob))

				}
				recorder.start();
				_this.recordBegin()
			},
			//录音开始UI效果
			recordBegin(e) {
				this.recording = true;
				this.voiceTis = '松开 结束';
				this.recordLength = 0;
				this.recordTimer = setInterval(() => {
					this.recordLength++;
				}, 1000)
			},
			// 录音被打断
			voiceCancel() {
				this.recording = false;
				this.voiceTis = '按住 说话';
				this.recordTis = '手指上滑 取消发送'
				this.willStop = true; //不发送录音
				this.RECORDER.stop(); //录音结束
			},
			// 录音中(判断是否触发上滑取消发送)
			voiceIng(e) {

				// // #ifdef H5
				// this.startRecord()
				// // #endif

				if (!this.recording) {
					return;
				}
				let touche = e.touches[0];
				//上滑一个导航栏的高度触发上滑取消发送
				if (this.initPoint.Y - touche.clientY >= uni.upx2px(100)) {
					this.willStop = true;
					this.recordTis = '松开手指 取消发送'
				} else {
					this.willStop = false;
					this.recordTis = '手指上滑 取消发送'
				}

			},
			// 结束录音
			voiceEnd(e) {

				if (!this.recording) {
					return;
				}
				this.recording = false;
				this.voiceTis = '按住 说话';
				this.recordTis = '手指上滑 取消发送'

				//原生录音停止
				// #ifdef H5
				//停止录音

				if (recorder.state != "inactive") {
					recorder.stop();
				}
				//把音频流也停止掉
				stream.getTracks().forEach((track) => track.stop())
				

				this.uplodMp3(this.voicePaths);
				// #endif
				// #ifndef H5
				this.RECORDER.stop(); //录音结束
				// #endif

			},
			//录音结束(回调文件)
			recordEnd(e) {
				let that = this
				clearInterval(this.recordTimer);
				if (!this.willStop) {
					this.$queue.showLoading('发送中...')
					console.log("e: " + JSON.stringify(e));
					let msg = {
						length: 0,
						url: e.tempFilePath
					}
					let min = parseInt(this.recordLength / 60);
					let sec = this.recordLength % 60;
					min = min < 10 ? '0' + min : min;
					sec = sec < 10 ? '0' + sec : sec;
					if (this.recordLength % 60 > 1) {
						msg.length = min + ':' + sec;
						console.log('msg.length___:' + msg.length)
						uni.uploadFile({ // 上传接口
							url: that.config("APIHOST1") + '/alioss/upload', //真实的接口地址
							filePath: e.tempFilePath,
							name: 'file',
							success: (uploadFileRes) => {
								uni.hideLoading();
								this.content = JSON.parse(uploadFileRes.data).data;
								console.log("语音：" + this.content)

								this.setChatSave();
								uni.hideLoading();
							}
						});
					} else {
						this.$queue.showToast('语音要大于一秒才可以发送！')
					}
				} else {
					console.log('取消发送录音');
				}
				this.willStop = false;
			},
			//上传mp3格式的音频
			uplodMp3(recordPath) {
				let _this = this;
				// var newbold = new File([recordPath],{type:'audio/mp3'})

				clearInterval(_this.recordTimer);
				if (!_this.willStop) {
					// that.$queue.showLoading('发送中...')
					uni.showLoading({
						title: '录音上传中...'
					})
					let msg = {
						length: 0,
						url: recordPath
					}
					let min = parseInt(_this.recordLength / 60);
					let sec = _this.recordLength % 60;
					min = min < 10 ? '0' + min : min;
					sec = sec < 10 ? '0' + sec : sec;
					if (_this.recordLength % 60 > 1) {
						msg.length = min + ':' + sec;
						// console.log('msg.length___:' + msg.length)
						setTimeout(function() {
							uni.uploadFile({ // 上传接口
								url: _this.config("APIHOST1") + '/alioss/upload', //真实的接口地址
								file: _this.blobData,
								// file: recordPath,
								name: 'file',
								success: (uploadFileRes) => {
									console.error('uploadFileRes------' + uploadFileRes)
									uni.hideLoading();
									_this.content = JSON.parse(uploadFileRes.data).data;
									// console.log("语音：" + that.content)
									_this.setChatSave();
									uni.hideLoading();
								}
							});
						}, 1000)
					} else {
						_this.$queue.showToast('语音要大于一秒才可以发送！')
					}
				} else {
					console.log('取消发送录音');
				}
				_this.willStop = false;
			},
			config: function(name) {
				var info = null;
				if (name) {
					var name2 = name.split("."); //字符分割
					if (name2.length > 1) {
						info = configdata[name2[0]][name2[1]] || null;
					} else {
						info = configdata[name] || null;
					}
					if (info == null) {
						let web_config = cache.get("web_config");
						if (web_config) {
							if (name2.length > 1) {
								info = web_config[name2[0]][name2[1]] || null;
							} else {
								info = web_config[name] || null;
							}
						}
					}
				}
				return info;
			},
		}
	}
</script>

<style lang="scss">
	@import "./css/style.scss";

	.jinji {
		height: 100vh;
		background: linear-gradient( 180deg, #90FFD6 0%, #E6FFF6 28%, #FFFFFF 47%, #E5FFF5 100%);
	}
	
</style>