<template>
	<view class="page" :style="{'min-height':h+'px', 'padding-top':mt+'px', 'padding-bottom': 'calc(240rpx + ' + fixBottom + 'px)'}">
		<cus-header title='对报告提问' bgColor="#E9F4F6"></cus-header>
		<view class="dialogs container" ref="messageContainer">
			<view class="d_pdf">
				<view class="dp_box">
					<view class="dq_text">{{ fileName||'' }}</view>
					<view class="dp_type adfac">
						<image src="@/static/pdf.png"></image>
						<span>PDF</span>
					</view>
				</view>
			</view>
			<view v-for="(item,index) in dialogList" :key="index">
				<view class="d_question">
					<view class="dq_text">{{ item.question }}</view>
				</view>
				<view class="d_answer">
					<view class="da_top adfac">
						<image src="@/static/logo.png"></image>
						<text>大创教练</text>
					</view>
					<view class="da_content">
						<template v-if="item.think">
							<view class="dac_think adfac">
								<image src="https://oss.familydaf.cn/sxsnfile/20260129/ce681f9923134f5bbf43654234e15367.gif"></image>
								<text v-if="!item.fail">让我思考一下，请稍等～</text>
								<text v-else>{{item.errMsg}}</text>
							</view>
						</template>
						<template v-else>
							<view style="font-size: 30rpx;color: #002846;line-height: 54rpx;">
								<u-parse :content="item.answer"></u-parse>
							</view>
						</template>
						<view class="dc_btns adfacjb" v-if="item.answer">
							<view 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> -->
							</view>
							<view class="db_r">
								<!-- <image :src="item.share?require('@/static/share_active.png'):require('@/static/share.png')" @tap="toShare(item,index)"></image> -->
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="ask_box" :style="{'bottom':fixBottom+'px'}">
			<view class="ask">
				<view class="a_inp">
					<view class="ai_l">
						<u-textarea v-model="question" placeholder="请输入你的问题" placeholder-style="font-size:30rpx;color:#95A5B1;" @confirm="sendQuestion" autoHeight :showConfirmBar="false" :adjustPosition="false" maxlength="999999"></u-textarea>
					</view>
					<view class="ai_r">
						<image @tap="sendQuestion" :src="imgBase+'dialog_send.png'"></image>
					</view>
				</view>
			</view>
			<view class="ask_memo">本服务为AI生成内容，结果仅供参考</view>
		</view>
		<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 {
				pdfUrl:'',
				fileName:'',
				retryCount: 3, // 最大重试次数
				currentRetry: 0, // 当前重试次数
				isRequesting: false, // 请求状态锁
				question:'',
				conversation_id:'',
				dialogList:[],
				streamingResponse:'',
				receivedData:'',
				windex:0,
				commentShow:false,
				content:'',
				cindex:'',
				fixBottom: 0
			}
		},
		onLoad(option) {
			this.pdfUrl = option.pdfUrl;
			this.fileName = option.fileName;
		},
		onReady() {
		    uni.onKeyboardHeightChange(res => {
		      this.fixBottom = res.height||0;
			  if(this.fixBottom>0){
				  this.scrollToBottom()
			  }
		    });
		},
		onUnload() {
		    uni.offKeyboardHeightChange();
			this.fixBottom = 0;
		},
		methods:{
			// 封装带重试机制的请求方法
			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/sendChatMessageStream`,
						method: 'POST',
						timeout: 20000,
						data:{ 
							query: this.question,
							identity:'被教练者',
							conversation_id: this.conversation_id,
							report:this.pdfUrl
						},
						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) => {
							// if(err.errMsg.indexOf('time out')>-1||err.errMsg.indexOf('timeout')>-1) this.$showToast('请求超时，请稍后再试')
							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);
						if(decodedString.indexOf('"code":500')>-1){
							this.$set(this.dialogList[this.dialogList.length-1],'fail',true);
							const dsJson = JSON.parse(decodedString);
							this.$set(this.dialogList[this.dialogList.length-1],'errMsg',dsJson?(dsJson.msg||'很抱歉，当前网络异常，请稍后再试~'):'很抱歉，当前网络异常，请稍后再试~');
						}
						try {
							let newtext = decodedString.replaceAll('data:','').replaceAll(':keepAlive','');
							let ntArr = newtext.split('\n\n');
							if(ntArr.length){
								ntArr.forEach(n=>{
									if(!n.trim()) return
									let nj = JSON.parse(n);
									if(nj.event=='message'){
										this.conversation_id = nj.conversation_id;
										let answer = this.dialogList[this.dialogList.length-1].answer+nj.answer?.replace(/(\r\n|\n|\r)+/g, '<br>').replace(/<think>.*?<\/think>/gs, '');
										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);
										this.$set(this.dialogList[this.dialogList.length-1],'think',false);
										this.$set(this.dialogList[this.dialogList.length-1],'fail',false);
										this.$set(this.dialogList[this.dialogList.length-1],'errMsg','');
									}
								})
								setTimeout(()=>{
									this.scrollToBottom();
								},100)
							}
						} 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,
					think:true,
					fail:false,
					errMsg:''
				}
				this.dialogList = [...this.dialogList,...[qa]];
				this.$nextTick(()=>{
					this.scrollToBottom();
					this.sendRequestWithRetry();
					this.question = '';
				})
			},
			// 滚动到底部
			scrollToBottom() {
				this.$nextTick(()=>{
					this.$nextTick(()=>{
						uni.pageScrollTo({
							scrollTop:99999,
							duration:300
						})
					})
				})
			},
			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: 64rpx !important;
	}
	
	.page{
		background: url('https://gitee.com/hw_0302/chuang-heng-wechat-images/raw/master/dialog_bg.png') no-repeat;
		background-size: 100% 100%;
		padding: 0 30rpx 240rpx;
		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%;
			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;
					.dac_think{
						image{
							width: 48rpx;
							height: 48rpx;
						}
						text{
							font-family: PingFangSC, PingFang SC;
							font-weight: 400;
							font-size: 28rpx;
							color: #002846;
							line-height: 54rpx;
							margin-left: 20rpx;
						}
					}
					.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: #33A7A7;
					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;
				}
			}
			
			.d_pdf{
				margin-top: 20rpx;
				display: flex;
				justify-content: flex-end;
				.dp_box{
					width: 364rpx;
					background: #FFFFFF;
					border-radius: 16rpx;
					border: 1rpx solid #F0F2F8;
					padding: 27rpx 21rpx;
					.dq_text{
						background: #FFFFFF;
						font-family: PingFang-SC, PingFang-SC;
						font-weight: bold;
						font-size: 26rpx;
						color: #252525;
						line-height: 37rpx;
					}
					.dp_type{
						margin-top: 15rpx;
						image{
							width: 25rpx;
							height: 30rpx;
						}
						span{
							font-family: PingFang-SC, PingFang-SC;
							font-weight: bold;
							font-size: 24rpx;
							color: #999999;
							line-height: 33rpx;
							margin-left: 5rpx;
						}
					}
				}
			}
		}
	
		.ask_box{
			width: 100%;
			min-height: 176rpx;
			padding: 0 30rpx 60rpx;
			position: fixed;
			left: 0;
			box-sizing: border-box;
			background: #F6F6F6;
			
			.ask_memo{
				font-family: PingFangSC, PingFang SC;
				font-weight: 400;
				font-size: 24rpx;
				color: #b1b1b1;
				line-height: 34rpx;
				text-align: center;
				margin-top: 16rpx;
			}
		}
	
		.ask{
			min-height: 116rpx;
			background: #FFFFFF;
			border-radius: 24rpx;
			border: 2rpx solid #F0F2F8;
			padding: 24rpx;
			box-sizing: border-box;
			.a_inp{
				display: flex;
				align-items: flex-end;
				max-height: 300rpx;
				overflow-y: auto;
				.ai_l{
					width: calc(100% - 64rpx);
					padding-right: 20rpx;
					box-sizing: border-box;
				}
				.ai_r{
					width: 64rpx;
					image{
						width: 64rpx;
						height: 64rpx;
					}
				}
			}
		}
	}
</style>