<template>
	<view class="chat">
		<uni-popup ref="popup" type="center" :animation="false">
			<view class="wrapper_inputMoney">
				<view class="wrapper_inputMoney_item">
					<!-- <view>请输入金额</view> -->
					<input @input="handleInput" v-model.number="inputMoney" type="number" placeholder="请输入金额"/>
				</view>
				<button class="yty" @click="handleSendMoney">提交</button>
			</view>
		</uni-popup>

		<view v-if="loading" class="full-screen-mask"></view>
		<view v-if="loading2" class="full-screen-mask2"></view>
		<image class="images" :src="codeUrl" />
		<button v-if="showResult" @click="getResults" class="getResult">查看结局</button>
		<view 
			@click="handleClearHistoryRecord"
			class="ClearHistoryRecord"
			>
			<image
				:class="{ 'box': true, 'hover': isHover }"
				src="../../static/photo/Reload.png"
				mode="scaleToFill"
			/>
			<text>重新来过</text>
		</view>
		<view 
			@click="sendMoneyMethods"
			class="sendMoney"
			>
			<image
				:class="{ 'box': true, 'hover': isHover }"
				src="../../static/photo/sendMoney.png"
				mode="scaleToFill"
			/>
			<text>发送红包</text>
		</view>
		<!-- 提供一个弹窗 用于输入昵称 -->
		<view v-if="false" class="dialog">
			<view class="dialogHeader">请输入您的昵称</view>
			<view class="dialogContent">
				<input
					class="inputU"
					ref="inputU"
					v-model="userInputName"
					placeholder="请输入..."
				/>
			</view>
			<view class="dialogFooter">
				<button @click="submitUserName">提交</button>
			</view>
		</view>
		
		<!-- 遮罩层 以及弹窗 -->
		<view v-if="board" class="shadow" @click="handleHiddenShadow"></view>
		<view v-if="board" class="board">
			<view class="jk">
				<!-- <image class="bk" :src="base64Img" /> -->
				<view class="imageH" :style="{backgroundImage:'url(' + base64Img + ')',backgroundSize:'auto',backgroundRepeat:'no-repeat'}"></view>
				<!-- 内容区域 -->
				<view>
					<view class="contentHeader">{{storyContent[0]}}</view>
					<view class="contentMain">
						<text>{{storyContent[1]}}</text>
					</view>
				</view>
			</view>
			<view class="footer">
				<button @click="backHome" class="home">返回首页</button>
				<button @click="handleClearHistoryRecord" class="reload">重新来过</button>
			</view>
		</view>
		<!-- 功能区 -->
		<view class="topBox">
			<image @click="backHome" class="backHome" src="../../static/photo/back.png"/>
			<view class="money">
				<image src="../../static/photo/money_bag.png" />
				<view class="monney">余额：{{ monney }}</view>
			</view>
			
			<image class="more" @click="handleMore" src="../../static/photo/more.png" />
		</view>
		<view class="goods" v-if="show">
			<view class="containerL">
				<!-- 物品栏 -->
				<view class="grid-container">
					<!-- 使用 v-for 循环渲染每个物品 -->
					<view class="grid-item" v-for="(item, index) in items" :key="index">
						<view class="grid_item_box">
							{{ item }}
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="shadow" v-if="show" @click="handleShow"></view>
		<!-- 历史聊天记录 回显到页面 -->
		<view class="container">
			<view v-if="historyRecord.length>0">
				<view v-for="(item, index) in historyRecord" :key="index" class="historyListData">
					<view class="historyListData_item parent-element">
						<view v-if="Object.keys(item.WObj).length!==0" class="left distence leftPhoto">
							<image :src="dpPhoto" class="photo"></image>
							<view class="allbody dealFloat li_left">
								<view class="heartActive doubleStatus">
									【时间】: {{ item.WObj["时间"] }}
								</view>
								<br />
								<view class="heartActive doubleStatus">
									【地点】: {{ item.WObj["地点"] }}
								</view>
								<view class="heartActive">
									<view class="textStyle" v-html="handleText(item.Message)"></view>
								</view>
							</view>
						</view>

						<view v-else class="right distence rightPhoto">
							<image :src="userPhoto" class="photo"></image>
							<view class="li_right allbody dealFloat">
								<view class="heartActive">
									{{ item.Message }}
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>

		</view>
		<view class='formContainer'>
			<view class='itemContainer'>
				<view class="chat-window">
					<view id="MyIn" class='tongyi'></view>
					<input
						v-model="inputVal"
						@focus="handleFocus"
						@blur="hadnleBlur"
						:class="boxClass"
						class="activeAnimaite"
						placeholder="请输入..."
					/>
					<image id="Send" :class="showSend" @click="handleSendMessage" src="../../static/photo/Send.png" />
					<image
						id="SendSound"
						:class="[activeState,focus]"
						class="activeAnimaite"
						src="../../static/photo/sound.png"
						@touchstart.prevent="startRecord"
						@touchend.prevent="endRecord"
					/>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
// import FullScreenLoading from '../../components/FullScreenLoading.vue';
const recorderManager = uni.getRecorderManager();
const innerAudioContext = uni.createInnerAudioContext();

innerAudioContext.autoplay = true;

export default {
	data() {
		return {
			inputMoney:0,
			loading2:true,
			userInputName:'',
			showDialog:true,
			userName:'',
			isHover: false,
			base64Img:'',
			showResult:false,
			showSend:'',
			activeState:'',
			focus:'',
			show: false,
			monney: 0,
			boxClass:'chat-window-message',
			items: [],
			historyRecord: [],
			socketTask: null,
			recive: null,
			codeUrl: '',
			dpPhoto: '',
			userPhoto: '',
			inputVal: '',
			loading: false,
			finalVal: '',
			EPlayer: null,
			innerAudioContext: null,
			board:false,
			storyContent:['头部内容','主体内容'],
			text: 'uni-app',
			voicePath: '',
			timer:null
		}
	},
	beforeDestroy (){
		if (this.socketTask) {
			this.socketTask.close(); // 关闭 WebSocket 连接
			this.socketTask = null; // 清空 WebSocket 对象
		}
		clearInterval(this.timer)
		if (this.EPlayer) {
			if(this.EPlayer.cb) this.EPlayer.cb = null
			this.EPlayer.stop();
			this.EPlayer.destroy();
			this.EPlayer = null;
		}

	},
	mounted() {
		console.log(uni.getStorageSync('userName'))
		this.userInputName = uni.getStorageSync('userName')
		this.submitUserName()
		const obj = getApp().globalData.shareObject;
		console.log('首页传来的数据',obj)
		if(this.$globalData.showEnding){
			this.board = true
			this.showResult = true
			this.storyContent = this.$globalData.EndingContent
			this.base64Img = this.$globalData.base64ImageStr
		}
		//讲完话以后 向服务器发送数据
		recorderManager.onStop( res=> {
			console.log(222,res)
			// self.voicePath = res.tempFilePath
			this.convertAudioToStream(res.tempFilePath)
		});

		// uni.setStorageSync('session_token', response[1].cookies[0].split(';')[0]);
		//1.获取心跳包
		uni.request({
			url: 'https://admin.mindepoch.com:8089/heartbeat',
			header: {
				'Cookie': `${uni.getStorageSync('session_token')}`
			}
		}).then(result => {
			// console.log(response[1])
		}).catch(errs => {
			console.log(errs)
		});

		//获取图片资源
		this.getPhoto()

	},
	onLoad() {

			
	},
	methods: {
		handleSendMoney() {
			if(this.inputMoney==""&&this.inputMoney.trim()==""){
				uni.showToast({
					title: '金额不可为空！',
					icon:'none'
				})
			}else{
				this.inputVal = '我向她发送了红包'+this.inputMoney+'元'
				//向服务器发请求
				this.socketTask.send({
					data: JSON.stringify({
						type: 0,
						content: '我向她发送了红包'+this.inputMoney+'元'
					}),
					success: () => {
						console.log('消息发送成功')
						this.loading = true;
						// uni.showLoading({
						// 	title: '思考中...',
						// 	mask: true // 是否显示透明蒙层，防止触摸穿透，默认为 false
						// });
						let str = '对方正在输入...'
						let i = 6
						this.timer = setInterval(() => {
							if(i<10){
								i += 1
							}else{
								i = 6
							}
							uni.setNavigationBarTitle({
								title: str.substr(0,i)
							});
						}, 400);
					}
				});
				this.$refs.popup.close()
				
			}
		},
		submitUserName(){
			if(this.userInputName==""&&this.userInputName.trim()==""){
				uni.showToast({
					title: '昵称不可为空！',
					icon:'none'
				})
			}else{
				this.showDialog = false
				// this.loading2 = false
				this.socketConnect()
				console.log("???")
				
			}
		},

		socketConnect(){
			//3.websocket 连接
			console.log(this.userInputName,uni.getStorageSync('userName'))
			this.socketTask = uni.connectSocket({
				url: `wss://admin.mindepoch.com:8089/WorldChats/ws?id=${uni.getStorageSync('wxUid')}&world_name=情圣日记&BgInfo=我是罗翔爱徒&userInfo={"name":"${uni.getStorageSync('userName')}","bk":"罗翔爱徒"}`, // WebSocket 服务器的地址
				// 成功建立连接的回调
				success: () => console.log('WebSocket 连接成功'),
				// 失败的回调
				fail: () => console.log('WebSocket 连接失败')
			});
			// 监听 WebSocket 连接打开事件
			this.socketTask.onOpen(() => {
				console.log('WebSocket 连接已打开');
				this.getHistory()
			});
			// 监听接收到服务器发送的消息事件
			this.socketTask.onMessage((message) => {
				console.log('--------',JSON.parse(message.data))
				clearInterval(this.timer);
				uni.setNavigationBarTitle({
					title: 'Ai聊天'
				});
				this.loading = false
				this.loading2 = false
				uni.hideLoading();
				//处理把数据添加至页面
				const backValue = JSON.parse(message.data)
				if(backValue.code===0){
					this.badRequest(backValue.backValue)
				}else if(backValue.code===3){
					this.badRequest(backValue.backValue)
				}else if(backValue.code===4){
					this.badRequest(backValue.backValue)
				}else if(backValue.code===-1){
					this.badRequest(backValue.backValue)
				}else if(backValue.code===1){
					let Contents = backValue.ISLIU ? backValue.ISLIU : ''
					console.log(Contents)
					if (Contents !== '') {
						Contents = Contents.replaceAll("“", `"`).replaceAll("”", `"`)
						this.finalVal = this.extractQuotedTexts(Contents).join(",")
						console.log('处理后的文字', this.finalVal)
						this.GoSound(this.finalVal, "huaHuo", function (text, falg) {
							if (falg) {
								console.log('讲话完毕！')
							}
						})
					}

					//物品栏的物品的展示
					if(backValue.WObj&&backValue.WObj['物品']&&Object.keys(backValue.WObj['物品']).length>0){
						//替换物品栏的物品
						this.items = Object.values(this.monney = backValue.WObj['物品']).filter(val=>{
							return !val.includes("存款:")
						})
						//余额显示
						const val = Object.values(this.monney = backValue.WObj['物品']).filter(val=>{
							return val.includes("存款:")
						})
						// console.log(val[0].match(/\d+/))
						if(val[0]){
							this.monney = val[0].match(/\d+/)
						}else{
							this.monney = 0
						}

						//出现结局用户不可聊天 显示查看结局按钮

						//展示剧情结局
						this.storyContent = backValue.WObj.EndStr.split('@')
						this.$globalData.EndingContent = backValue.WObj.EndStr.split('@')
						if(backValue.WObj.EndStr){
							//出现结局面板
							if(backValue.WObj.EndStr!==''){
								//请求背景图片
								uni.request({
									url: `https://admin.mindepoch.com:8089/worlds/${this.storyContent[0]}.png`,
									method: 'get',
									responseType: 'arraybuffer',
									header: {
										'Cookie': `${uni.getStorageSync('session_token')}`,
									}
								}).then(res=>{
									console.log('图片资源',res)
									//结局面板 背景图片 底部按钮
									// this.board = true
									this.base64Img = 'data:image/png;base64,' + uni.arrayBufferToBase64(res[1].data);
									this.showResult = true
									//全局存储
									this.$globalData.showEnding = true
									this.$globalData.base64ImageStr = this.base64Img
								}).catch(err=>{
									console.log(err)
								})
							}
						}else{
							//未到达结局 因此不展示结局面板
							this.board = false //隐藏结局面板
							this.showResult = false  //隐藏查看结局按钮
							this.$globalData.showEnding = false //不展示弹窗信息
						}
						
					}

					if (!backValue.content) {
						// console.log(backValue)
						//对象一为用户 对象二为数字人
						if(this.historyRecord.length===0){
							this.historyRecord.push( {
								Message: backValue.ISLIU,
								WObj: backValue.WObj,
							})
						}else{
							this.historyRecord.push({
								Message: this.inputVal,
								WObj: {}
							}, {
								Message: backValue.ISLIU,
								WObj: backValue.WObj,
							})
						}

						this.inputVal = ''
						this.loading = false;
						uni.hideLoading();
					}
				}
			});
			// 监听 WebSocket 错误事件
			this.socketTask.onError((error) => {
				console.error('WebSocket 错误：', error);
			});
			// 监听 WebSocket 连接关闭事件
			this.socketTask.onClose(() => {
				console.log('WebSocket 连接已关闭');
			});
		},

		getHistory(){
			uni.request({
				url: 'https://admin.mindepoch.com:8089/worldChat-history',
				method: 'post',
				data:{
					// id:this.$globalData.wxUid
					id:1
				},
				header: {
					'Cookie': `${uni.getStorageSync('session_token')}`,
					'Content-Type': 'application/x-www-form-urlencoded'
				}
			}).then(res => {
				console.log('从服务器获取历史聊天记录',res[1].data)
				if (res[1].data.code===1) {
					if(res[1].data.chatRecordInfo){
						this.historyRecord = res[1].data.chatRecordInfo.Records
						//把文字内容加粗
						// let textArr = []
						// this.historyRecord.forEach(element => {
						// 	textArr.push(element.Message)
						// });
						// console.log(textArr)
						// //重新编辑文字内容 
						// textArr.forEach((everyText,index)=>{
						// 	textArr[index] = `<strong>${everyText}<strong>`
						// })
						// this.historyRecord.forEach((element,index) => {
						// 	this.historyRecord[index].Message = textArr[index]
						// });

					}
				}else{
					uni.showToast({
						title: res[1].data.message,
						icon: 'none'
					})
				}
			}).catch(err => {
				console.log(err)
			})
		},

		getPhoto(){
			//获取背景图 
			uni.request(
				{
					url:`https://admin.mindepoch.com:8089/static/poster${96}.png` ?
						`https://admin.mindepoch.com:8089/static/poster${96}.png` :
						`https://admin.mindepoch.com:8089/static/poster${96}.jpg` ?
						`https://admin.mindepoch.com:8089/static/poster${96}.jpg` :
						`https://admin.mindepoch.com:8089/static/poster${96}.gif` ?
						`https://admin.mindepoch.com:8089/static/poster${96}.gif` :
						`/static/images/ai1.png`,
					method: 'GET',
					data: {
						id: 1,
					},
					responseType: 'arraybuffer',
					header: {
						'Cookie': `${uni.getStorageSync('session_token')}`,
						"Cache-Control": "no-cache"
					}
				}).then(res => {
					const arrayBuffer = res[1].data
					this.codeUrl = 'data:image/png;base64,' + uni.arrayBufferToBase64(arrayBuffer);
				}).catch(err => console.log(err))

			//获取数字人头像
			uni.request(
				{
					url:`https://admin.mindepoch.com:8089/static/avatar${96}.png` ?
						`https://admin.mindepoch.com:8089/static/avatar${96}.png` :
						`https://admin.mindepoch.com:8089/static/avatar${96}.jpg` ?
						`https://admin.mindepoch.com:8089/static/avatar${96}.jpg` :
						`https://admin.mindepoch.com:8089/static/avatar${96}.gif` ?
						`https://admin.mindepoch.com:8089/static/avatar${96}.gif` :
						`/static/images/ai1.png`,
					method: 'GET',
					responseType: 'arraybuffer',
					data: {
						id: 96,
					},
					responseType: 'arraybuffer',
					header: {
						'Cookie': `${uni.getStorageSync('session_token')}`,
						"Cache-Control": "no-cache"
					}
			}).then(res => {
				const arrayBuffer = res[1].data
				this.dpPhoto = 'data:image/png;base64,' + uni.arrayBufferToBase64(arrayBuffer);
			}).catch(err => {
				console.log(err)
			})

			//获取用户头像
			uni.request({
				url:`https://admin.mindepoch.com:8089/userFile/avatar${1}.png` ?
					`https://admin.mindepoch.com:8089/userFile/avatar${1}.png` :
					`https://admin.mindepoch.com:8089/userFile/avatar${1}.jpg` ?
					`https://admin.mindepoch.com:8089/userFile/avatar${1}.jpg` :
					`https://admin.mindepoch.com:8089/userFile/avatar${1}.gif` ?
					`https://admin.mindepoch.com:8089/userFile/avatar${1}.gif` :
					`/static/images/ai1.png`,
				method: 'GET',
				responseType: 'arraybuffer',
				data: {
					id: 1,
				},
				responseType: 'arraybuffer',
				header: {
					'Cookie': `${uni.getStorageSync('session_token')}`,
					"Cache-Control": "no-cache"
				}
			}).then(res => {
				const arrayBuffer = res[1].data
				this.userPhoto = 'data:image/png;base64,' + uni.arrayBufferToBase64(arrayBuffer);
			}).catch(err => console.log(err))
		},

		badRequest(message){
			uni.showToast({
				title: message,
				icon: 'none'
			});
			return
		},
		handleTouchStart() {
			this.isHover = true;
		},
		handleTouchEnd() {
			this.isHover = false;
		},
		handleText(text){
			return text.replace(/“([^”]*)”/g, '<strong style="color:#e4c7ffd9 ">"$1"</strong>')
		},
		handleHiddenShadow(){
			this.board = false
		},
		getResults(){
			this.board = true
		},
		handleInput(event){
			console.log(event.target.value)
			const val = event.target.value
			// this.inputMoney
			// if(typeof val === 'number' && !isNaN(val)){
			// 	//输入为数字
			// 	this.inputMoney = val
			// }else{
			// 	this.inputMoney = 0
			// }
		},
		open() {
			this.$refs.popup.open()
		},
		close() {
			// TODO 做一些其他的事情，before-close 为true的情况下，手动执行 close 才会关闭对话框
			// ...
			this.$refs.popup.close()
		},
		confirm(value) {
			console.log(value)
			this.$refs.popup.close()
		},

		backHome() {
			uni.navigateTo({
                url: `/pages/homeCards/index`
            });
		},
		sendMoneyMethods(){
			//弹窗出现 输入金额 确认 提交 发送
			// this.showInputMoneyDialog = true
			this.$refs.popup.open('center')
			
		},
		
		handleClearHistoryRecord(){
			this.historyRecord = []
			this.showResult = false //隐藏底部的查看结局按钮
			this.board = false //隐藏弹窗
			uni.showLoading({
				title: '请稍等...',
				mask: true // 是否显示透明蒙层，防止触摸穿透，默认为 false
			});
			this.loading = true //显示遮挡层
			uni.request({
				url: `https://admin.mindepoch.com:8089/SoulNeuralFileWorldReset`,
				method: 'post',
				data: {
					worldName: '情圣日记',
					BgInfo:'我是罗翔爱徒',
					userInfo:`{"name":"${this.userInputName}","bk":"罗翔爱徒"}`
				},
				header: {
					'Cookie': `${uni.getStorageSync('session_token')}`,
					"Cache-Control": "no-cache",
					'Content-Type': 'application/x-www-form-urlencoded'
				}
			}).then(res => {
				console.log('用户的聊天历史记录',res[1])
				this.loading = false //隐藏遮挡层
				uni.hideLoading();
				if(res[1].statusCode===200){
					//清理全局的缓存
					this.$globalData.EndingContent = []
					this.$globalData.base64ImageStr = ''
					this.$globalData.showEnding = false
				}
			}).catch(err => {
				this.loading = false  //隐藏遮挡层
				uni.hideLoading();
			})
		},
		convertAudioToStream(filePath) {
			const that = this
			const fileSystemManager = uni.getFileSystemManager();
			fileSystemManager.readFile({
				filePath: filePath, // 音频文件路径
				success: function(res) {
					console.log('音频',res.data);
					// 这里的res.data就是音频文件的ArrayBuffer数据，根据需要对其进行操作。
					// 比如，你可以将这个数据上传到服务器。
					//语音接口
					uni.uploadFile({
						url: 'https://admin.mindepoch.com:8089/speechConvertor',
						filePath: filePath,
						name: 'file',
						header: {
							'Content-Type': 'multipart/form-data',
							'Cookie': `${uni.getStorageSync('session_token')}`,
						},
						success: uploadFileRes => {
							const vocieData = JSON.parse(uploadFileRes.data)
							console.log('uploadFile success, res is:', uploadFileRes);
							if(vocieData.code===1){
								if(vocieData.message.transcription.length==0){
										uni.showToast({
											title: '说话时长过短，请重新录制！',
											icon: 'none'
										});
									return
								}
								that.inputVal = vocieData.message.transcription[0].text
								//获取到用户说的话
								that.socketTask.send({
									data: JSON.stringify({
										type: 0,
										content: that.inputVal
									}),
									success: () => {
										console.log('消息发送成功')
										that.loading = true;
										uni.showLoading({
											title: vocieData.message,
											mask: true, // 显示透明蒙层，防止触摸穿透
										});
										let str = '对方正在输入...'
										let i = 6
										that.timer = setInterval(() => {
											if(i<10){
												i += 1
											}else{
												i = 6
											}
											uni.setNavigationBarTitle({
												title: str.substr(0,i)
											});
										}, 400);
									}
								});
							}else{
								that.loading = false;
								uni.showToast({
									title: vocieData.message,
									icon: 'none'
								});
							}
						},
						fail: uploadFileErr => {
							console.error('uploadFile error, err is:', uploadFileErr);
						}
					})
				},
				fail: function(err) {
					console.log(err);
				}
			});
		},
		startRecord() {
			console.log('开始录音');
			recorderManager.start();
			this.activeState = 'activeMicrophone'
			uni.setNavigationBarTitle({
				title: '语音输入中...'
			});
		},
		endRecord() {
			console.log('录音结束');
			recorderManager.stop();
			this.activeState = ''
			uni.setNavigationBarTitle({
				title: 'AI聊天'
			});
		},

		handleShow() {
			this.show = false
		},
		handleMore() {
			//出现物品栏
			this.show = true
		},
		handleFocus(){
			this.focus = 'activeFocus'
			this.showSend = 'showSend'
			this.boxClass = 'chat-window-message2'
			// console.log('聚焦')
		},

		hadnleBlur(){
			console.log('blur')
			this.focus = ''
			// console.log('失焦')
			this.showSend = ''
			this.boxClass = 'chat-window-message'
			uni.setNavigationBarTitle({
				title: 'AI聊天'
			});
		},
		handleSendMessage() {
			console.log('click')
			if(this.inputVal.trim()===''){
				uni.showToast({
					title: '输入框值不可为空',
					icon: 'none'
				});
				this.inputVal = ''
				return
			}
			this.socketTask.send({
				data: JSON.stringify({
					type: 0,
					content: this.inputVal
				}),
				success: () => {
					console.log('消息发送成功')
					this.loading = true;
					// uni.showLoading({
					// 	title: '思考中...',
					// 	mask: true // 是否显示透明蒙层，防止触摸穿透，默认为 false
					// });

					let str = '对方正在输入...'
					let i = 6
					this.timer = setInterval(() => {
						if(i<10){
							i += 1
						}else{
							i = 6
						}
						uni.setNavigationBarTitle({
							title: str.substr(0,i)
						});
					}, 400);
				}
			});
		},
		computeLen(OBJ) {
			console.log(OBJ)
			let Sr = "", cp = OBJ.content
			while (1) {
				let sAim = cp.match(/,|，|。|\!|！|？|\?|\n/)
				if (Sr.length < 20 && sAim) {
					Sr += cp.substring(0, sAim.index + 1)
					cp = cp.substring(sAim.index + 1)
				} else {
					if ((Sr.length + cp.length) < 20 || Sr.length < 15) {
						Sr += cp
					}
					break;
				}
			}
			let obj = {}
			obj.Sr = Sr
			obj.content = OBJ.content.replace(Sr, "")
			return obj
		},

		FetchAbuffer(OriginObj, voicer, Sarry, CB) {
			let Cobj = this.computeLen(OriginObj);
			let Asr = Cobj.Sr;
			uni.request({
				url: 'https://admin.mindepoch.com:8089/VoiceMode/GetVoiceEcho',
				method: 'post',
				responseType: 'arraybuffer', // 设置响应类型为 'arraybuffer'
				header: {
					'Content-Type': 'application/x-www-form-urlencoded',
					'Cookie': `${uni.getStorageSync('session_token')}`
				},
				data: {
					name: voicer,
					voice_text: Cobj.Sr,
					text_language: 'zh'
				}
			}).then(response => {
				if (response[1].statusCode === 200) {
					return response[1].data
				} else {
					// return response.text().then(text => Promise.reject(text));
				}
			}).then(arrayBuffer => {
				Sarry.push({ A: arrayBuffer, S: Asr });
				// OriginObj = Cobj
				OriginObj.content = Cobj.content
				OriginObj.Sr = Cobj.Sr
				if (Cobj.content != "") {
					setTimeout(() => {
						this.FetchAbuffer(Cobj, voicer, Sarry)
					}, 1000)
				}
			})
		},

		GoSound(content, voicer, CB) {
			// 要读的文字 声线 回调
			let Sarry = [], Cobj = this.computeLen({ content });
			uni.request({
				url: 'https://admin.mindepoch.com:8089/VoiceMode/GetVoiceEcho',
				method: 'post',
				responseType: 'arraybuffer', // 设置响应类型为 'arraybuffer'
				header: {
					'Content-Type': 'application/x-www-form-urlencoded',
					'Cookie': `${uni.getStorageSync('session_token')}`
				},
				data: {
					name: voicer,
					voice_text: Cobj.Sr,
					text_language: 'zh'
				}
			}).then(response => {
				// console.log(response[1])
				if (response[1].statusCode === 200) {
					return response[1].data
				} else {
					// return response.text().then(text => Promise.reject(text));
					console.log(response)
				}
			})
				.then(arrayBuffer => {
					console.log(arrayBuffer)
					const FileSystemManager = uni.getFileSystemManager();
					let tempFilePath = wx.env.USER_DATA_PATH + `/tempAudio_${new Date().getTime()}.mp3`; // 或者其他音频格式，根据实际情况而定
					console.log('tempFilePath:',tempFilePath)
					FileSystemManager.writeFile({
						filePath: tempFilePath,
						data: arrayBuffer,
						encoding: 'binary',
						success: () => {
							// 写入成功，使用小程序的背景音频播放器播放音频
							if (this.EPlayer) {
								// this.EPlayer.onended=null
								this.EPlayer.onEnded()
								this.EPlayer.stop()
								this.EPlayer.cb && this.EPlayer.cb(Cobj.Sr, true, true)
							}
							if (CB) CB(Cobj.Sr)
							this.EPlayer = uni.createInnerAudioContext();
							this.EPlayer.src = tempFilePath;
							this.EPlayer.play();
							this.EPlayer.cb = CB
							var Rfunc = () => {
								// console.log('rfun')
								if (Sarry.length == 0) {
									// console.log(Cobj.content)
									if (Cobj.content != '') {
										setTimeout(() => {
											// this.EPlayer.onEnded(Rfunc)
											this.EPlayer.onended()
										}, 1000);
										return
									}
									if (CB) CB(Cobj.Sr, true)
									return
								}
								let Sobj = Sarry.shift()
								console.log(Sobj)
								uni.removeSavedFile({
									filePath: tempFilePath,
									success: function (res) {
										console.log('删除缓存文件成功');
									},
									fail: function (err) {
										console.log('删除缓存文件失败', err);
									}
								})
								tempFilePath = wx.env.USER_DATA_PATH + `/tempAudio_${new Date().getTime()}.mp3`
								FileSystemManager.writeFile({
									filePath: tempFilePath,
									data: Sobj.A,
									encoding: 'binary',
									success: () => {
										console.log(tempFilePath)
										if (CB) CB(Cobj.Sr)
										this.EPlayer = uni.createInnerAudioContext();
										this.EPlayer.src = tempFilePath;
										this.EPlayer.play();
										this.EPlayer.onEnded(Rfunc)
										this.EPlayer.onended = Rfunc
									},
									fail: console.error,
								});
							}
							this.EPlayer.onEnded(Rfunc)
							this.EPlayer.onended = Rfunc
							if (Cobj.content != "") {
								setTimeout(() => {
									this.FetchAbuffer(Cobj, voicer, Sarry, CB)
								}, 5000)
							}

						},
						fail: console.error,
					});
				})
				.catch(reason => {
					console.log(reason);
				}).finally(() => {
				});
		},
		extractQuotedTexts(str) {
			// 正则表达式匹配引号内的文本，包括转义引号
			const pattern = /(["'])(?:(?=(\\?))\2.)*?\1/g;
			let matches = [];
			let match;
			// 使用正则表达式的exec方法进行循环匹配
			while ((match = pattern.exec(str)) !== null) {
				// 获取引号内的文本（排除引号本身）
				let quotedText = match[0].slice(1, -1).replace(/\\(["'])/g, '$1'); // 去除引号并取消转义
				matches.push(quotedText);
			}
			return matches.length == 0 ? [str] : matches;
		}
	}
}
</script>


<style scoped>
.chat {
	background-color: #293339a2;
}

.formContainer {
    height: 10vh;
    width: 100vw;
    background-color: #000000c7;
    position: fixed;
    bottom: 0;
    left: 0;
}

.container {
    margin: auto 2%;
    height: 80vh !important;
    padding: 1.5vh 0;
    overflow: scroll;
}

.chat-window {
	width: 100vw;
	height: 100rpx;
	position: fixed;
	bottom: 6rpx;
	left: 0;
}

.chat-window-message {
    font-size: 26rpx;
	margin-left: 2vw;
	margin-bottom: 2vh;
    width: 25vw;
    height: 6vh;
    border-radius: 10rpx;
    border: 1px solid #ffffff9c;
    color: white;
    text-indent: 10rpx;
	padding-left: 10rpx;
}

.activeAnimaite{
	transition: all .5s;
}


.chat-window-message2 {
	font-size: 26rpx;
	margin-left: 2vw;
    margin-bottom: 2vh;
    width: 70vw;
    height: 6vh;
    border-radius: 10rpx;
    border: 1px solid #ffffff9c;
    color: white;
    text-indent: 10rpx;
	padding-left: 10rpx;
}

#Send {
    width: 7vh;
    height: 7vh;
	position: fixed;
	bottom: 1.2vh;
	right: 25rpx;
	border: 1px solid rgba(154, 150, 211, 0.788);
	border-radius: 50%;
	display: none;
}

#SendSound {
    width: 90rpx;
    height: 90rpx;
    position: absolute;
    bottom: 7rpx;
    left: 50%;
    -webkit-transform: translateX(-50%);
    transform: translateX(-50%);
    border-radius: 50%;
    transition: all .5s;
	border: 1px solid rgba(255, 255, 255, 0.578);
}

.historyListData {
	font-size: 26rpx;
}
.historyListData:last-child{
	margin-bottom: 30rpx;
}

.historyListData_item {
	color: white;
}

.heartActive {}

.dealFloat {}

.li_left {
	margin-left: 120rpx;
}

.li_left::after {
	border-top: 10px solid #ddd5ff33;
	content: "";
	height: 0;
	position: absolute;
	top: 15rpx;
	width: 0;
	border-left: 15px solid #0000;
	left: 90rpx;
}

.li_right {
	margin-right: 120rpx;
}

.li_right::before {
	border-top: 10px solid #ddd5ff33;
	content: "";
	height: 0;
	position: absolute;
	top: 15rpx;
	width: 0;
	border-right: 15px solid #0000;
	right: 90rpx;
}

.doubleStatus {
	background-color: #adb6ff66;
	border-radius: 5px;
	display: inline-block;
	margin-bottom: 6px;
	padding: 3px 9px 3px 3px;
}

.allbody {
	background-color: #ddd5ff33;
	padding: 12rpx 15rpx;
	border-radius: 6px;
	display: inline-block;
	word-break: break-all;
	max-width: 60vw;
}

.left {
	float: left;
}

.right {
	float: right;
}

.distence {
	margin-bottom: 20rpx;

}

.leftPhoto {
	position: relative;
}

.leftPhoto image {
	position: absolute;
	top: 0;
	left: 0;
}

.rightPhoto {
	position: relative;
}

.rightPhoto image {
	position: absolute;
	top: 0;
	right: 0;
}

.images {
	position: fixed;
	width: 100vw;
	height: 100vh;
	z-index: -99;
}

.photo {
	width: 80rpx;
	height: 80rpx;
	border-radius: 50%;
}

.full-screen-mask {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	/* 半透明遮罩层 */
	z-index: 999;
}
.full-screen-mask2 {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	z-index: 998;
	/* 半透明遮罩层 */
}

.current {
	position: fixed;
	top: 0;
	left: 0;
	width: 100vw;
	z-index: 998;
}

.current2 {
	position: fixed;
	top: 50px;
	left: 0;
	width: 100vw;
	z-index: 999;
}

.more {
	width: 60rpx;
	height: 60rpx;
	margin-right: 10rpx;
}

.money {
	text-align: center;
}

.money>image {
	width: 40rpx;
	height: 40rpx;
}

.monney {
	font-size: 20rpx;
	color: #ffffff;
}

.shadow {
	z-index: 998;
	position: fixed;
	top: 0;
	left: 0;
	width: 100vw;
	height: 100vh;
	background-color: #0000007b;
}

.goods {
	z-index: 999;
	position: fixed;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	width: 80vw;
	height: 50vh;
	background-color: #ffffff5e;
	border-radius: 20rpx;
	overflow-y: scroll;
}

.containerL {
	padding: 10px;

}

/* 栅格容器样式 */
.grid-container {
	display: flex;
	flex-wrap: wrap;
	/* 允许元素换行 */
	justify-content: space-between;
	/* 元素间距设置为平均分布 */
}

/* 单个格子样式 */
.grid-item {
	width: 30%;
	/* 一行三个物品，每个物品占据宽度的30% */
	background-color: #342e2e6e;
	/* 背景颜色 */
	margin-bottom: 15px;
	/* 格子间底部外边距 */
	text-align: center;
	/* 内容居中显示 */
	border-radius: 10rpx;

}

.grid_item_box {
	width: 90%;
	height: 120rpx;
	margin: 5%;
	border-radius: 10rpx;
	background-color: #342e2e6e;
	/* 背景颜色 */
}

.topBox {
	background-color: #00000091;
	height: 7vh;
	display: flex;
    justify-content: space-between;
	align-items: center;
}
.activeMicrophone{
	width: 150rpx !important;
	height: 150rpx !important;
	left:90vw;
	z-index: 999;
    border-radius: 50%;
    border: 1px solid #ffffff2e;
    padding: 2rpx;
    box-shadow: 0 0 14rpx #fff;
	
}
/* 定义进入和离开时的过渡状态 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 2s;
}

/* 定义进入开始和离开结束时的状态 */
.fade-enter,
.fade-leave-to {
  opacity: 0;
}

.activeFocus{
	left: 90vw !important;
	transition: all .5s;
	opacity: 0;
	z-index: -1 !important;
}
.showSend{
	display: block !important;
}
.ClearHistoryRecord{
	position: fixed;
    bottom: 10.5vh;
    right: 2vw;
	font-size: 20rpx;
	color: #fff;
	font-size: 24rpx;
}
.ClearHistoryRecord>image{
	width: 50rpx;
	height: 50rpx;
	display: block;
	margin: 0 auto 10rpx;
}
.ClearHistoryRecord>image:active{
	scale: 1.9;
}
.sendMoney{
	position: fixed;
    bottom: 20.5vh;
    right: 2vw;
	font-size: 20rpx;
	color: #fff;
	font-size: 24rpx;
}
.sendMoney>image{
	width: 50rpx;
	height: 50rpx;
	display: block;
	margin: 0 auto 10rpx;
}
.sendMoney>image:active{
	scale: 1.9;
}
.wrapper_inputMoney{
	width: 65vw;
	height: 200rpx;
	background-color: #ffffff;
	border-radius: 10rpx;
	background-color: rgba(180, 142, 148, 0.34);
	padding: 40rpx;
	z-index: 999;
}
.wrapper_inputMoney_item{
	
}
.wrapper_inputMoney_item>input{
	width: 80%;
	border: 1px solid #ffffff;
	border-radius: 10rpx;
	height: 70rpx;
	text-indent: 10rpx;
	margin: 30rpx auto;
	font-size: 34rpx;
	color: #ffffff;
}
.yty{
	margin: auto;
	width: 200rpx;
	height: 80rpx;
	line-height: 80rpx;
	background-color: rgb(158, 166, 184);
	font-size: 40rpx;
	border-radius: 15rpx;
	color: #ffffff;
	margin-top: 20rpx;
}
.board{
	width: 80vw;
	min-height: 30vh;
	max-height: 70vh;
	border-radius: 10rpx;
	position: fixed;
	top:50%;
	left:50%;
	transform: translate(-50%,-50%);
	background-color: rgb(31 28 28 / 97%);
	z-index: 999999;
	padding: 12rpx;
	color: #fff;
}
.contentHeader{
	text-align: center;
	padding: 20rpx;
	font-size: 34rpx;
}
.contentMain{
	font-size: 30rpx;
	padding: 20rpx;
	line-height: 45rpx;
	overflow-y: scroll;
    overflow: scroll;
	height: 50vh;
}
.imageH{
	height: 60vh;
	width: 100%;
	position: absolute;
	top:0;
	left:0;
	z-index: -1;
	opacity: .45;
}
.getResult{
	height: 10vh;
	position: fixed;
	bottom: 0;
	left:0;
	width: 100vw;
	font-size: 50rpx;
	z-index: 1;
}
.shadow{
	width: 100vw;
	height: 100vh;
	position: fixed;
	top:0;
	left:0;
	z-index: 999998;
}
.backHome{
	width: 70rpx;
	height: 60rpx;
	margin-left: 10rpx;
}
.footer{
	height: 60rpx;
	margin-top: 20rpx;
	display: flex;
}
.home{
    width: 200rpx;
    height: 50rpx;
    font-size: 26rpx;
    line-height: 50rpx;
}
.reload{
    width: 200rpx;
    height: 50rpx;
    font-size: 26rpx;
    line-height: 50rpx;
}
.bk{
	width: 100%;
	height: 100%;
	position: absolute;
    top: 0;
    left: 0;
    opacity: 0.25;
}
.jk{
	position: relative;
}
.parent-element::after {
    content: "";
    display: table;
    clear: both;
}
.dialog{
	width: 80vw;
	height: 400rpx;
	position: fixed;
	top:50%;
	left:50%;
	transform: translate(-50%,-50%);
	border-radius: 10rpx;
	background-color: rgba(180, 142, 148, 0.34);
	z-index: 999;
}
.dialogHeader{
	text-align: center;
	font-size: 40rpx;
	color: #ffffff;
	padding: 20rpx;
}
.dialogContent{
	
}
.dialogFooter > button{
	margin: auto;
	width: 200rpx;
	height: 80rpx;
	line-height: 80rpx;
	background-color: rgb(158, 166, 184);
	font-size: 40rpx;
	border-radius: 15rpx;
	color: #ffffff;
	margin-top: 80rpx;
}
.inputU{
	border: 1px solid #ffffff;
	border-radius: 10rpx;
	width: 400rpx;
	height: 70rpx;
	text-indent: 10rpx;
	margin: 30rpx auto;
	font-size: 34rpx;
	color: #ffffff;
}
.textStyle{
	font-size: 30rpx;
}
</style>
