<template>
	<view class="container" :style="{'top': viewTop + 'px', 'height': viewHeight + 'px'}">
		<view class="content">
			<scroll-view scroll-y="true" :show-scrollbar="false" :scroll-top="scroll_top" style="top: 0%;width: 80vw; height:65%;position: absolute;">
					<view class="scroll-view-text">
						<view  style="margin-left: 13%; display: flex; align-items: center;justify-content: center;width: 100%;  user-select: text;" v-for="(msgIndex,index) in recvMsgQueue ">
							<!-- ai 的消息结构体 -->
							<view v-if="isAItell(recvMsgQueue[index].who_msg)"  style="width: 100%;height: 100%;margin-bottom: 1%;">
								<text style=" font-size: 10rpx;color: #B34FFF;font-size: 10rpx;margin-left: 2%;background: linear-gradient(90deg, #24BF74 10%, #FAEE07 90%);-webkit-background-clip: text;-webkit-text-fill-color: transparent;">
									{{ai_name}}
								</text>
								<view  style="margin-bottom: 3%; margin-top: 1%;margin-left: 1%;padding: 1%; width: 70%;background: #2A2832;border-radius: 10rpx 10rpx 10rpx 10rpx;">
									<view @tap="handleClick()" style="width: 100%;background-color: #2A2832;color: white;" class="htmlContent" ref="htmlContent" v-html="returnText(recvMsgQueue[index].msg_text)" >
										
									</view>
									<image v-if="getImg(index)!=''" :src="getImg(index)"></image>
									<view @click="stopRecv()" v-if="recvStatus&&recvMsgQueue[index].isFinish==false" style="display: flex;width: 100%;align-items: center;justify-content: center;">
										<image src="../../static/closed.png" style="width: 50upx;height: 50upx;align-self: center;"></image>
									</view>
									
								</view>
								
					
								<view v-if="false" style="margin-left: 65%;">
									<image src="../../static/msg-opt-3.png" style="margin-left: 10upx;width: 30upx;height: 30upx;"></image>
									<image src="../../static/msg-opt-4.png" style="margin-left: 10upx;width: 30upx;height: 30upx;"></image>
								</view>
								
						
								
								<view style=" display: flex;flex-wrap: wrap;width: 40%;">
									<view  style="width:  25%;justify-content: center;align-items: center;display: flex;margin-top: 2%;" v-for="(item,i) in recvMsgQueue[index].actions" key="key">
										<view @click="clickitem(recvMsgQueue[index].actions[i],recvMsgQueue[index].image_id)" style="background-color: #24BF74;display: flex;border-radius: 25px 25px 25px 25px;align-items: center;justify-content: center;width: 100%;margin: 1%;">{{recvMsgQueue[index].actions[i]}}</view>		
									</view>
								</view>
							
								
							</view>
						
							<!-- 我发送 的消息结构体 -->
							<view v-if="!isAItell(recvMsgQueue[index].who_msg)"  style="width: 100%;height: 100%;margin-top: 1%;">
								
								<view style=" font-size: 10rpx;color: #B34FFF;font-size: 10rpx;margin-left: 2%;">
									{{user_name}}
								</view>
								<view  style="margin-bottom: 3%; margin-top: 1%;margin-left: 1%;padding: 1%; width: 70%;background: #2A2832;border-radius: 10rpx 10rpx 10rpx 10rpx;">
									<view style="width: 100%;background-color: #2A2832;color: white;" class="htmlContent" ref="htmlContent" >
										{{recvMsgQueue[index].msg_text}}
									</view>
									<image v-if="recvMsgQueue[index].des_img!=''" :src="recvMsgQueue[index].des_img"></image>
								</view>
								
								<view v-if="false" style="margin-left: 65%;">
									<image src="../../static/msg-opt-1.png" style="margin-left: 10upx; width: 30upx;height: 30upx;"></image>
									<image src="../../static/msg-opt-2.png" style="margin-left: 10upx;width: 30upx;height: 30upx;"></image>
									<image src="../../static/msg-opt-3.png" style="margin-left: 10upx;width: 30upx;height: 30upx;"></image>
									<image src="../../static/msg-opt-4.png" style="margin-left: 10upx;width: 30upx;height: 30upx;"></image>
								</view>
								
							</view>
							
						</view>
					</view>
			</scroll-view>
			
			<view style="display: flex;width: 70vw;height: 90upx;position: absolute;bottom:500upx;">
					<view style="display: flex;width: 90%;  border-radius: 25px 25px 25px 25px;opacity: 1;border: 1px solid #32B3AA;width: 100%;" class="textarea-box">
					
						<view style="width: 90%; height: 100%; display: flex;align-items: center;justify-content: center" >
							<textarea  v-model="inputValue" :cursor-spacing="15" class="textarea" auto-height="true"
								@keydown.enter="onKeydown('enter')" :disabled="disabled"
								@input="onKeyInput"
								placeholder="请输入消息内容(使用 Enter 发送)" :maxlength="-1" 
								placeholder-class="input-placeholder"></textarea>
						</view>
						<view v-if="recvStatus==false" style="width: 10%; height: 100%; display: flex; color: aliceblue;align-items: center;justify-content: center" @click="sendMsg">
							<image src="../../static/img_send.png" style="width: 29.57upx;height: 37.67upx;" ></image>
						</view>
					</view>
					<view style=" display: flex;align-items: center;justify-content: center;width: 5%;position: relative;">
						<image @click="onclickdelete()" src="../../static/img_delete.png" style="width: 50upx;height: 70upx;"></image>
					</view>
			</view>
		</view>
					<view style="position: absolute;top: 10%;right: 5%;width: 200upx;display: flex;align-items: center;justify-content: center;">
						<view style="color: white;margin-right: 10upx;">开启慢速</view>
						<image @click="is_open_relax=false" v-show="is_open_relax==true" src="../../static/img-on.png" style="width: 60upx;height: 30upx;"></image>
						<image @click="is_open_relax=true" v-show="is_open_relax==false" src="../../static/img-off.png" style="width: 60upx;height: 30upx;"></image>
					</view>
					
					<view @click="is_show_import_img_view=true" style="position: absolute;top: 20%;right: 5%;width: 200upx;display: flex;align-items: center;justify-content: center;">
						<view style="color: white;margin-right: 10upx;">导入图片</view>
						<image  src="../../static/import-img.png" style="width: 60upx;height: 60upx;"></image>
					</view>
					
					
					<view v-if="is_show_import_img_view==true" style=" display: flex; height: 100vh; position: absolute;top: 0;width: 500upx;background-color:#24BF74;">
						<view style="width: 100%;;">
							<view @click="onFileInput" style="display: flex;align-items: center;justify-content: center;margin-top: 5%;center;margin-bottom: 5%;">
								<image :src="cur_select_img" style="width: 100upx;height: 100upx;"></image>
							</view>
							
								
							<view style="display: flex;align-items: center;justify-content: center;margin-top: 5%;center;margin-bottom: 5%;">
								<textarea   style="display: flex;align-items: center;justify-content: center;" v-model="diy_inputValue" :cursor-spacing="15" auto-height="true"
									@input="onKeyInput"
									placeholder="请输入描述" :maxlength="-1" 
									placeholder-class="input-placeholder"></textarea>
							</view>
							<view @click="send_diy_img()" style="display: flex;align-items: center;justify-content: center;margin-top: 5%;center;margin-bottom: 5%;">
								<view style="display: flex;align-items: center;justify-content: center;background-color: aqua;;border-radius: 10rpx 10rpx 10rpx 10rpx;width: 50%;">发送</view>
							</view>
							
							<view @click="is_show_import_img_view=false" style="display: flex;align-items: center;justify-content: center;margin-top: 5%;center;margin-bottom: 5%;">
								<view style="display: flex;align-items: center;justify-content: center;background-color: aqua;;border-radius: 10rpx 10rpx 10rpx 10rpx;width: 50%;">关闭</view>
							</view>
							
							<scroll-view scroll-y="true" style="height:500upx;">
								<view @click="selectImg(import_list[j])" style="display: flex;align-items: center;justify-content: center;" v-for="(itemx,j) in import_list">
									<image style="width: 150upx;height: 150upx;margin-top: 5%;" :src="import_list[j]"></image>
								</view>
								
							</scroll-view>
							
						</view>
				
					</view>
					<view v-if="is_up_img_file" style="align-items: center;justify-content: center;display: flex; color: aliceblue; position: absolute; width: 100vw;height:100vh;background-color: black;opacity: 70%;">
						正在上传
					</view>
				
	</view>
</template>

<script>
	import marked from '../marked/marked.min.js';
	import config from '../index/config.js';
	import hljs from "../highlight.js/lib/common.js";
	import interfaces from '../../utils/interfaces.js'
	import "../highlight.js/styles/atom-one-dark.css";
	// import  '../v-copy.js';
	// 键盘的shift键是否被按下
	let shiftKeyPressed = false
	export default {
		components:{
			marked
		},
		data() {
			return {
				diy_inputValue: '',
				is_up_img_file:false,
				import_list:[],
				is_show_import_img_view:false,
				is_open_relax:true,
				code:'',
				title: 'Hello',
				disabled: false,
				socketOpen:false,
				socketMsgQueue:[],
				recvMsgQueue:[],
				sendMsgQueue:[],
				inputValue: '',
				inputOldValue: '',
				_socketTask:null,
				scroll_text_:"\n",
				sendStatus:false,
				recvStatus:false,
				all_src_list:[],
				src_index:0,
				scroll_top:0,
				user_name:'ZYWZ',  //用户名字
				ai_name:"SmartAssistant", //ai名字
				user_mobile:"18612220000",//用户手机号
				ani:'',
				ani_style:{
					width: "100upx",height: "100upx",rotate: 0,left:"25%",right:"25%",position:"absolute"
				},
				angle:359,
				imageUrl:'',
				fileData:null,
				cur_select_img:'../../static/import-img.png',
			}	
		},
		mounted(){
			    this.user_mobile = this.tools.get_user_info().mobile
				marked.setOptions({
				          renderer: new marked.Renderer(),
				          gfm: true,
				          tables: true,
				          breaks: false,
				          pedantic: false,
				          sanitize: false,
				          smartLists: true,
				          smartypants: false,
						  highlight: function (code) {
						  					return hljs.highlightAuto(code).value;
						 },
						 langPrefix:"hljs language-"
				});
		},
		props: {
			viewTop: {
				type: Number,
				default: 0
			},
			viewHeight: {
				type: Number,
				default: 0
			}
		},
		methods: {
			send_diy_img(){
				if(this.cur_select_img==="../../static/import-img.png"){
					uni.showToast({
						title:"请选择图片"
					})
					return
				}
				if(this.diy_inputValue.length>0){
					this.is_show_import_img_view = false;
					let des_img = this.cur_select_img;
					this.sendSocketMessage(this.diy_inputValue,this.cur_select_img+" "+this.diy_inputValue,des_img)
					this.diy_inputValue = '';
				}else{
					uni.showToast({
						title:"请添加描述，只支持英文哦"
					})
				}
				
			},
			selectImg(path){
				let self = this;
				self.cur_select_img = path;
			},
			onFileInput(event) {
				let self = this;
				uni.chooseImage({
					success: (chooseImageRes) => {
						const tempFilePaths = chooseImageRes.tempFilePaths;
						self.is_up_img_file = true;
						uni.uploadFile({
							url: 'https://mlapi.hainanmlwl.com/file/upload_aiimg', //仅为示例，非真实的接口地址
							filePath: tempFilePaths[0],
							name: 'aiimg_url',
							formData: {
								// 'aiimg_url': self.cur_select_img
							},
							success: (uploadFileRes) => {
								self.is_up_img_file = false;
								let obj = JSON.parse(uploadFileRes.data)
								uni.showModal({
									content:obj.message,
									showCancel:false
								})
								console.log("self.cur_select_img",self.cur_select_img)
							
								if(obj.code==10000){
									let img_url = obj.content.surl
									self.import_list.push(img_url)
									self.cur_select_img = img_url;
								}
								console.log("uploadFile",obj);
							},
							fail() {
								uni.showModal({
									content:"上传失败",
									showCancel:false
								})
								self.is_up_img_file = false;
							}
						});
					}
				});

				// console.log("onFileInput",event)
			 //  const file = event.target.files[0]  // 获取选择的文件
			 //  const reader = new FileReader()  // 创建FileReader对象
			 //  // 当文件被读取时，将其转换为DataURL格式的字符串，并将其作为imageUrl值赋给组件的data属性中
			 //  reader.onload = (e) => {
			 //    this.imageUrl = e.target.result
			 //    // 保存文件对象到data属性中
			 //    this.fileData = file
			 //  }
			 //  reader.readAsDataURL(file)  // 读取文件并启动onload回调函数
			},
			clickitem(action,image_id){
				switch(action){
					case "upsample1":
					break;
					case "upsample2":
					break;
					case "upsample3":
					break;
					case "upsample4":
					break;
					case "variation1":
					break;
					case "variation2":
					break;
					case "variation3":
					break;
					case "variation4":
					break;
				}
				console.log("clickitem",this.recvStatus,action,image_id)
				if(!this.recvStatus){
					this.sendSocketMessage(action,'','',action,image_id)
				}
				
			},
			getImg(index){
				return this.recvMsgQueue[index].msg_img
			},
			onclickdelete(){
				let self = this;
				if(self.recvMsgQueue.length>0&&self.recvMsgQueue[self.recvMsgQueue.length-1].isFinish){
					uni.showModal({
						showCancel:true,
						content:"是否删除记录",
						success:(res)=>{
							if(res.confirm){
								self.recvMsgQueue = []
							}
						}
					})
				}
				
			},
			// #ifdef H5 && VUE2
			onKeydown(keyname) {
				let self = this;
				if(self.inputOldValue!=self.inputValue){
					 self.sendMsg();
				}else{
				
				}
			},
			onKeyup(keyname) {
				let self = this;
				self.inputOldValue=self.inputValue;
			},
			// #endif
			setCopy(content){
			    // 使用#ifdef H5和#endif控制各端调用情况
			
			    // 该方法不支持h5
			    //#ifndef H5
			    uni.setClipboardData({
			        data: String(content), // 必须字符串
			        success: function () {
			            console.log('success');
			        }
			    });
			    //#endif
			
			    // h5端赋值方法，使用创建节点
			    // #ifdef H5
			    if (!document.queryCommandSupported('copy')) { // 兼容某些浏览器的判断
			        console.log('该浏览器不支持')
			    }
			    let textarea = document.createElement("textarea")
			    textarea.value = content
			    textarea.readOnly = "readOnly"
			    document.body.appendChild(textarea)
			    textarea.select() // 选择对象
			    textarea.setSelectionRange(0, content.length) // 核心
			    let result = document.execCommand("copy") // 执行浏览器复制命令
			    if (result) {
			        uni.showToast({
			            title: '复制成功',
			            duration: 2000
			        });
			    }
			    textarea.remove()
			    // #endif
			},
			updateSrcList(){
				let self = this;
				let list = this.getIndexList(self.scroll_text_);
				for (var i = 0; i < list.length; i+=2) {
					let start = list[i];
					let end = list[i+1];
					self.all_src_list.push(self.scroll_text_.substring(start,end))
				}	
				console.log("updateSrcList",self.all_src_list,self.scroll_text_)
			},
			stopRecv(){
				let self =this;
				self._socketTask.close()
				// self.initTcp(true);
				self.finish_recv();
			},
			 handleClick(e) {
				e = e || window.event;
				let target = e.target || e.srcElement;
				let name = target.tagName.toLowerCase();
				let self =this;
				if(name.substring(0,3)=="abc"){
					let name_list = name.split('_');
					if(name_list.length>0){
						let index = parseInt(name_list[1])-1;
						console.log("handleClick",index,self.all_src_list)
						self.setCopy(self.all_src_list[index])
					}
					console.log("handleClick",self.all_src_list[index])
					console.log(target.tagName.toLowerCase())
				}
				console.log(name.substring(0,3))
			  },
			copyUpdates(){
				let self = this;
				let str = self.recvMsgQueue[self.recvMsgQueue.length-1].msg_text
				let key = "</code></pre>";
				let index = self.all_src_list.length;
				while(str.indexOf(key) != -1){
					index++;
					let s_tag =   "</code><abc_"+index+" class=\"copy-button\">Copy</abc_"+index+"></pre>"
					console.log("s_tag",s_tag)
					str=str.replace("</code></pre>", s_tag)
				}
				// str=str.replaceAll("</code></pre>", "</code><abc class=\"copy-button\">Copy</abc></pre>")
				self.recvMsgQueue[self.recvMsgQueue.length-1].msg_text = str
				// console.log("copyUpdates",str)
				self.$forceUpdate();
			},	
			
			getIndexList(box_str){
				let box = box_str;
				let boxarr=[];
				let pos = box.indexOf('```');
				while(pos>-1){
					boxarr.push(pos);
					pos= box.indexOf('```',pos+1);
				}
				return boxarr
		
			},
			returnText(text){
				return "<style> body { background-color: black; color: white; } pre {position: relative;}.copy-button { position: absolute; top: 0;right: 0;padding: 4px 8px;background-color: #333;color: #fff;cursor: pointer;user-select: none;} p {line-height: 2;} li{line-height: 1.5;} table {border-collapse: collapse;width: 100%;font-family: Arial, sans-serif;font-size: 14px;}table th,table td {border: 1px solid #ddd;padding: 8px;text-align: left;}</style>" +text
			},
			// 滚动窗口以显示最新的一条消息
			showLastMsg() {
				let self = this;
				let container = uni.createSelectorQuery().in(this).select(".scroll-view-text");
				// 利用uniapp提供的接口获取可视区域的高度和滚动高度
					// let query=uni.createSelectorQuery()
					// let container=query.select('.box');
					container.fields({
						// rect:true,   //是否返回节点布局位置信息{left,top,right,bottom}
						size:true,  //是否返回节点尺寸信息{width，height}
						scrollOffset:true //是否返回节点滚动信息{scrollLeft,scrollTop}
					},(res)=>{
						self.scroll_top = res.height;
						// console.log(res)
				}).exec()
			},
			isAItell(type){
				if(type===config.type_ai){
					return true;
				}
				return false;
			},
			make_avatar(type){
				if(type===config.type_ai){
					return "../../static/PubImgs_avatar_avatar7.png";
				}
				return "../../static/PubImgs_avatar_avatar8.png";
			},
			isShow(text){
				return text!="";
			},
			initAni(){
				let self = this;
				if(!self.disabled){
					clearTimeout(self.initAni)
						return;
				}
				let loading_title = self.recvMsgQueue[self.recvMsgQueue.length-1].loading_title;
				let loading_title_str = ""
				for (var i = 0; i < loading_title; i++) {
					loading_title_str+="."
				}
				// console.log("loading_title_str",loading_title_str)
				self.recvMsgQueue[self.recvMsgQueue.length-1].msg_text  ="正在生成" +loading_title_str;
				loading_title = loading_title>=3?0: (loading_title+1)
				self.recvMsgQueue[self.recvMsgQueue.length-1].loading_title = loading_title;
				setTimeout(self.initAni,1000)
			},
			async finish_recv(){
				let self = this;
				self.recvStatus = false;
				self.disabled = false;
				clearTimeout(self.initAni)
				self.scroll_text_+="\n"
				console.log("self.recvMsgQueue",self.scroll_text_)
				self.stopUpdateView();
				self.copyUpdates();
				self.updateSrcList();
				self.showLastMsg();
				self.recvMsgQueue[self.recvMsgQueue.length-1].isFinish = true;
			},
			async sendMsg(){
				// 如果内容为空
				if (!this.inputValue) {
					// 弹出提示框
					return uni.showToast({
						// 提示内容
						title: '内容不能为空',
						// 不显示图标
						icon: 'none'
					});
				}
				this.sendSocketMessage(this.inputValue)
			},
			onKeyInput(event) {
				// console.log("onKeyInput",event.target.value)
				let self = this;
				// self.inputOldValue=self.inputValue
			},
			startUpdateView(){
				let self = this;
				self.$forceUpdate();
				setTimeout(self.startUpdateView,500)
			},
			stopUpdateView(){
				let self = this;
				clearTimeout(self.startUpdateView)
			},
			sendSocketMessage(msg,prompt=msg,des_img='',action='generate',image_id='') {
				console.log("sendSocketMessage send",des_img)
				let self = this;
				let isRelax = self.is_open_relax;
				let token = isRelax?"7d995cf958f54d2c9c3264e645a9c4d9":"bdb957b8003e4a46b6b26a7174be5789";
				let relax = isRelax?"/relax" :"";		
				let url = 'https://api.zhishuyun.com/midjourney/imagine' +relax +'?token='+token		
				self.sendStatus = true;
				self.disabled = true;
				self.ani_style.rotate = 0;
				self.inputValue = '';
				self.recvMsgQueue.push({who_msg:config.type_self,msg_type:0,msg_text:msg,isFinish:true,'des_img':des_img})
				self.recvMsgQueue.push({who_msg:config.type_ai,msg_type:0,msg_text:"正在生成...",msg_img:"",isFinish:false,actions:[],image_id:"",task_id:"",loading_title:1})
				// self.recvMsgQueue[self.recvMsgQueue.length-1].actions=['upsample1', 'upsample2', 'upsample3', 'upsample4', 'variation1', 'variation2', 'variation3', 'variation4']
				self.initAni();
				
				
				uni.request({
					url:url,
					timeout:600000,
					header: {'Content-Type':'application/json','accept':'application/json'},
					method:'POST',
					data:{'prompt':prompt,'action':action,'image_id':image_id},
					success:(res)=>{
						self.finish_recv()
						if(res.statusCode===200){
							let html_img = '<!DOCTYPE html> <html><head></head><body> <img src='+res.data.image_url+ '></body></html>'
							self.recvMsgQueue[self.recvMsgQueue.length-1].msg_img = res.data.image_url;
							self.recvMsgQueue[self.recvMsgQueue.length-1].msg_text = "";
							self.recvMsgQueue[self.recvMsgQueue.length-1].image_id = res.data.image_id;
							console.log("res.data.actions",res.data.actions)
							self.recvMsgQueue[self.recvMsgQueue.length-1].actions = [];
							let list = [];
							list = res.data.actions;
							for (var i = 0; i < list.length; i++) {
								self.recvMsgQueue[self.recvMsgQueue.length-1].actions.push(list[i])
							}
						}else{
							uni.showModal({
								content:res.data.detail+":"+res.statusCode,
								showCancel:false
							})
							self.recvMsgQueue[self.recvMsgQueue.length-1].msg_text = res.data.detail;
						}
						console.log("Ai-view",res)
					},
					fail: (e) => {
						console.log('fail', e)
						self.finish_recv()
						self.recvMsgQueue[self.recvMsgQueue.length-1].msg_text ="生成失败";
						
					}
				})
			},
			
		
		}
	}
</script>


<style>
	.container{
		display: flex;
		box-sizing: border-box;
		flex-direction: column;
		position: fixed;
		/* position: relative; */
		/* background-color: #2A2832; */
		left: 0;
		width: 100%;
		justify-content: center;
	}
	.content {
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		position: relative;
		background-color: #2A2832;
	}
	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
	
	.textarea-box,
	.textarea {
		width: 100%;
		height: 100%;
		margin-left: 3%;
	},
	textarea-box {
		width: 100% !important;
	}
	
	.textarea-box,
	.textarea,
	textarea,
	textarea-box {
		/* height: 120px; */
	}

	.textarea-box {
		background-color: #FFF;
	}
	
	uni-scroll-view .uni-scroll-view::-webkit-scrollbar {
	display: none;
	width: 0 !important;
	height: 0 !important;
	-webkit-appearance: none;
	background: transparent;
	color: transparent;
	}
	 

</style>


