<template>
	<view>
		
		<view class="header gpt-header" :style="[{height:CustomBar + 'px'}]" :class="scrollTop>40?'goScroll':''">
			<view class="cu-bar" :style="{'height': CustomBar + 'px','padding-top':StatusBar + 'px'}" >
				<view class="action" @tap="back">
					<text class="cuIcon-back"></text>
				</view>
				<view class="content" :style="[{top:StatusBar + 'px'}]">
					<text class="text-bold">{{name}}</text>
				</view>
				<view class="action">
					<view class="cu-avatar round"  @tap="showModal" data-target="chatInfo" :style="avatarstyle" v-if="avatarstyle!=''"></view>
					<view class="cu-avatar round" v-else>
						<text class="home-noLogin"></text>
					</view>
				</view>
			</view>
		</view>
		<view class="gpt-bg">
			<image src="./style/gpt-bg.png"></image>
		</view>
		<view class="cu-chat cu-chat-gpt" >
			<view class="cu-item"  :style="[{padding:NavBar + 'px 0px 0px 0px'}]"></view>
			<!-- <view class="more-msg">
				<text class="text-blue" @tap="loadMore">{{moreText}}</text>
			</view> -->
			<view class="gpt-nodata-info" v-if="msgList.length==0">
				<view class="gpt-nodata-info-ico">
					<image src="./style/gpt.png"></image>
				</view>
				<view class="gpt-nodata-info-tips">
					欢迎使用AI聊天功能，您可以按如下方式询问。
				</view>
				<view class="gpt-nodata-info-box">
					<view class="gpt-nodata-info-main" @tap="msg='我要怎么克服拖延症？'">
						我要怎么克服拖延症？
					</view>
				</view>
				<view class="gpt-nodata-info-box">
					<view class="gpt-nodata-info-main" @tap="msg='请帮我写一个关于秋天的故事。'">
						请帮我写一个关于秋天的故事。
					</view>
				</view>
				<view class="gpt-nodata-info-box">
					<view class="gpt-nodata-info-main" @tap="msg='怎么用javascript实现随机数生成？'">
						怎么用javascript实现随机数生成？
					</view>
				</view>
			</view>
			<view class="cu-info gpt-cu-info" v-if="msgList.length>0">
				聊天窗口消息仅显示最新的100条，可在历史记录中查询之前的消息
				
			</view>
			<block v-for="(item,index) in msgList" :key="index">
				<view class="cu-item " :class="item.isAI==0?'self':''">
					<!-- <view class="cu-avatar radius" @tap="toUserContents(item.userJson)"  v-if="item.isAI==1" :style="'background-image:url('+avatar+');'"></view> -->
					<view class="main">
						<view class="content shadow break-all gpt-content" :class="item.isAI==0?'bg-blue light':''">
							<!-- <rich-text :nodes="markHtml(item.text)"></rich-text> -->
							<mp-html :content="item.text" :selectable="true" :show-img-menu="true"  :scroll-table="true" :markdown="true"/>
						</view>
					</view>
					<!-- <view class="cu-avatar radius"  v-if="item.isAI==0" :style="'background-image:url('+item.userJson.avatar+');'"></view> -->
					<view class="date">
					{{formatDate(item.created)}}
					
					
					</view>
				</view>
			</block>
			<view class="cu-item" v-if="isWaiting==1">
				<view class="main">
					<view class="content shadow break-all">
						AI正在思考中...
					</view>
				</view>
			</view>
		</view>

		<view class="cu-bar foot input" :style="[{bottom:InputBottom+'px'}]">
			<template v-if="isWaiting==0">
				<!-- <input class="solid-bottom" :adjust-position="false" :focus="false" maxlength="300" cursor-spacing="10"></input> -->
				 
				 <textarea class="msg-input"  :adjust-position="false" :focus="false" maxlength="-1" auto-height  :placeholder="'当前AI单次请求消耗'+price+currencyName"
				 @focus="InputFocus" @blur="InputBlur" v-model="msg"/>
				<button class="cu-btn bg-blue light" @tap="sendMsg()">发送</button>
			</template>
			
			<template v-if="isWaiting==1">
				<input class="solid-bottom" :adjust-position="false" :focus="false" maxlength="300" cursor-spacing="10" placeholder="AI正在思考..."></input>
				<button class="cu-btn bg-blue light">等待</button>
			</template>
		</view>
		<view class="cu-modal" :class="modalName=='chatInfo'?'show':''">
			<view class="cu-dialog">
				<view class="cu-bar bg-white justify-end">
					<view class="content"><text class="text-bold">{{name}}</text>
					</view>
					<view class="action" @tap="hideModal">
						<text class="cuIcon-close text-red"></text>
					</view>
				</view>
					<view class="user-edit-header">
						<image :src="avatar"></image>
						<view class="gpt-tips-intro">{{intro}}</view>
											
					</view>
					
				<view class="cu-bar bg-white justify-center">
					<view class="action">
							<button class="cu-btn bg-blue light" @tap="goHistory()">历史消息</button>
							<button class="cu-btn bg-red margin-left" @tap="gptChatDelete()">重置聊天</button>
					</view>
				</view>
			</view>
		</view>
		<!--加载遮罩-->
		<view class="loading" v-if="isLoading==0">
			<view class="loading-main">
				<image src="style/loading.gif"></image>
			</view>
		</view>
		<!--加载遮罩结束-->
	</view>
</template>

<script>
	import { localStorage } from '@/js_sdk/mp-storage/mp-storage/index.js'
	export default {
		data() {
			return {
				StatusBar: this.StatusBar,
				CustomBar: this.CustomBar,
				NavBar:this.StatusBar +  this.CustomBar,
				AppStyle:this.$store.state.AppStyle,
				InputBottom: 0,
				id:0,
				name:"未知大模型",
				moreText:"获取更多",
				isWaiting:0,
				toid:0,
				avatar:"",
				userInfo:null,
				token:"",
				avatarstyle:"",
				msg:"",
				page:1,
				
				msgList:[],
				uid:"",
				
				msgLoading:null,
				lastTime:0,
				
				group:"",
				
				
				modalName:"",
				lastid:0,
				
				isLoading:0,
				
				price:"",
				intro:"",
				currencyName:"",
				
				scrollTop:0,
			};
		},
		onPageScroll(res){
			var that = this;
			that.scrollTop = res.scrollTop;
		},
		onShow() {
			var that = this
			if(localStorage.getItem('userinfo')){
				
				that.userInfo = JSON.parse(localStorage.getItem('userinfo'));
				that.uid = that.userInfo.uid;
				that.group = that.userInfo.group;
			}
		},
		onReachBottom() {
		    //触底后执行的方法，比如无限加载之类的
			var that = this;
			//到底部后，重新变成第一页，开始加载数据
			that.page = 1;
		},
		onBackPress() {
			var that = this
			
		},
		onUnload() {
			var that = this
			
		},
		onLoad(res) {
			var that = this;
			// #ifdef APP-PLUS || MP
			that.NavBar = this.CustomBar;
			// #endif
			
			uni.request({
				url:that.$API.SPset(),
				method:'GET',
				dataType:"json",
				success(res) {
					that.currencyName = res.data.assetsname;
				},
				fail(error) {
				  console.log(error);
				}
				
			})
			if(res.id){
				that.id = res.id;
				that.getGptInfo();
				that.getMsgList();
				// that.setRead();
				// that.msgLoading = setInterval(() => {
				//  that.getMsgList(false);
				// }, 3000);
			}
			
			
			// if(that.type==1){
			// 	that.getGroupInfo(that.chatid);
			// }
			// #ifdef APP-PLUS
			uni.onKeyboardHeightChange(res => {
				//监听软键盘的高度 
				//当点击软键盘自带的收起按钮的时候也就是会隐藏软键盘 这时候监听到的软键盘的高度就是0 、
				//让输入框取消焦点 这时候再去输入内容的时候 输入框就会弹起
				if (res.height == 0) {
				
					that.InputBottom = 0;
					
				}else{
					that.InputBottom = res.height;
				}
			});
			// #endif
			
		},
		methods: {
			back(){
				var that = this;
				clearInterval(that.msgLoading);
				that.msgLoading = null
				uni.navigateBack({
					delta: 1
				});
			},
			formatDate(datetime) {
				var datetime = new Date(parseInt(datetime * 1000));
				// 获取年月日时分秒值  slice(-2)过滤掉大于10日期前面的0
				var year = datetime.getFullYear(),
					month = ("0" + (datetime.getMonth() + 1)).slice(-2),
					date = ("0" + datetime.getDate()).slice(-2),
					hour = ("0" + datetime.getHours()).slice(-2),
					minute = ("0" + datetime.getMinutes()).slice(-2);
				//second = ("0" + date.getSeconds()).slice(-2);
				// 拼接
				var result = year + "-" + month + "-" + date + " " + hour + ":" + minute;
				// 返回
				return result;
			},
			InputFocus(e) {
				this.isOwO = false;
				this.InputBottom = e.detail.height;
			},
			InputBlur(e) {
				this.InputBottom = 0;
			},
			previewImage(image) {
				var imgArr = [];
				imgArr.push(image);
				//预览图片
				uni.previewImage({
					urls: imgArr,
					current: imgArr[0]
				});
			},
			getMsgList(){
				var that = this;
				var token = "";
				if(localStorage.getItem('userinfo')){
					var userInfo = JSON.parse(localStorage.getItem('userinfo'));
					token=userInfo.token;
				}
				// else{
				// 	用户加载更多数据时，不再加载数据
				// 	if(page > 1){
				// 		return false;
				// 	}
				// }
				that.$Net.request({
					url: that.$API.gptLastMsg(),
					data:{
						"token":token,
						"gptid":that.id,
						"limit":100,
					},
					header:{
						'Content-Type':'application/x-www-form-urlencoded'
					},
					method: "get",
					dataType: 'json',
					success: function(res) {
						uni.stopPullDownRefresh();
						that.isLoad=0;
						if(res.data.code==1){
							var list = res.data.data;
							list = list.reverse();
							that.msgList = list;
							
						}
						that.isLoading=1;
						setTimeout(() => {
							uni.pageScrollTo({
								duration: 0,
								scrollTop: 99999999
							})
						},200)
					},
					fail: function(res) {
						uni.stopPullDownRefresh();
						that.isLoad=0;
						that.isLoading=1;
					}
				})
			},
			getGptInfo(){
				var that = this;
				var data = {
					"id":that.id,
				}
				
				that.$Net.request({
					url: that.$API.gptInfo(),
					data:data,
					header:{
						'Content-Type':'application/x-www-form-urlencoded'
					},
					method: "get",
					dataType: 'json',
					success: function(res) {
						if(res.data.code==1){
							var gptInfo = res.data.data;
							that.avatarstyle = "background-image:url("+gptInfo.avatar+");"
							that.avatar = gptInfo.avatar;
							that.name = gptInfo.name;
							that.price = gptInfo.price;
							that.intro =  gptInfo.intro;
						}
					},
					fail: function(res) {
					}
				});
			},
			sendMsg(){
				var that = this;
				var token = "";
				if(that.msg==""){
					return false;
				}
				if(localStorage.getItem('userinfo')){
					var userInfo = JSON.parse(localStorage.getItem('userinfo'));
					token=userInfo.token;
				}else{
					uni.showToast({
						title: "请先登录",
						icon: 'none'
					})
					uni.navigateTo({
						url: '/pages/user/login'
					});
					return false;
				}
				if(that.msg.length>1500){
					uni.showToast({
						title: "最大字符数为1500",
						icon: 'none'
					})
					return false
				}
				var data={
					"gptid":that.id,
					"token":token,
					"msg":that.msg,
					
				}
				//添加一个新字段
				var curtime = Date.parse(new Date());
				var msg ={
					"created": curtime / 1000,
					"text":that.msg,
					"isAI": 0,
					"uid": that.uid,
					"userJson": that.userInfo
				}
				that.msgList.push(msg);
				setTimeout(() => {
					uni.pageScrollTo({
						duration: 0,
						scrollTop: 99999999
					})
				},100)
				that.msg = "";
				that.isWaiting = 1;
				
				that.$Net.request({
					
					url: that.$API.gptSendMsg(),
					data:data,
					header:{
						'Content-Type':'application/x-www-form-urlencoded'
					},
					method: "post",
					dataType: 'json',
					success: function(res) {
						that.isWaiting = 0;
						if(res.data.code==1){
							//that.getMsgList();
							//var aiMsgtime = Date.parse(new Date());
							var msg ={
								"created": res.data.data.created,
								"text":res.data.data.text,
								"isAI": 1,
								"uid": that.uid,
								"userJson": that.userInfo
							}
							that.msgList.push(msg);
							setTimeout(() => {
								uni.pageScrollTo({
									duration: 0,
									scrollTop: 99999999
								})
							},200)
						}else{
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							})
						}
					},
					fail: function(res) {
						that.isWaiting = 0;
						uni.showToast({
							title: "网络开小差了哦",
							icon: 'none'
						})
					}
				})
			},
			goHistory(){
				var that = this;
				uni.navigateTo({
					url: '/pages/plugins/sy_gpt/history?id='+that.id
				});
			},
			ToCopy(text) {
				var that = this;
				// #ifdef APP-PLUS
				uni.setClipboardData({
					data: text,
					success: () => { //复制成功的回调函数
						uni.showToast({ //提示
							title: "复制成功"
						})
					}
				});
				// #endif
				// #ifdef H5 
				let textarea = document.createElement("textarea");
				textarea.value = text;
				textarea.readOnly = "readOnly";
				document.body.appendChild(textarea);
				textarea.select();
				textarea.setSelectionRange(0, text.length) ;
				uni.showToast({ //提示
					title: "复制成功"
				})
				var result = document.execCommand("copy") 
				textarea.remove();
				
				// #endif
			},
			upload(){
				let that = this;
				var token = "";
				if(localStorage.getItem('userinfo')){
					var userInfo = JSON.parse(localStorage.getItem('userinfo'));
					token=userInfo.token;
				}else{
					uni.showToast({
						title: "请先登录",
						icon: 'none'
					})
					clearInterval(that.msgLoading);
					that.msgLoading = null
					uni.navigateTo({
						url: '/pages/user/login'
					});
					return false;
				}
				uni.chooseImage({
					count: 6, 
					sourceType: ['album', 'camera'], 
				    success: function (res) {
						uni.showLoading({
							title: "上传中"
						});
						const tempFilePaths = res.tempFilePaths;
						for(let i = 0;i < tempFilePaths.length; i++) {
							const uploadTask = uni.uploadFile({
							  url : that.$API.upload(),
							  filePath: tempFilePaths[i],
							  name: 'file',
							  formData: {
							   'token': token
							  },
							  success: function (uploadFileRes) {
								  let count = 0;
								  count++;
								  if(count==tempFilePaths.length){
									  setTimeout(function () {
										uni.hideLoading();
									  }, 1000);
								  }
									var data = JSON.parse(uploadFileRes.data);
									//var data = uploadFileRes.data;
									// uni.showToast({
									// 	title: data.msg,
									// 	icon: 'none'
									// })
									if(data.code==1){
										that.sendURL(1,data.data.url);
									}
								},fail:function(){
								}
								
							   
							});
						}
					}
				})
			},
			sendURL(type,url){
				var that = this;
				var token = "";
				if(that.url==""){
					return false;
				}
				if(localStorage.getItem('userinfo')){
					var userInfo = JSON.parse(localStorage.getItem('userinfo'));
					token=userInfo.token;
				}else{
					uni.showToast({
						title: "请先登录",
						icon: 'none'
					})
					uni.navigateTo({
						url: '/pages/user/login'
					});
					return false;
				}
				
				var data={
					"chatid":that.chatid,
					"token":token,
					"url":url,
					"type":type,
					
				}
				that.$Net.request({
					
					url: that.$API.sendMsg(),
					data:data,
					header:{
						'Content-Type':'application/x-www-form-urlencoded'
					},
					method: "post",
					dataType: 'json',
					success: function(res) {
						if(res.data.code==1){
							that.getMsgList();
							that.msg = "";
						}else{
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							})
						}
					},
					fail: function(res) {
						uni.showToast({
							title: "网络开小差了哦",
							icon: 'none'
						})
					}
				})
			},
			markHtml(text){
				var that = this;
				text = that.replaceAll(text,"<","&lt;");
				text = that.replaceAll(text,">","&gt;");
				// #ifdef APP-PLUS || H5
				var owoList=that.owoTextList;
				for(var i in owoList){
				
					if(that.replaceSpecialChar(text).indexOf(owoList[i].data) != -1){
						text = that.replaceAll(that.replaceSpecialChar(text),owoList[i].data,"<img src='/"+owoList[i].icon+"' class='tImg' />")
						
					}
				}
				// #endif
				
				return text;
				
				
			},
			goChatInfo(){
				var that = this;
			},
			replaceSpecialChar(text) {
				if(!text){
					return false;
				}
				text = text.replace(/&quot;/g, '"');
				text = text.replace(/&amp;/g, '&');
				text = text.replace(/&lt;/g, '<');
				text = text.replace(/&gt;/g, '>');
				text = text.replace(/&nbsp;/g, ' ');
				return text;
			},
			replaceAll(string, search, replace) {
			  return string.split(search).join(replace);
			},
			showModal(e) {
				this.modalName = e.currentTarget.dataset.target
			},
			hideModal() {
				this.modalName = null
			},
			gptChatDelete(){
				var that = this;
				var token = "";
				this.modalName = null;
				if(localStorage.getItem('userinfo')){
					var userInfo = JSON.parse(localStorage.getItem('userinfo'));
					token=userInfo.token;
				}
				var data = {
					"id":that.id,
					"token":token
				}
				uni.showModal({
				    title: '此操作将删除所有消息，并将聊天重置',
				    success: function (res) {
				        if (res.confirm) {
				            uni.showLoading({
				            	title: "加载中"
				            });
				            
				            that.$Net.request({
				            	url: that.$API.gptChatDelete(),
				            	data:data,
				            	header:{
				            		'Content-Type':'application/x-www-form-urlencoded'
				            	},
				            	method: "get",
				            	dataType: 'json',
				            	success: function(res) {
				            		setTimeout(function () {
				            			uni.hideLoading();
				            		}, 1000);
				            		uni.showToast({
				            			title: res.data.msg,
				            			icon: 'none'
				            		})
				            		if(res.data.code==1){
										that.back();
				            		}
				            		
				            	},
				            	fail: function(res) {
				            		setTimeout(function () {
				            			uni.hideLoading();
				            		}, 1000);
				            		uni.showToast({
				            			title: "网络开小差了哦",
				            			icon: 'none'
				            		})
				            	}
				            })
				        } else if (res.cancel) {
				            console.log('用户点击取消');
				        }
				    }
				});
				
			},
		}
	}
</script>

<style>
page{
  padding-bottom: 100upx;
}
.cu-bar.foot{
	z-index: 998;
}
</style>
