<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="position: fixed; top: 70px;width: 80vw; bottom: 210upx;">
					<view v-if="recvMsgQueue.length > 0" 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 " :key="index">
							<!-- 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)" @click="onclickAiGetImg(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-direction: row; width: 500px; align-items: center;">
									<view style=" display: flex;flex-wrap: wrap;width: 400px;">
										<view  style="width: 23%;justify-content: center;align-items: center;display: flex;margin-top: 2%; margin-right: 2%;" v-for="(item,i) in recvMsgQueue[index].actions" :key="i">
											<view @click="clickitem(recvMsgQueue[index].actions[i],recvMsgQueue[index].image_id)" 
											style="background-color: #32B3AA;display: flex; box-sizing: border-box; border-radius: 5px;align-items: center;justify-content: center;width: 100%; padding: 2%; font-size: 16px; word-break: break-all; text-overflow: ellipsis; word-wrap: break-word; white-space: pre-wrap; text-align: center;">{{recvMsgQueue[index].actions[i].text}}</view>
										</view>
									</view>
	
									<view v-if="recvMsgQueue[index].has_chonghua" style="display: flex; flex-direction: column; width: 40px; margin-left: 18px; align-items: center;"
									@click="clickonredraw">
						                <view style="width: 15px; height: 15px;">
											<image style="width: 100%; height: 100%;" src="../../static/img_redraw.png" mode="aspectFit"></image>
						                </view>
										<view style="margin-top: 5px; color: #ffffff; font-size: 13px;">重画</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" style="background-color: #111111; margin-top: 1%;" mode="aspectFit" @click="onclickSendImg(index)"></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>
					<view v-else style="display:flex; width: 100%; height: 100%; color: #ffffff; justify-content: center; align-items: center;">
						<text style="font-size: 20px; font-weight: 400; text-align: center; line-height: 60px;">探索AI世界的奥秘，释放无限的创造潜能。\n开始您的创作吧！</text>
					</view>
			</scroll-view>
			
			<view class="inputbox" style="display: flex;width: 70vw;height: 90upx;position: fixed;bottom:80upx;">
				<view style="display: flex;align-items: center;justify-content: center;width: 5%;position: relative;">
					<image @click="onclickchooseImg()" src="../../static/img_upload.png" style="width: 65upx;height: 65upx;"></image>
				</view>
				<view style="display: flex;width: 90%; margin-left: 5px; border-radius: 25px 25px 25px 25px;opacity: 1;border: 1px solid #32B3AA;" 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-off.png" style="width: 60upx;height: 30upx;"></image>
						<image @click="is_open_relax=true" v-show="is_open_relax==false" src="../../static/img-on.png" style="width: 60upx;height: 30upx;"></image>
					</view>
					
					<view v-if="false" @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" :key="j">
									<image style="width: 150upx;height: 150upx;margin-top: 5%;" :src="import_list[j]"></image>
								</view>
								
							</scroll-view>
							
						</view>
				
					</view>
					
					<view v-if="choose_img_tempFilePath != ''" style="position: fixed; bottom: 190upx; left: 20%; width: 130px; height: 90px;">
						<view style="position: absolute; top: 10px; width: 120px; height: 80px; background-color: #111111;">
							<image style="width: 100%; height: 100%;" :src="choose_img_tempFilePath" mode="aspectFill" @click="onclickPreviewChooseImg"></image>
						</view>
						<view style="position: absolute; right: 0; width: 30px; height: 30px;" @click="onclickDeleteChooseImg">
							<image style="margin-left: 10px; width: 20px; height: 20px;" src="../../static/img_jian.png" mode="aspectFit"></image>
						</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',
				
				choose_img_tempFilePath: '',
				
				action_type: {
					generate: 'generate',  // 选择图片和输入框
					youhua: 'variation',// 优化
					fangda: 'upsample', // 放大
				},
				current_send: {
					msg:'',
					image_url: '', // 不为空时,表示用户通过选择图片和输入框内容
					image_id: '', // 不为空时,表示是 点'放大'或'优化'
					prompt: '',
					action: '', // generate:表示用户通过选择图片和输入框内容 variation数字:优化 upsample1数字:放大
				}
			}	
		},
		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-"
			});	
								
			// this.recvMsgQueue = uni.getStorageSync('recvMsgQueue')	
			// console.log('this.recvMsgQueue[0].actions=',this.recvMsgQueue[0].actions)	
		},
		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.id){
					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)
					this.sendSocketMessage(action.text,'','',action.id,image_id)
					let self = this
					setTimeout(function() {self.showLastMsg()}, 500);
				}
				
			},
			isRecvMsgFinish(showToast=true) {
				if(this.recvMsgQueue.length == 0) {
					return true
				}
				if(showToast) {
					uni.showToast({
						icon:'none',
						title:'正在生成中...',
						duration:1500,
					})
				}
				let isFinish = this.recvMsgQueue[this.recvMsgQueue.length - 1].isFinish
				return isFinish
			},			
			isHasChonghua(action) {
				if(action.includes(this.action_type.generate)) {
					// console.log('表示用户通过选择图片和输入框内容')
					return true
				} else if (action.includes(this.action_type.youhua)) {
					// console.log('优化 优化 优化 优化 优化')
					return true
				} else if (action.includes(this.action_type.fangda)) {
					// console.log('放大 放大 放大 放大 放大')
					return false
				}
				return false
			},
			clickonredraw() {
				// console.log('重画')
				// console.log('msg=', this.current_send.msg)
				// console.log('image_url=', this.current_send.image_url)
				// console.log('image_id=', this.current_send.image_id)
				// console.log('prompt=', this.current_send.prompt)
				// console.log('action=', this.current_send.action)
				let self = this
				uni.showModal({
					content:"是否重画",
					confirmText:'确定',
					cancelText:'取消',
					success:(res)=>{
						if(res.confirm){
							if(self.isRecvMsgFinish(false) == false) {
								return
							}
							
							if(self.isHasChonghua(self.current_send.action)) {
								self.sendSocketMessage(self.current_send.msg, 
								                       self.current_send.prompt,
													   self.current_send.image_url, 
													   self.current_send.action,
													   self.current_send.image_id)
								setTimeout(function() {self.showLastMsg()}, 500);
							} else {
								uni.showToast({
									icon:'error',
									title:'无法重画',
									duration:1500,
								})
							}
						}
					}
				})
			},	
			getImg(index){
				return this.recvMsgQueue[index].msg_img
			},
			onclickdelete(){
				if(this.isRecvMsgFinish() == false) {
					return
				}
				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.recvMsgQueue[self.recvMsgQueue.length-1].isFinish = true;
				self.stopUpdateView();
				self.copyUpdates();
				self.updateSrcList();
				setTimeout(function() {
					self.showLastMsg();
				}, 200);
			},
			async sendMsg(){
				if(this.choose_img_tempFilePath != '') {
					this.sendImageAndTextOperation()
					return
				}
				
				// 如果内容为空
				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)
				// console.log('msg=',msg, 'prompt=',prompt, 'des_img=',des_img, 'action=',action, 'image_id=',image_id)
				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();
				
				if(action.includes(this.action_type.generate)) {
					self.current_send.msg = msg
					self.current_send.image_url = des_img
					self.current_send.image_id = image_id
					self.current_send.prompt = prompt
					self.current_send.action = action
				}
				
				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)=>{
						console.log("Ai-view",res)
						if(res.statusCode===200){
							let html_img = '<!DOCTYPE html> <html><head></head><body> <img src='+res.data.image_url+ '></body></html>'
							let recvMsgQueue_lastIndex = self.recvMsgQueue.length-1
							self.recvMsgQueue[recvMsgQueue_lastIndex].msg_img = res.data.image_url;
							self.recvMsgQueue[recvMsgQueue_lastIndex].msg_text = "";
							self.recvMsgQueue[recvMsgQueue_lastIndex].image_id = res.data.image_id;
							console.log("res.data.actions",res.data.actions)
							self.recvMsgQueue[recvMsgQueue_lastIndex].actions = [];
							let list = [];
							list = res.data.actions;
							// for (var i = 0; i < list.length; i++) {
							// 	self.recvMsgQueue[recvMsgQueue_lastIndex].actions.push(list[i])
							// }
							
							// 如果不是放大,需要 'actons数据'和'重画按钮'和'之前有重画按钮隐藏' 
							let isHasChonghua = self.isHasChonghua(action)
							if(isHasChonghua == true) {
								for(var recvI = 0; recvI<self.recvMsgQueue.length; recvI++) {
									if(self.recvMsgQueue[recvI].has_chonghua == true) {
										self.recvMsgQueue[recvI].has_chonghua = false
									}
								}
							} 
							self.recvMsgQueue[recvMsgQueue_lastIndex].has_chonghua = isHasChonghua
							
							if(isHasChonghua == true) {
								for (var i = 0; i < list.length; i++) {
									let action = list[i]
									let dic = {}
									switch (action){
										case 'upsample1':
										    dic = {'id': action, 'text': '放大1'}
											break;
										case 'upsample2':
										    dic = {'id': action, 'text': '放大2'}
											break;
										case 'upsample3':
										    dic = {'id': action, 'text': '放大3'}
											break;
										case 'upsample4':
										    dic = {'id': action, 'text': '放大4'}
											break;
										case 'variation1':
										    dic = {'id': action, 'text': '优化1'}
											break;
										case 'variation2':
										    dic = {'id': action, 'text': '优化2'}
											break;
										case 'variation3':
										    dic = {'id': action, 'text': '优化3'}
											break;
										case 'variation4':
										    dic = {'id': action, 'text': '优化4'}
											break;
										default:
										    dic = {'id': action, 'text': action}
											break;
									}
									// console.log('action.dic=',dic)
									self.recvMsgQueue[recvMsgQueue_lastIndex].actions.push(dic)
								}
							}
								
						}else{
							uni.showModal({
								content:res.data.detail+":"+res.statusCode,
								showCancel:false
							})
							self.finish_recv()
							self.recvMsgQueue[self.recvMsgQueue.length-1].msg_text = res.data.detail;
						}
						self.finish_recv()
					},
					fail: (e) => {
						console.log('fail', e)
						self.recvMsgQueue[self.recvMsgQueue.length-1].msg_text ="生成失败";
						self.finish_recv()
					}
				})
			},
			onclickSendImg(index){
				let img_url = this.recvMsgQueue[index].des_img
				if(img_url) {
					uni.previewImage({
						urls:[img_url]
					})
				} else {
					uni.showToast({
						icon:'error',
						title:'预览图片失败',
						duration:2000
					})
				}
				
			},
			onclickAiGetImg(index){
				let img_url = this.getImg(index)
				if(img_url) {
					uni.previewImage({
						urls:[img_url]
					})
				} else {
					uni.showToast({
						icon:'error',
						title:'预览图片失败',
						duration:2000
					})
				}
			},
			onclickPreviewChooseImg() {
				let img_url = this.choose_img_tempFilePath
				if(img_url) {
					uni.previewImage({
						urls:[img_url]
					})
				} else {
					uni.showToast({
						icon:'error',
						title:'预览图片失败',
						duration:2000
					})
				}
			},
			onclickDeleteChooseImg() {
				let self = this
				uni.showModal({
					showCancel:true,
					content:"是否删除",
					success:(res)=>{
						if(res.confirm){
							self.choose_img_tempFilePath = ''							
						}
					}
				})
			},
			onclickchooseImg(event){
				if(this.isRecvMsgFinish() == false) {
					return
				}
				let self = this;
				uni.chooseImage({
					success: (chooseImageRes) => {
						const tempFilePaths = chooseImageRes.tempFilePaths;
						this.choose_img_tempFilePath = tempFilePaths[0]
						if(tempFilePaths.length > 0) {
							self.choose_img_tempFilePath = tempFilePaths[0]
						} else {
							uni.showToast({
								icon:'error',
								title:'图片选择失败,请重新选择',
								duration:2000
							})
						}
					}
				});
			},
			sendImageAndTextOperation() {
				if (this.inputValue.length == 0) {
					return uni.showToast({
						title: '请添加描述哦,只支持英文',
						icon: 'none'
					});
				}
				
				let self = this
				self.is_up_img_file = true
				// 上传图片+发送图片链接和文本
				// 上传图片
				uni.uploadFile({
					url: 'https://mlapi.hainanmlwl.com/file/upload_aiimg',
					filePath: self.choose_img_tempFilePath,
					name: 'aiimg_url',
					formData: {
						// 'aiimg_url': self.cur_select_img
					},
					success: (uploadFileRes) => {
						console.log("uploadFile",uploadFileRes);
						self.is_up_img_file = false;
						let obj = JSON.parse(uploadFileRes.data)
						// uni.showToast({
						// 	title:obj.message,
						// 	duration:1500
						// })
						
						if(obj.code == 10000) {
							let img_url = obj.content.surl
							if(img_url == '') {
								uni.showModal({
									content:"图片链接为空",
									showCancel:false
								})
								return
							} 
							
							if(self.choose_img_tempFilePath != '') {
								self.choose_img_tempFilePath = ''
							}
							
							// 发送
							self.sendSocketMessage(self.inputValue, img_url+" "+self.inputValue ,img_url)
							
						} else {
							uni.showModal({
								showCancel:false,
								content:obj.msg
							})
						}
					},
					fail(err) {
						console.log('上传失败err=',err)
						uni.showModal({
							content:"上传失败",
							showCancel:false
						})
						self.is_up_img_file = false;
					}
				});
			}
		
		}
	}
</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>


