<template>
	<view class="page" :style="{'min-height':h+'px', 'padding-top':mt+'px'}">
		<u-navbar title="创衡正念企业教练" bgColor="transparent" :titleStyle="{'font-size':'32rpx','font-weight':'bold'}">
			<view class="u-nav-slot" slot="left" style="display: flex;background-color: transparent;">
				<image src="https://transcend.ringzle.com/xiaozhi-app/profile/2025/06/16/ef50e3e8-d0f9-41dd-a4ec-546b157a1de9.png" style="width: 45rpx;height: 45rpx;" @tap="toBack"></image>
				<image src="https://transcend.ringzle.com/xiaozhi-app/profile/2025/06/16/e536bf8e-3b33-4ea8-b60b-7154c6353bec.png" style="width: 42rpx;height: 42rpx;margin-left: 40rpx;" @tap="startNewDialog"></image>
			</view>
		</u-navbar>
		<template v-if="dialogList.length===0">
			<div class="welcome">
				<image src="https://transcend.ringzle.com/xiaozhi-app/profile/2025/06/16/5292af4c-977b-4620-a4e4-4aadcd5ad092.png"></image>
				<p>Hi，我是你的AI团队教练助手～</p>
				<p class="tip">任何关于团队、分析报告、教练的问题，你都可以向我提问。我正在快速学习和进化中，有新功能时，我一定第一时间告诉你～ </p>
			</div>
		</template>
		<template v-else>
			<div class="dialogs container" ref="messageContainer">
				<div class="d_answer init">
					<div class="da_top adfac">
						<image src="@/static/logo.png"></image>
						<text>创衡正念企业教练</text>
					</div>
					<div class="da_content">Hi，任何关于团队、分析报告、教练的问题，你都可以向我提问～</div>
				</div>
				<div v-for="(item,index) in dialogList" :key="index">
					<div class="d_question">
						<div class="dq_text">{{ item.question }}</div>
					</div>
					<div class="d_answer">
						<div class="da_top adfac">
							<image src="@/static/logo.png"></image>
							<text>创衡正念企业教练</text>
						</div>
						<div class="da_content">
							<u-parse :content="item.answer"></u-parse>
							<div class="dc_btns adfacjb" v-if="item.answer">
								<div class="db_l">
									<image :src="item.copy?require('@/static/copy_active.png'):require('@/static/copy.png')" @tap="toCopy(item,index)"></image>
									<image :src="item.upvote?require('@/static/upvote_active.png'):require('@/static/upvote.png')" @tap="toUpvote(item,index)"></image>
									<image :src="item.comment?require('@/static/comment_active.png'):require('@/static/comment.png')" @tap="toComment(item,index)"></image>
								</div>
								<div class="db_r">
									<image :src="item.share?require('@/static/share_active.png'):require('@/static/share.png')" @tap="toShare(item,index)"></image>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</template>
		<div class="ask">
			<div class="a_inp">
				<u-textarea v-model="question" placeholder="请输入您的问题" autoHeight @confirm="sendQuestion"></u-textarea>
			</div>
			<div class="a_btn adfacjb">
				<div class="ab_l adfac">
					<div class="al_pre adfacjc">
						<image src="https://transcend.ringzle.com/xiaozhi-app/profile/2025/06/16/451ac13c-5fdc-4d15-8f35-9f4d238e87c1.png"></image>
						<text>创衡增强</text>
					</div>
					<div class="al_pre adfacjc">
						<image src="https://transcend.ringzle.com/xiaozhi-app/profile/2025/06/16/d4668dcc-1d28-47ff-8bae-84dc6475794b.png"></image>
						<text>联网搜索</text>
					</div>
				</div>
				<div class="ab_r">
					<image src="https://transcend.ringzle.com/xiaozhi-app/profile/2025/06/16/caf6075c-0967-4c99-a269-ea453537075c.png"></image>
					<image @tap="sendQuestion" src="https://transcend.ringzle.com/xiaozhi-app/profile/2025/06/16/2429556b-54b7-4878-97c0-6b440b546ee4.png"></image>
				</div>
			</div>
		</div>
		<u-modal :show="commentShow" title="评论" @confirm="commentConfirm" @cancel="commentCancel" @close="commentCancel" :showCancelButton="true">
			<u-textarea v-model="content" placeholder="对于我们的回答您是否不满意，您有更好的答案建议吗？请在此输入."></u-textarea>
		</u-modal>
	</view>
</template>

<script>
	var timer = null;
	let requestTask = null;
	import { BaseApi } from '../http/baseApi.js'
	import * as TextEncoding from "text-encoding-shim";
	export default {
		data(){
			return {
				isDialog:false,
				retryCount: 3, // 最大重试次数
				currentRetry: 0, // 当前重试次数
				isRequesting: false, // 请求状态锁
				question:'',
				streamingResponse:'',
				receivedData:'',
				dialogList:[],
				windex:0,
				commentShow:false,
				content:'',
				cindex:'',
			}
		},
		methods:{
			toBack(){
				uni.reLaunch({
					url:'/pages/home'
				})
			},
			startNewDialog(){
				clearInterval(timer)
				this.dialogList = [];
				this.question = '';
				this.streamingResponse = '';
			},
			// 封装带重试机制的请求方法
			async sendRequestWithRetry() {
				if (this.isRequesting) return;
				this.isRequesting = true;
				this.currentRetry = 0;
				try {
					await this._executeRequest();
				} catch (error) {
					  this.$showToast('请求失败，请稍后重试')
				} finally {
					this.isRequesting = false;
				}
			},
			// 实际执行请求的方法
			_executeRequest() {
				return new Promise((resolve, reject) => {
					requestTask = uni.request({
						url: `${BaseApi}/core/chat/messages`,
						method: 'POST',
						timeout: 10000,
						data:{ 
							query: this.question,
							timestamp:Date.now()
						},
						header: {
						  'Content-Type': 'application/json',
						  'token': uni.getStorageSync('token') || ''
						},
						enableChunked: true, // 启用流式接收
						responseType:'text',
						success: (res) => {
							if (res.statusCode === 200) {
								this._handleSuccess(res.data);
								resolve();
							} else {
								this._handleError(`状态码异常: ${res.statusCode}`, resolve, reject);
							}
						},
						fail: (err) => {
							this._handleError(err.errMsg, resolve, reject);
						},
						complete: (com) => {
							console.log('请求完成',com)
						}
					});
					
					requestTask.onChunkReceived(async (res) => {
						const uint8Array = new Uint8Array(res.data);
						const decoder = new TextEncoding.TextDecoder("utf-8");
						const decodedString = decoder.decode(uint8Array);
						try {
							let newtext = decodedString.replaceAll('data:','')
							let ntArr = newtext.split(/\s+/);
							if(ntArr.length){
								ntArr.forEach(n=>{
									if(!n.trim()) return
									let nj = JSON.parse(n);
									if(nj.event=='agent_message'){
										let answer = this.dialogList[this.dialogList.length-1].answer+nj.answer;
										this.$set(this.dialogList[this.dialogList.length-1],'answer',answer);
										this.$set(this.dialogList[this.dialogList.length-1],'id',nj.id);
										this.$set(this.dialogList[this.dialogList.length-1],'task_id',nj.task_id);
										this.$set(this.dialogList[this.dialogList.length-1],'message_id',nj.message_id);
										this.$set(this.dialogList[this.dialogList.length-1],'conversation_id',nj.conversation_id);
										uni.pageScrollTo({ scrollTop: 99999, duration: 300});
									}
								})
							}
						} catch (e) {
							console.error('解析失败', e, '原始数据:', decodedString);
						}
					});
				});
			},
			// 成功处理
			_handleSuccess(data) {
				if (data) {
				  this.streamingResponse += data;
				}
				this.currentRetry = 0; // 重置重试计数器
			},
			// 错误处理
			_handleError(errorMsg, resolve, reject) {
				if (this._shouldRetry(errorMsg)) {
					this.currentRetry++;
					setTimeout(() => {
						this._executeRequest().then(resolve).catch(reject);
					}, this._getRetryDelay());
				} else {
					reject(errorMsg);
				}
			},
			// 判断是否需要重试
			_shouldRetry(errorMsg) {
				const retryableErrors = [
					'timeout', 
					'request:fail', 
					'Network Error'
				];
				return this.currentRetry < this.retryCount && retryableErrors.some(e => errorMsg.includes(e));
			},
			// 获取指数退避延迟时间
			_getRetryDelay() {
				return Math.min(1000 * Math.pow(2, this.currentRetry), 10000);
			},
			sendQuestion(){
				if(!this.question) return this.$showToast('请输入您的问题');
				let qa = {
					question:JSON.parse(JSON.stringify(this.question)),
					answer:'',
					copy:false,
					upvote:false,
					comment:'',
					share:false,
				}
				this.dialogList = [...this.dialogList,...[qa]];
				this.$nextTick(()=>{
					uni.pageScrollTo({ scrollTop: 99999, duration: 300});
					this.sendRequestWithRetry();
					this.question = '';
				})
			},
			toCopy(item,index){
				uni.setClipboardData({
					data:item.answer,
					success: (res) => {
						this.$showToast('复制成功');
					},
					fail: (err) => {
						this.$showToast('复制失败');
					}
				})
			},
			toUpvote(item,index){
				this.$set(this.dialogList[index],'upvote',!this.dialogList[index].upvote);
			},
			toComment(item,index){
				this.cindex = index;
				this.commentShow = true;
			},
			toShare(item,index){
				this.$set(this.dialogList[index],'share',!this.dialogList[index].share);
			},
			commentConfirm(){
				this.$set(this.dialogList[this.cindex],'comment',this.content);
				this.commentShow = false;
			},
			commentCancel(){
				this.content = '';
				this.commentShow = false;
			},
		}
	}
</script>

<style scoped lang="scss">
	::v-deep .u-textarea{
		border: none !important;
		padding: 0 !important;
	}
	::v-deep .u-textarea textarea{
		min-height: 96rpx !important;
	}
	
	.page{
		background: linear-gradient( 227deg, #EEEFF8 0%, #F6ECF4 100%, #F6ECF4 100%);
		padding: 0 30rpx 302rpx;
		box-sizing: border-box;
		
		.welcome{
			margin-top: 259rpx;
			padding: 0 34rpx;
			image{
				width: 88rpx;
				height: 87rpx;
				margin-left: 20rpx;
			}
			p{
				font-family: PingFang-SC, PingFang-SC;
				font-weight: bold;
				font-size: 36rpx;
				color: #252525;
				line-height: 36rpx;
				margin-top: 36rpx;
				&.tip{
					font-family: PingFangSC, PingFang SC;
					font-weight: 400;
					font-size: 26rpx;
					color: #646464;
					line-height: 40rpx;
					margin-top: 20rpx;
				}
			}
		}
	
		.dialogs{
			width: 100%;
			height: calc(100vh - 282rpx);
			padding-top: 34rpx;
			box-sizing: border-box;
			overflow-y: auto;
			.d_answer{
				margin-top: 40rpx;
				&.init{
					margin-top: 0;
				}
				.da_top{
					image{
						width: 48rpx;
						height: 48rpx;
					}
					text{
						font-family: PingFang-SC, PingFang-SC;
						font-weight: bold;
						font-size: 30rpx;
						color: #505050;
						line-height: 48rpx;
						margin-left: 20rpx;
					}
				}
				.da_content{
					padding: 30rpx 32rpx;
					margin-top: 20rpx;
					background: #FFFFFF;
					border-radius: 4rpx 24rpx 24rpx 24rpx;
					.dc_btns{
						margin-top: 44rpx;
						image{
							width: 48rpx;
							height: 48rpx;
						}
						.db_l{
							image{
								margin-right: 40rpx;
							}
						}
					}
				}
			}
			.d_question{
				margin-top: 40rpx;
				display: flex;
				justify-content: flex-end;
				.dq_text{
					background: #833478;
					border-radius: 24rpx 4rpx 24rpx 24rpx;
					font-family: PingFangSC, PingFang SC;
					font-weight: 400;
					font-size: 30rpx;
					color: #FFFFFF;
					line-height: 48rpx;
					text-align: right;
					padding: 26rpx 30rpx;
				}
			}
		}
	
		.ask{
			width: calc(100% - 60rpx);
			height: 210rpx;
			background: #FFFFFF;
			border-radius: 24rpx;
			border: 2rpx solid #F0F2F8;
			position: fixed;
			left: 30rpx;
			bottom: 72rpx;
			display: flex;
			flex-direction: column;
			padding: 24rpx;
			box-sizing: border-box;
			.a_inp{
				flex: 1;
				overflow-y: auto;
			}
			.a_btn{
				padding-top: 20rpx;
				height: 54rpx;
				.ab_l{
					.al_pre{
						width: 162rpx;
						height: 54rpx;
						background: #FFFFFF;
						border-radius: 27rpx;
						border: 1rpx solid #E0E0E0;
						margin-right: 24rpx;
						image{
							width: 24rpx;
							height: 24rpx;
						}
						text{
							font-family: PingFangSC, PingFang SC;
							font-weight: 400;
							font-size: 22rpx;
							color: #393939;
							line-height: 22rpx;
							margin-left: 10rpx;
						}
					}
				}
				.ab_r{
					image{
						width: 48rpx;
						height: 48rpx;
						margin-left: 30rpx;
					}
				}
			}
		}
	}
</style>