<!-- 语音广播 -->
<template>
	<view class="voiceBroadcast">
		<view class="null-box" @click="backPage()"></view>
		<!-- 语音广播-执行疏散 -->
		<view class="broadcast">
			<view class="broadcast_t">语音广播<label>选择喇叭位置</label></view>
			<!-- 按钮部分 -->
			<view class="trumpet-max-box">
				<view @click="trumpetClick(index)" class="trumpet-for-box"
					:class="item.type?'trumpet-color-a':'trumpet-color-b'" v-for="(item,index) in trumpetList" :key="index">
					<img :src="imagesUrl('commonality/icon_sskz_zc.png')" v-if="!item.type">
					<img :src="imagesUrl('commonality/icon_sskz_xz.png')" v-if="item.type">
					{{item.deviceName}}
				</view>
			</view>
			<!-- #ifdef MP-WEIXIN -->
			<view class="broadcast_m">
				<view class="broadcast_m_t" :class="liveType?'broadcast_m_t_back_a':'broadcast_m_t_back_b'"
					@longpress.stop="recordButton" @touchmove.stop="cancelButton" @touchend.stop="sendButton">
					{{liveType?'松开发送':'按住说话'}}
				</view>
				<view class="broadcast_m_b" v-if="!liveType">按住说话，录入广播内容</view>
				<view class="broadcast_m_b" v-if="liveType">松开发送，向上滑动取消发送</view>
			</view>
			<!-- #endif -->
			<!-- #ifdef WEB -->
			<view class="broadcast_m no-long-press">
				<view class="broadcast_m_t no-long-press"
					:class="liveType?'broadcast_m_t_back_a':'broadcast_m_t_back_b'"
					@touchstart="handleTouchStart"
					@touchmove="handleTouchMove"
					@touchend="handleTouchEnd"
					@touchcancel="handleTouchEnd"
					@contextmenu.prevent="handleContextMenu">
				</view>
				<!-- @longpress.stop="startRecord" @touchmove.stop="delRecord" @touchend.stop="stopRecord" -->
				<view class="broadcast_m_b no-long-press" v-if="!liveType">按住说话，录入广播内容</view>
				<view class="broadcast_m_b no-long-press" v-if="liveType">松开发送，向上滑动取消发送</view>
			</view>
			<!-- #endif -->
		</view>
	</view>
</template>
<script>
	// #ifdef WEB
	import Recorder from 'recorder-core';
	import 'recorder-core/src/engine/mp3';
	import 'recorder-core/src/engine/mp3-engine';
	// #endif
	import {
		iotAppSpeakerFindHorn,
		iotAppSpeakerPlayVoice
	} from '@/pages_manage/api/index.js'
	import {
		config
	} from '@/api/request/config.js'
	export default {
		name: "voiceBroadcast",
		props: {
			subjectData: {},
		},
		data() {
			return {
				baseUrl: config.base_url,
				//喇叭数据
				trumpetList: [],
				//广播相关
				liveType: false,
				sendLock: true, //发送锁，当为true时上锁，false时解锁发送
				recorderManager: uni.getRecorderManager(),
				isEvacuate: true, //疏散按钮控制，当为true时候执行疏散
				//滑动记录
				startPoint: {},
				subId: '',
				floorId: '',
				//H5
				recording: false,
				recorder: null,
				audioBlob: null,
				audioPath: null,
				//H5 拖拽
				touchStartY: 0,
				isLongPress: false,
				hasMoved: false,
				longPressTimer: null,
				moveDirection: null,
				hasTriggeredMethod3: false, // 确保方法3只触发一次
			}
		},
		created() {

		},
		mounted() {
			this.$set(this, 'subId', this.subjectData.subId);
			this.$set(this, 'floorId', this.subjectData.floorId);
			this.iotAppSpeakerFindHorn();
			// #ifdef WEB
			if (this.recorderManager) {
				this.recorderManager.stop();
			}
			// #endif
		},
		methods: {
			// 返回按钮
			backPage() {
				// #ifdef WEB
				this.$parent.$parent.buttonClick('broadcastClose', '');
				// #endif
				// #ifdef MP-WEIXIN
				this.$parent.buttonClick('broadcastClose', '');
				// #endif
			},
			//获取喇叭列表
			async iotAppSpeakerFindHorn() {
				let self = this;
				let obj = {
					subId: self.subId,
					floorId: self.floorId,
				};
				const {
					data
				} = await iotAppSpeakerFindHorn(obj)
				if (data.code == 200) {
					for (let i = 0; i < data.data.length; i++) {
						data.data[i].type = false;
					}
					this.$set(this, 'trumpetList', data.data)
				}
			},
			//点击选择喇叭
			trumpetClick(index) {
				this.trumpetList[index].type = !this.trumpetList[index].type;
			},
			//录制
			recordButton(e) {
				console.log("按下")
				let self = this;
				let num = 0;
				for (let i = 0; i < self.trumpetList.length; i++) {
					if (self.trumpetList[i].type) {
						num++
					}
				}
				if (num == 0) {
					uni.showToast({
						title: '请选择喇叭',
						icon: "none",
						mask: true,
						duration: 2000
					});
					return
				}
				this.liveType = true;
				// console.log('录制', e)
				this.startPoint = e.touches[0]; //记录长按时开始点信息，后面用于计算上划取消时手指滑动的距离。
				const options = {
					duration: 10000,
					sampleRate: 16000,
					numberOfChannels: 1,
					encodeBitRate: 48000,
					format: 'mp3',
					frameSize: 50
				}
				this.recorderManager.start(options); //开始录音
				this.recorderManager.onStart(() => {
					// console.log('recorder start')
				})
				this.recorderManager.onError((res) => {
					// console.log(res);
				})
				uni.showToast({
					title: "正在录音，上划取消发送",
					icon: "none",
					duration: 60000 //先定义个60秒，后面可以手动调用wx.hideToast()隐藏
				});
				this.sendLock = false; //长按时是不上锁的。
			},
			//取消
			cancelButton(e) {
				// console.log("移动")
				let self = this;
				let num = 0;
				for (let i = 0; i < self.trumpetList.length; i++) {
					if (self.trumpetList[i].type) {
						num++
					}
				}
				if (num == 0) {
					return
				}
				// console.log('取消', e)
				let moveLenght = e.touches[e.touches.length - 1].clientY - this.startPoint.clientY; //移动距离
				if (Math.abs(moveLenght) > 50) {
					uni.showToast({
						title: "松开手指,取消发送",
						icon: "none",
						duration: 60000
					});
					this.liveType = false;
					this.sendLock = true; //触发了上滑取消发送，上锁
				} else {
					uni.showToast({
						title: "正在录音，上划取消发送",
						icon: "none",
						duration: 60000
					});
					this.liveType = true;
					this.sendLock = false; //上划距离不足，依然可以发送，不上锁
				}
			},
			//发送
			sendButton(e) {
				// console.log("松开")
				let self = this;
				let num = 0;
				for (let i = 0; i < self.trumpetList.length; i++) {
					if (self.trumpetList[i].type) {

						num++
					}
				}
				if (num == 0) {
					return
				}
				this.liveType = false;
				// console.log('发送', e)
				uni.hideToast(); //结束录音、隐藏Toast提示框
				this.recorderManager.stop(); //结束录音
				this.recorderManager.onStop((res) => {
					if (!this.sendLock) {
						// console.log('1', this.recorderManager)
						// console.log('res.tempFilePath', res.tempFilePath)
						this.uploadImg(res.tempFilePath);
					}
					// console.log('停止录音', res.tempFilePath)
					// console.log("sendLock", this.sendLock);
				})
			},
			//上传MP3
			async uploadImg(tempFilePaths) {
				var self = this;
				uni.uploadFile({
					url: config.base_url + '/system/file/upload', //仅为示例，非真实的接口地址
					header: {
						'Authorization': uni.getStorageSync('token')
					},
					filePath: tempFilePaths,
					name: 'file',
					formData: {
						'user': 'test'
					},
					success: (uploadFileRes) => {
						let res = JSON.parse(uploadFileRes.data);
						if (res.code == 200) {
							// console.log("上传成功", res)
							let url = uni.getStorageSync('fileBrowseEnvironment') + '/' + res.data.url
							self.iotAppSpeakerPlayVoice(url);
						} else {
							uni.showToast({
								title: res.msg,
								icon: "none",
								mask: true,
								duration: 2000
							});
						}
					},
					fail: err => {
						uni.hideLoading()
					},
					complete: () => {}
				});
			},
			//发送语音
			async iotAppSpeakerPlayVoice(text) {
				let self = this;
				let list = [];
				for (let i = 0; i < self.trumpetList.length; i++) {
					if (self.trumpetList[i].type) {
						list.push(self.trumpetList[i].deviceNo)
					}
				}
				let obj = {
					deviceNo: list.join(','),
					voiceUrls: text,
					cycle: 1,
					level: 1000,
				}
				const {
					data
				} = await iotAppSpeakerPlayVoice(obj)
				if (data.code == 200) {
					uni.showToast({
						title: '发送成功',
						icon: "none",
						mask: true,
						duration: 2000
					});
				}
			},
			// #ifdef WEB
			/* H5 */
			async initRecorder() {
				try {
					// 获取麦克风权限
					await navigator.mediaDevices.getUserMedia({ audio: true });
					
					this.recorder = new Recorder({
						type: "mp3", // 输出格式
						bitRate: 64,  // 降低比特率提升兼容性
						// 不指定 sampleRate，让浏览器使用系统默认值（iOS 兼容性要求）
					});
					
					this.recorder.open(() => {
						// 初始化成功，继续 startRecord 流程
						this.startRecord();
					}, (error) => {
						console.error("录音器初始化失败:", error);
						uni.showToast({
							title: '麦克风权限获取失败,请允许麦克风权限',
							icon: "none",
							mask: true,
							duration: 2000
						});
					});
				} catch (err) {
					console.error("获取麦克风失败:", err);
					uni.showToast({
						title: '请允许麦克风权限',
						icon: "none",
						mask: true,
						duration: 2000
					});
				}
			},
			// 开始录音
			async startRecord() {
				let self = this;
				if (!this.recorder) {
					await this.initRecorder();
					// this.startRecord()
					return;
				}
				let num = 0;
				for (let i = 0; i < self.trumpetList.length; i++) {
					if (self.trumpetList[i].type) {
						num++
					}
				}
				if (num == 0) {
					uni.showToast({
						title: '请选择喇叭',
						icon: "none",
						mask: true,
						duration: 2000
					});
					return
				}
				this.recorder.start();
				this.recording = true;
				this.liveType = true;
				uni.showToast({ title: "录音开始", icon: "none" });
			},
			// 停止录音
			stopRecord() {
				if (!this.recorder || !this.recording) return;
				this.recorder.stop((blob, duration) => {
					this.recording = false;
					this.liveType = false;
					this.audioBlob = blob;
					// 生成临时文件路径
					this.audioPath = URL.createObjectURL(blob);
					this.uploadAudio();
				}, (error) => {
					console.error("录音失败:", error);
					uni.showToast({ title: "录音失败", icon: "none" });
				});
			},
			delRecord(){
				this.recorder.stop((blob, duration) => {
					this.recording = false;
					this.liveType = false;
					this.audioBlob = null;
					this.audioPath = null;
				})
			},
			// 上传录音文件
			uploadAudio() {
				let self = this;
				if (!this.audioBlob) return;
				// 1. 通过fetch获取Blob数据
				fetch(this.audioPath)
					.then(response => response.blob())
					.then(blob => {
						// 2. 将Blob转换为File对象
						const file = new File([blob], 'audio.mp3', { type: 'audio/mp3' });
						// console.log('file',file);
						// 3. 使用uni.uploadFile上传
						uni.uploadFile({
							url: config.base_url + '/system/file/upload',
							header: {
								'Authorization': uni.getStorageSync('token')
							},
							file: file,
							name: 'file',
							formData: {
								'user': 'test'
							},
							success: (res) => {
								// #ifdef WEB
								let obj = JSON.parse(res.data);
								// console.log('上传成功', obj);
								let url = uni.getStorageSync('fileBrowseEnvironment') + '/' + obj.data.url
								// #endif
								// #ifdef MP-WEIXIN
								// console.log('上传成功', res);
								let url = uni.getStorageSync('fileBrowseEnvironment') + '/' + res.data.url
								// #endif
								// console.log('url=====',url)
								self.iotAppSpeakerPlayVoice(url);
							},
							fail: (err) => {
								console.error('上传失败', err);
								uni.showToast({
									title: res.msg,
									icon: "none",
									mask: true,
									duration: 2000
								});
							}
						});
					})
					.catch(error => {
						console.error('获取Blob数据失败', error);
					});
			},
			//H5 拖拽
			// 触摸开始
			handleTouchStart(event) {
				// 彻底阻止所有默认行为
				event.preventDefault();
				event.stopPropagation();
				
				this.touchStartY = event.touches[0].clientY;
				this.hasMoved = false;
				this.moveDirection = null;
				this.hasTriggeredMethod3 = false;
				
				// 设置长按定时器
				this.longPressTimer = setTimeout(() => {
					this.isLongPress = true;
					this.startRecord(); // 执行方法1
				}, 300); // 300ms触发长按
			},
	
			// 触摸移动
			handleTouchMove(event) {
				// 彻底阻止所有默认行为
				event.preventDefault();
				event.stopPropagation();
				
				if (!this.isLongPress) return;
				
				const currentY = event.touches[0].clientY;
				const deltaY = currentY - this.touchStartY;
				
				// 检测滑动方向（向上滑动为负值）
				if (Math.abs(deltaY) > 75) { // 增加阈值避免误触
					this.hasMoved = true;
					this.moveDirection = deltaY < 0 ? 'up' : 'down';
					
					// 向上滑动执行方法3（确保只触发一次）
					if (this.moveDirection === 'up' && !this.hasTriggeredMethod3) {
						this.hasTriggeredMethod3 = true;
						this.delRecord();
					}
				}
			},
	
			// 触摸结束
			handleTouchEnd() {
				// 清除长按定时器
				clearTimeout(this.longPressTimer);
				
				if (this.isLongPress) {
					this.stopRecord(); // 执行方法2
				}
				
				// 重置状态
				this.isLongPress = false;
				this.hasMoved = false;
				this.moveDirection = null;
			},
			
			// 关键：禁用上下文菜单（长按菜单）
			handleContextMenu(e) {
				e.preventDefault();
				return false;
			},
			// #endif
			
		},
		beforeDestroy() {
			// 清理资源
			if (this.recorder) {
				this.recorder.close();
			}
			if (this.audioPath) {
				URL.revokeObjectURL(this.audioPath);
			}
		}
	}
</script>

<style lang="stylus" scoped>
	@import '@/api/request/imagesUrl.styl';

	.voiceBroadcast {
		height: 100%;
		width: 100%;
		position: fixed;
		top: 0;
		display: flex;
		flex-direction: column;
		z-index: 10;
		background: rgba(0, 0, 0, 0.2);

		.null-box {
			flex: 1;
		}

		/* 语音广播-执行疏散 */
		.broadcast {
			width: 100%;
			background: #FFFFFF;
			border-top-left-radius: 20rpx;
			border-top-right-radius: 20rpx;
			padding: 22rpx 30rpx 30rpx;
			box-sizing: border-box;
			margin-top: 20rpx;
			position: absolute;
			bottom: 0;

			.broadcast_t {
				font-size: 30rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #333333;
				line-height: 30rpx;

				>label {
					font-size: 24rpx;
					font-family: PingFang SC;
					font-weight: 500;
					color: #999999;
					line-height: 30rpx;
					margin-left: 16rpx;
				}
			}

			.trumpet-max-box {
				display: flex;
				justify-content: flex-start;
				margin-top: 22rpx;
				flex-wrap: wrap;

				.trumpet-for-box {
					display: inline-block;
					width: auto;
					height: 60rpx;
					line-height: 60rpx;
					font-size: 24rpx;
					text-align: center;
					cursor: pointer;
					overflow: hidden;
					border: 1rpx solid #E0E0E0;
					border-radius: 10rpx;
					color: #E0E0E0;
					display: flex;
					justify-content: center;
					margin-right: 20rpx;
					margin-bottom: 10rpx;
					padding: 0 12rpx;
					box-sizing: border-box;

					>img {
						width: 36rpx;
						height: 34rpx;
						margin: 12rpx 20rpx 0 25rpx;
					}
				}

				.trumpet-color-a {
					border: 1px solid #0183FA;
					color: #0183FA;
				}

				.trumpet-color-b {
					border: 1px solid #CCCCCC;
					color: #999;
				}
			}
			.no-long-press{
				// -webkit-touch-callout: none !important;
				// -webkit-user-select: none !important;
				// -khtml-user-select: none !important;
				// -moz-user-select: none !important;
				// -ms-user-select: none !important;
				// user-select: none !important;
			}
			.broadcast_m {
				width: 100%;

				.broadcast_m_t {
					width: 142rpx;
					height: 142rpx;
					margin: 30rpx 0 0 258rpx;
					position: relative;
					font-size: 24rpx;
					font-family: PingFang SC;
					font-weight: 500;
					line-height: 170rpx;
					text-align: center;

					>img {
						width: 142rpx;
						height: 142rpx;
						position: absolute;

					}

					>label {
						width: 100%;
						font-size: 24rpx;
						font-family: PingFang SC;
						font-weight: 500;
						color: #0183FA;
						line-height: 24rpx;
						display: inline-block;
						text-align: center;
						position: absolute;
						top: 76rpx;
					}

					/* 按下 */
					.press_color {
						color: #FFFFFF;
					}

					/* 松开 */
					.slip_color {
						color: #0183FA;
					}
				}

				.broadcast_m_b {
					font-size: 24rpx;
					font-family: PingFang SC;
					font-weight: 500;
					color: #999999;
					line-height: 24rpx;
					text-align: center;
					margin-top: 14rpx;
				}
				.broadcast_m_t_back_a {
					background: url($imagesUrl+'commonality/icon_sskz_skfs_1.png') no-repeat center 0px;
					background-size: 100%;
					color: #FFFFFF;
				}
				
				.broadcast_m_t_back_b {
					background: url($imagesUrl+'commonality/icon_sskz_azsh_1.png') no-repeat center 0px;
					background-size: 100%;
					color: #0183FA;
				}
			}

			/* 疏散按钮 */
			.evacuation-button-box {
				width: 650rpx;
				height: 100rpx;
				background: #0183FA;
				color: #fff;
				text-align center;
				line-height: 100rpx;
				font-size: 28rpx;
				margin: 88rpx auto 0;
				border-radius: 20rpx;
			}
		}
	}
</style>