<template>
	<!-- <view style="padding-bottom: 248rpx;"> -->
	<view style="">
		<!-- #ifdef H5 -->
		<view style="color: #000;">
			<tn-nav-bar backgroundColor="#fff">GPT</tn-nav-bar>
			<view :style="{ height: tobheight + 'px' }"></view>
		</view>
		<!-- #endif -->

		<view class="content" @touchmove="touchmove">
			<view class="msg-list">

				<!-- 顶部切换模型内容块 -->
				<view class="row">
					<block>
						<view class="other">
							<view class="left" v-if="true" @click="">
								<u-image
									src="https://dev.iduomi.cc/addons/wike_chatgpt/public/static/storage/presets/mode/1.png"
									mode="widthFix" radius="5" width="40" height="40"></u-image>
							</view>
							<view class="right">
								<view class="username">
									<view class="name"></view>
									<view class="time">'ai问答机器人</view>
								</view>
								<view class="bubble">
									<view class="content">
										<view style="font-size: 32rpx;">我是您的AI助手，您可以向我提出任何问题~</view>
									</view>
								</view>
							</view>
						</view>
					</block>
				</view>



				<block v-for="(row, index) in talkList" :key="index" :id="'msg' + row.id">
					<view class="row">
						<block>
							<view class="my" v-if="row.fromid==1">
								<view class="left">
									<view class="username">
										<view class="name">{{ row.nickname }}</view>
									</view>
									<u-icon v-if="row.content !='该问题已被隐藏!'" @click="copyText(index)" name="file-text"
										color="#9e9e9e82" size="22"></u-icon>

									<view v-if="row.type == 1" class="bubble" style="color: #fff;margin-left: 15rpx;">
										<rich-text :nodes="row.content" @longtap="copy" :data-text="row.content"
											selectable="true"></rich-text>
									</view>

								</view>
								<view class="right">
									<u-image :src="row.avatar?row.avatar:'/static/images/head.jpg'" mode="widthFix"
										radius="5" width="42" height="42"></u-image>
								</view>
							</view>

							<!-- GPT -->
							<view class="other" v-if="row.fromid==-1">
								<view class="left" v-if="true" @click="">
									<u-image
										src="https://dev.iduomi.cc/addons/wike_chatgpt/public/static/storage/presets/mode/1.png"
										mode="widthFix" radius="5" width="42" height="42"></u-image>
								</view>

								<view class="right">
									<view class="username" v-if="true">
										<view class="name"></view>
										<view class="time">{{row.nickname}}</view>
									</view>

									<view v-if="row.type == 1" class="bubble"
										style="display: block;position: relative;">
										<view>
											<zero-markdown-view v-if="row.done" :themeColor="themeColor"
												:markdown="row.content"></zero-markdown-view>

											<text v-else @longtap="copy"
												:data-text="row.content">{{ row.content.replace(/^\s+|\s+$/g, '') }}</text>

											<!-- <text v-if="row.content == '正在思考中...'">{{ second }}s</text> -->

											<text class="flash" v-if="row.show_flash">│</text>
										</view>
									</view>


									<view v-if="row.done" class="tn-flex align-center justify-between operate">
										<view @click="copyText(index)" hover-class="hoversubmit"
											class="tn-flex align-center">
											<u-icon name="file-text" top="1" color="#68d7bb" size="20"></u-icon>
											<view class="duplicate">复制回答</view>
										</view>
									</view>

								</view>
							</view>
						</block>
					</view>
				</block>
			</view>
			<view class="bottomheight"></view>
			<view class="env"></view>
		</view>
		<view class="box-2">
			<view class="flex_col">
				<view class="flex_grow">
					<u--textarea height="45" @blur="blurinput" @focus="focusinput" fixed :showConfirmBar="false"
						v-model="content" placeholder="请输入您的问题..." maxlength="-1" border="none"
						:cursorSpacing="80"></u--textarea>
				</view>
				<button class="send" @click.prevent="send(content)">发送</button>
			</view>
		</view>


		<!-- 	<button @click="test">测试发送</button> -->

		<!-- <wike-skeleton count="4" type="user" v-if="true"></wike-skeleton> -->

		<u-no-network></u-no-network>
		<!-- <wike-loading-page :isLoading="isLoading"></wike-loading-page> -->
	</view>
</template>

<script>
	import {
		sendGpt
	} from '@/api/public/index.js';
	import {
		Socket
	} from 'dgram';
	import {
		mapMutations,
		mapActions,
		mapState,
		mapGetters
	} from 'vuex';
	import {
		apiurl
	} from '@/common/request/request';
	import MumuRecorder from '@/uni_modules/mumu-recorder/components/mumu-recorder/mumu-recorder.vue';
	import eliseAudio from '@/components/elise-audio/elise-audio.vue';

	import {
		userInfo
	} from '@/api/my/index.js'
	// #ifdef H5
	import Recorder from 'recorder-core';
	import 'recorder-core/src/engine/wav'
	import {
		log
	} from 'util';
	import {
		clearTimeout
	} from 'timers';


	// #endif

	let down, delay;
	let interstitialAd = null,
		timer,
		time2,
		timingr;
	// const innerAudioContext = uni.createInnerAudioContext();
	const recorderManager = uni.getRecorderManager();
	export default {
		components: {
			MumuRecorder,
			eliseAudio,
			// #ifdef H5
			Recorder
			// #endif
		},
		data() {
			return {
				templateQuestionList: [
					'给产品经理的一些建议',
					'讲一个冷笑话'
				],

				gpt_mode_index: 0,
				talkList: [],
				content: '',
				thecontent: '',
				image: '',
				hot: [],
				scrollTop: 999999,
				scrollAnimation: false,
				text1: ['您好，ChatGPT为您服务', '长按对话即可复制'],
				tobheight: 45,
				zhuangtai: 'AI智能问答机器人',
				platform: this.$platform.get(),
				// isFlash:false,
				showPoster: false,
				posterObj: {},
				switchmodel: false,
				selectornot: 0,
				modeldata: [],
				qrcode: '',
				haddressurl: '',
				haddresssk: '',
				scrollToView: '',
				question_index: 0,
				answer_index: 0,
				themeColor: '#007AFF',
				codeBgColor: '#26B3A0',
				showexpand: false,

				second: 15,
				showanswer: false,
				h5question: '',
				followornot: true,
				eights: false,
				spmplatform: 0,
				is_commission: 0,
				timing: 30,
				showcontext: true,
				showfetch: true,
				showdirect: true,
				//通道
				thoroughfare: 0,

				//绘画输入框
				drawcontent: '',
				//绘画模式
				paintingmode: false,
				//是否在绘画
				showdraw: false,
				//绘画id
				uuid: '',
				//绘画列表
				paintinglist: [],

				//弹出录音
				soundrecording: false,
				//是否长按
				showlongpress: false,
				//音频
				innerAudioContextsrc: '',
				//取消音频加载
				cancel: false,
				//第一次录
				firstrecording: 0,
				isLoading: true,

				timer: null,


				userInfo: {},

				freeCount: 5
			};
		},
		computed: {
			...mapGetters(['appInfo', 'hasLogin', 'userInfo', 'homeTemplate', 'userData'])
		},
		mounted() {

		},
		onReady() {

		},

		async onLoad() {
			if (uni.getStorageSync('token')) {
				this.freeCount = 99999
			}



			let res = await userInfo()
			console.log('gpt页用户个人信息返回值', res);
			if (res.code == 0) {
				this.userInfo = res.data
			}



			var that = this;
			if (this.$Route.query.question) {
				this.h5question = this.$Route.query.question;
				// this.aigetAddress();
			}


			this.spmplatform = ['H5', 'wxOfficialAccount', 'wxMiniProgram', 'App'].indexOf(this.platform) + 1;
			this.followornot = true;
			// #ifdef H5
			this.toaigetAddress();
			// #endif
			this.isLoading = false
			this.initGpt();
			this.getCommissionSetting()
			this.onmessage();
			uni.onSocketError(function(res) {});
		},
		onShow: function() {

		},
		onUnload() {
			this.followornot = false
			uni.$emit('stop')
		},
		onHide() {

		},
		onReachBottom() {},
		methods: {
			test() {
				let url = 'http://t20.9026.com/api/chat/send'
				fetch(url, {
					method: 'POST',
					headers: {
						'Content-Type': 'application/json'
					},
					body: JSON.stringify({
						message: '帮我写一个数组去重的代码'
						// message:'中国的首都是'
					})
				}).then(async (resp) => {
					console.log('回复内容返回值', resp);
					if (resp.staus > 300 && resp.staus < 200) {


					} else {
						const msg = await resp.text()
						console.log('回复内容', JSON.parse(msg).data);

					}
				}).catch((err) => {
					console.log('请求失败2-------', err);
				})




				// console.log(resp.body);

				// const reader=resp.body.getReader()

				// const textDecoder=new TextDecoder()
				// while(1){
				// 	const {done,value}	=await reader.read()
				// 	if(done){
				// 		break
				// 	}
				// 	const str=JSON.parse(textDecoder.decode(value)).data  
				// 	console.log('strs.....',str);
				// }

			},



			handleEnter(e) {
				console.log('111111111111111111111111111111111111111111111');
			},



			...mapActions(['getUserInfo', 'showAuthModal', 'getUserData']),

			touchmove() {
				this.followornot = false;
			},
			getCommissionSetting() {
				this.$http('conf.getGroupConf', {
					group: 'system.commission'
				}).then(res => {
					if (res.code == 0) {
						this.is_commission = res.data.is_commission
					}
				});
			},




			aigetAddress() {
				this.send(this.h5question);
			},



			copy(e) {
				var that = this;
				var text = e.currentTarget.dataset.text;
				uni.setClipboardData({
					data: text,
					success(res) {
						uni.getClipboardData({
							success(res) {}
						});
					}
				});
			},
			changeinput(e) {},
			focusinput() {
				this.showexpand = false;
				this.$nextTick(() => {
					uni.pageScrollTo({
						scrollTop: 9999,
						duration: 300
					});
				});
			},
			blurinput() {
				// this.showexpand = true;
			},
			commontemplate() {
				this.$store.dispatch('getTemplate');
			},
			//敏感词过滤检测
			getcheckText() {
				var that = this;
				return new Promise((resolve, reject) => {
					that.$http('ai.checkText', {
						prompt: that.thecontent
					}).then(res => {
						if (res.code == 0) {
							resolve(1);
						} else {
							let data = {
								id: new Date().getTime(),
								content: '该问题已被隐藏!',
								type: 1,
								toid: that.toid,
								fromid: that.userInfo.id,
								avatar: that.userInfo.avatar,
								nickname: that.userInfo.nickname,
								done: true
							};
							that.talkList.push(data);
							let chat_data = {
								id: new Date().getTime(),
								content: res.msg,
								type: 1,
								toid: this.toid,
								fromid: -1,
								avatar: this.homeTemplate.mode[this.selectornot]
									.img_file.path,
								nickname: this.homeTemplate.mode[this.selectornot]
									.name,
								show_flash: false,
								done: true,
								donec: true
							};
							this.talkList.push(chat_data);
							this.$nextTick(() => {
								// 清空内容框中的内容
								this.content = '';
								uni.pageScrollTo({
									scrollTop: 9999,
									duration: 300
								});
							});
						}
					})
				});
			},
			// 发送信息
			async send(e) {
				if (this.freeCount <= 0) {
					uni.showToast({
						title: '抱歉，您的免费次数(5次)已用完！',
						icon: 'none'
					});
					return;
				}


				let that = this;
				if (that.talkList.length > 1 && !that.talkList[that.talkList.length - 1].done) {
					uni.showToast({
						title: '正在输入回答,请等待输入完成',
						icon: 'none'
					});
					return;
				}
				if (!e) {
					uni.showToast({
						title: '请输入有效的内容',
						icon: 'none'
					});
					return;
				}
				this.thecontent = e;
				// console.log('提问内容检测');
				uni.showLoading({})
				uni.hideLoading();
				// 将当前发送信息 添加到消息列表。
				let data = {
					id: new Date().getTime(),
					content: e,
					type: 1,
					toid: 666,
					fromid: 1,
					avatar: this.userInfo.avatar,
					nickname: '我',
					done: true
				};
				this.talkList.push(data);

				let chat_data = {
					id: new Date().getTime(),
					content: '正在思考中...',
					type: 1,
					toid: 666,
					fromid: -1,
					avatar: 'https://nywhcm.com/addons/wike_aging/public/static/storage/presets/mode/1.png',
					nickname: '小助手',

					show_flash: true,
					done: false
				};
				this.talkList.push(chat_data);
				this.$nextTick(() => {
					// 清空内容框中的内容
					this.content = '';
					uni.pageScrollTo({
						scrollTop: 99999,
						duration: 300
					});
				});

				// 重置是否来数据的判断
				this.showanswer = false;
				// this.show_flash = true;
				// 允许跟随到最底部
				this.followornot = true;

				// 方案一
				// 	that.timer=setTimeout(()=>{
				// 	that.talkList[that.talkList.length-1].done=true
				// 	that.talkList[that.talkList.length-1].show_flash=false
				// 	that.talkList[that.talkList.length-1].content='本次提问出错/超时,请重新提问'
				// 	uni.showToast({
				// 		title:'本次提问出错/超时,请重新提问',
				// 		icon:'none'
				// 	})
				// },60000)

				let url = 'http://t20.9026.com/api/chat/send'
				fetch(url, {
					method: 'POST',
					headers: {
						'Content-Type': 'application/json'
					},
					body: JSON.stringify({
						// message:'介绍一下思维定制'
						message: that.thecontent
					})
				}).then(async (resp) => {
					let result = await resp.text()
					const res = JSON.parse(result)
					if ((resp.status >= 200 && resp.status < 300) && res.code == 0) {
						that.talkList[that.talkList.length - 1].done = true
						that.talkList[that.talkList.length - 1].show_flash = false
						that.talkList[that.talkList.length - 1].content = res.data
						that.$nextTick(() => {
							uni.pageScrollTo({
								scrollTop: 9999,
								duration: 1000
							});
						})
						that.freeCount--
						console.log('游客剩余提问次数', that.freeCount)



						// 此处发送记录问答记录的请求
						console.log('每次记录问答参数', {
							ques_content: that.talkList[that.talkList.length - 2].content,
							ai_aswerContent: that.talkList[that.talkList.length - 1].content
						})
						// let res = await writeLog({
						// 	ques_content: that.talkList[that.talkList.length - 2].content,
						// 	ai_aswerContent: that.talkList[that.talkList.length - 1].content
						// })
						// if (res.code == 0) {
						// 	console.log('记录问答记录成功');
						// }


					} else {
						that.talkList[that.talkList.length - 1].done = true
						that.talkList[that.talkList.length - 1].show_flash = false
						that.talkList[that.talkList.length - 1].content = '本次提问由于网络超时出错啦,请稍后重新提问'
						uni.showToast({
							title: '本次提问由于网络超时出错啦,请稍后重新提问',
							icon: 'none'
						})

					}
				}).catch((err) => {
					that.talkList[that.talkList.length - 1].done = true
					that.talkList[that.talkList.length - 1].show_flash = false
					that.talkList[that.talkList.length - 1].content = '本次提问由于网络超时出错啦,请稍后重新提问'
					uni.showToast({
						title: '本次提问由于网络超时出错啦,请稍后重新提问',
						icon: 'none'
					})
				})

				// 方案二	
				// 	that.timer=setTimeout(()=>{
				// 	that.talkList[that.talkList.length-1].done=true
				// 	that.talkList[that.talkList.length-1].show_flash=false
				// 	that.talkList[that.talkList.length-1].content='本次提问出错/超时,请重新提问'
				// 	uni.showToast({
				// 		title:'本次提问出错/超时,请重新提问',
				// 		icon:'none'
				// 	})
				// },60000)
				// 	let res=await sendGpt({
				// 		message:that.thecontent
				// 	})

				// 	console.log('gpt返回值',res);
				// 	if(res.code==0){
				// 		 clearInterval(that.timer);
				// 		that.timer = null;

				// 		that.talkList[that.talkList.length-1].done=true
				// 		that.talkList[that.talkList.length-1].show_flash=false
				// 		that.talkList[that.talkList.length-1].content=res.data
				// 		this.$nextTick(()=>{
				// 			uni.pageScrollTo({
				// 				scrollTop: 9999,
				// 				duration: 1000
				// 			});
				// 		})
				// 		console.log('最新的消息列表数据',that.talkList);

				// 	}		
			},



			//fetch模式
			fetchmodel(e) {
				// console.log('走方案2');
				var that = this;
				let i = 1,
					message = '';
				let answer = '';
				that.thoroughfare = 2;
				this.question_index = that.talkList.length - 1;
				this.answer_index = that.talkList.length - 2;
				if (that.talkList.length > 2 && that.showcontext) {
					answer = that.talkList[that.question_index - 2].content;
				}

				let param = {
					max_tokens: 3000,
					model: 'gpt-3.5-turbo-0301',
					stream: true,
					messages: [{
							role: 'assistant',
							content: answer
						},
						{
							role: 'system',
							content: that.homeTemplate.mode[that.selectornot].guide
						},
						{
							role: 'user',
							content: e
						}
					]
				};
				let headers = {};
				if (that.appInfo.connect_lines == 2) {
					headers = {
						'Content-Type': 'application/json',
						Authorization: 'Bearer' + ' ' + that.haddresssk
					}
				}
				// console.log(that.haddressurl,headers,param,that.appInfo.connect_lines);
				fetch(that.haddressurl, {
						method: 'POST',
						body: JSON.stringify(param),
						headers: headers
					})
					.then(x => {
						if (x.status === 200) return x.body;
						throw x;
					})
					.then(x => {
						const k = x.getReader();

						return new ReadableStream({
							start(V) {
								function F() {
									k.read().then(({
										done: E,
										value: U
									}) => {

										that.showanswer = true;
										if (E) {
											// console.log('done', E)
											// , V.close();
											that.timing = that.appInfo
												.text_expire_time ? Number(that
													.appInfo.text_expire_time) : 30;
											that.showcontext = true;
											that.getcontext();
											that.record(that.talkList[that
													.answer_index].content,
												message);
											that.talkList[that.question_index]
												.show_flash = false;
											that.talkList[that.question_index].done =
												true;
											that.getUserData();
											if (that.followornot) {
												uni.pageScrollTo({
													scrollTop: 9999,
													duration: 300
												});
											}

											return;
										}
										V.enqueue(U);
										const L = new TextDecoder().decode(U);

										try {
											const G = L.match(/data:\s/g),
												j = L.split('data:').filter(w => !!w
													.trim() && w
													.trim() !== '[DONE]');
											// console.log(j);
											// let N = null;

											let N = j
												.map(w => JSON.parse(w))
												.map(w => (N = w.choices[0].delta
													.content))
												.join('');


											if (N != undefined) {
												message += N;
											}
											if (that.thoroughfare == 2) {
												that.talkList[that.question_index]
													.content = message;
											}
											// let C = null;
											let C = j
												.map(w => JSON.parse(w))
												.map(w => (N = w.choices[0]
													.finish_reason))
												.join('');
											if (C == 'stop') {
												that.timing = that.appInfo
													.text_expire_time ? Number(
														that.appInfo.text_expire_time
													) : 30;
												that.showcontext = true;
												that.getcontext();
												that.record(that.talkList[that
														.answer_index].content,
													message);
												that.talkList[that.question_index]
													.show_flash = false;
												that.talkList[that.question_index]
													.done = true;
												that.getUserData();
												// if (that.followornot) {
												// 	uni.pageScrollTo({
												// 		scrollTop: 9999,
												// 		duration: 300
												// 	});
												// }
												setTimeout(() => {
													uni.pageScrollTo({
														scrollTop: 9999,
														duration: 300
													});
												}, 100);

												return;
											}
											// console.log(C,'1');
											if (that.followornot) {
												uni.pageScrollTo({
													scrollTop: 9999,
													duration: 0
												});
											}
										} catch (G) {
											// console.error(G,'1');
										}
										F();
									});
								}
								F();
							}
						});
					})
					.then(x =>
						new Response(x, {
							headers: {
								'Content-Type': 'text/html'
							}
						}).text()
					);
			},
			// 记录回答
			record(question, answer) {
				let that = this;
				this.$http('question.add', {
					question,
					answer
				}).then(res => {
					if (res.code == 0) {
						that.getUserData();
						// console.log(that.question_index);
					} else {
						that.talkList[that.question_index].content = res.msg;
						that.talkList[that.question_index - 1].content = '该问题已被隐藏!';
						that.talkList[that.question_index].show_flash = false;
						that.talkList[that.question_index].done = true;
						that.talkList[that.question_index].donec = true;
					}

				});
			},
			// 复制文本
			copyText(e) {
				uni.setClipboardData({
					data: this.talkList[e].content,
					success: function() {
						// console.log('success');
						uni.showToast({
							title: '复制成功'
						});
					}
				});
			},
			// 插屏广告显示时间
			showInterstitial() {
				time2 = setInterval(
					function() {
						interstitialAd.show().catch(err => {
							// console.error(err);
						});
					},
					this.appInfo.gap ? this.appInfo.gap * 1000 : 12000
				);
			},
			// 生成图片
			toSave() {
				uni.showLoading({
					title: '海报生成中'
				});
				this.$refs.painter.canvasToTempFilePathSync({
					// 在nvue里是jpeg
					fileType: 'jpg',
					quality: 1,
					success: res => {
						// this.path = res.tempFilePath;
						// this.$refs.posterImg.open();
						// this.show_poster = true;

						// console.log(res.tempFilePath);
						// 非H5 保存到相册
						// H5 提示用户长按图另存

						// #ifdef H5
						this.showPoster = false;
						uni.hideLoading();
						uni.showModal({
							confirmColor: '#26B3A0',
							confirmText: '查看图片',
							title: '提示',
							content: '查看图片后长按图片即可保存或分享',
							success(src) {
								if (src.confirm) {
									uni.previewImage({
										urls: [res.tempFilePath]
									});
								} else if (src.cancel) {
									this.showPoster = true;
								}
							}
						});
						// #endif
					}
				});
			},
			//预览图片
			preview(e) {
				uni.previewImage({
					urls: [this.paintinglist[e].img],

				});
			},
			//选择模型
			onselect(e) {
				if (this.selectornot != e) {
					let data = {
						content: uni.$u.trim(this.homeTemplate.mode[e].greetings),
						type: 1,
						toid: this.toid,
						fromid: -1,
						avatar: this.homeTemplate.mode[e].img_file.path,
						nickname: this.homeTemplate.mode[e].name,
						done: true,
						donec: true
					};
					this.talkList.push(data);
					this.$nextTick(() => {
						uni.pageScrollTo({
							scrollTop: 9999,
							duration: 300
						});
					});
				}
				this.showcontext = false
				this.switchmodel = this.selectornot == e ? true : false;
				this.selectornot = e;
				// #ifdef H5
				this.zhuangtai = this.homeTemplate.mode[e].name;
				// #endif
			},
		}
	};
</script>

<style lang="scss" scoped>
	@import '@/pages/chat/global.scss';
	@import './chat.scss';
</style>