<template src="./viewMask.html">

</template>
<script>
	const util = require('@/utils/util.js').default;
	// const config = require('@/services/url$config.js');
	import touchHandle from '@/mixins/touchHandle.js';
	// import requestConfig from '@/static/lib/requestConfig';
	// const app = getApp(); //获取应用实例
	export default {
		mixins: [touchHandle],
		data: function() {
			return {
				currentIndex:0,	//当前看到的图片序号
				showAIImage: false,//是否显示当前AI结果集合 默认不显示，因为没有
				aiImagesList:[
				],//AI生成的图片列表
				
				styleList: [], //风格列表数据
				curStyleIndex: 0, //当前选中的风格序号
				aiFlag:false,
				aiImage: "",
				inputBase64Url: "",
				taskId: "", // 图生图任务ID
				img2imgTimer: null,
				outTimer: null,
				imageWidth: 750,
				imageHeight: 448,
				showAIFlag:false,//继续生成状态切换标志
				checked:false,
				shottingImg:'',
				count:0,
				random:1,
				// disableAble:false,
				spaceTypes: [{
						icon: "",
						title: "卧室",
						subtitle: "0个布局",
						englishRemark: "bedroom",
					},
					{
						icon: "",
						title: "客厅",
						subtitle: "0个布局",
						englishRemark: "living room",
					},
					{
						icon: "",
						title: "餐厅",
						subtitle: "0个布局",
						englishRemark: "dinning room",
					},
					{
						icon: "",
						title: "厨房",
						subtitle: "0个个布局",
						englishRemark: "kitchen",
					},
					{
						icon: "",
						title: "玄关",
						subtitle: "0个布局",
						englishRemark: "hallway",
					},
					{
						icon: "",
						title: "卫生间",
						subtitle: "0个布局",
						englishRemark: "bathroom",
					},
					{
						icon: "",
						title: "衣帽间",
						subtitle: "0个布局",
						englishRemark: "walkin closet",
					},
					{
						icon: "",
						title: "收纳",
						subtitle: "0个布局",
						englishRemark: "storage room",
					},
					{
						icon: "",
						title: "阳台",
						subtitle: "0个布局",
						englishRemark: "balcony",
					},
					{
						icon: "",
						title: "飘窗",
						subtitle: "0个布局",
						englishRemark: "bay window",
					},
					{
						icon: "",
						title: "链接空间",
						subtitle: "0个布局",
						englishRemark: "connecting space between two rooms",
					},
					{
						icon: "",
						title: "自定义",
						subtitle: "0个布局",
						englishRemark: "room",
					},
				],
				myloading:false,
				loadingMsg:'',
				screenWidth:0,
				screenHeight:0,
				modelType:2,	//当前模型类型，1指创意设计 2指精准设计 默认2
				themeIndex:0,
				themeList:[
					{
						id:1,
						text:'默认',
						prot:'',
					},
					{
						id:2,
						leftColor:'#F4EBDE',
						rightColor:'#C1C9B4',
						text:'莫兰素雅',
						prot:'Soft grays, warm earth tones, subtle blues, soft pinks,',
					},
					{
						id:3,
						leftColor:'#1F1F1F',
						rightColor:'#FFFFFF',
						text:'经典黑白',
						prot:'Classic black and pure white,',
					},
					{
						id:4,
						leftColor:'#6FA5BE',
						rightColor:'#E2CCC5',
						text:'海岸珊瑚',
						prot:'Deep ocean blue paired with vibrant coral red,',
					},
					{
						id:5,
						leftColor:'#849059',
						rightColor:'#E6CEB4',
						text:'森林璀璨',
						prot:'Deep forest green paired with luxurious gold,'
					},
					{
						id:6,
						leftColor:'#A1BACB',
						rightColor:'#E6DFD8',
						text:'梦幻静谧',
						prot:'Dreamy powder blue paired with neutral gray,'
					},
					{
						id:7,
						leftColor:'#303B2B',
						rightColor:'#D8C8A6',
						text:'自然和谐',
						prot:'Natural olive green paired with warm beige,'
					},
					{
						id:8,
						leftColor:'#652C30',
						rightColor:'#D5C3B0',
						text:'醇酒乳香',
						prot:'Rich burgundy paired with soft cream,'
					},
					{
						id:9,
						leftColor:'#E3C7C5',
						rightColor:'#EDE4DB',
						text:'雅致浪漫',
						prot:'Understated taupe paired with romantic pink,'
					},
					{
						id:10,
						leftColor:'#2C3C6E',
						rightColor:'#F0DBBD',
						text:'夜空璀璨',
						prot:'Elegant navy blue paired with glamorous gold,'
					},
					{
						id:11,
						leftColor:'#ACC9A1',
						rightColor:'#E6DCC6',
						text:'复古翠绿',
						prot:'Vintage tan paired with vibrant green,'
					},
					{
						id:12,
						leftColor:'#AAA8A7',
						rightColor:'#D8A176',
						text:'暖阳灰影',
						prot:'Warm orange paired with cool gray,'
					},
					{
						id:13,
						leftColor:'#413D41',
						rightColor:'#D1B687',
						text:'耀眼黑金',
						prot:'black and gold,'
					},
				],
				timeOut:20000,		//超时时间
				subType:0,
				currentImg:null,
				reqList:[
					{
						model:'batouresearch/sdxl-controlnet-lora',
						level:'5',
						aiPicId:'',
						resultImg:'',
					},{
						model:'lucataco/sdxl-controlnet',
						level:'3',
						aiPicId:'',
						resultImg:'',
					}
				],
				reqListReset:[
					{
						model:'deployments/elabgroup/elab-sdxl-controlnet-lora',
						level:'5',
						aiPicId:'',
						resultImg:'',
					},{
						model:'batouresearch/sdxl-controlnet-lora',
						level:'3',
						aiPicId:'',
						resultImg:'',
					}
				],
				dialogVisible: false,
			}
		},
		props:{
			spaceObj: {
				type: Object,
				default: null,
			},
		},
		watch: {
			spaceObj(newVal, oldVal) {
				if (newVal == null) {
					return;
				}
				console.log("当前空间数据view-mark-watch:", newVal);
				this.getAiBeautyFamily();
				// this.curSpaceArea = parseFloat(
				// 	(newVal.spaceWidth * newVal.spaceHeight) / 10000
				// ).toFixed(2);
				// this.getOverallArrangementDetailsList();
			},
		},
		mounted() {//组件挂载时事件
			// console.warn("***mounted-nav***",this.seedItem)
			// if(this.seedItem){
			// 	this.title = this.seedItem.seedText;
			// }
			this.screenWidth = window.screen.width;
			this.screenHeight = window.screen.height;
			if(window.innerWidth && window.screen.width){
				this.screenWidth = Math.min(window.innerWidth,window.screen.width)
			}
			if(window.innerHeight && window.screen.height){
				this.screenHeight = Math.min(window.innerHeight,window.screen.height)
			}
		},
		// 页面被展示时执行
		onPageShow: function() {  
			
		},
		//页面被隐藏时执行
        onPageHide: function() {
        },
		beforeDestroy:function(){
			console.warn("***beforeDestroy***");//更新到页面上的数据
			this.clearInterval();
		},
		computed: {
			aiData() {
				return this.$store.state.aiData;
			},
			curHouseObj() {
				return this.$store.state.curHouseObj;
			},
		},
		methods:{
			swiperChangeImg(e){
				this.currentIndex = e.detail?e.detail.current:e;
				this.checked = this.aiImagesList[this.currentIndex].checked;
				console.warn("***swiperChangeImg***",this.checked);//更新到页面上的数据
			},
			//视角切换
			switchActor(){
				// this.$parent.clearHandle()
				this.$emit('switchActor');
				this.showAIImage = false;//隐藏AI结果集合-执行切换视角
				let index = this.$parent.currentActor.userIndex;//当前视角的序号
				let nextIndex = (index + 1) % this.$parent.actors.length;
				let param = {
					type: 'CLK', //埋点类型
					clkId: 'clk_2cmina_23080417', //点击ID
					clkName: 'changeangle_clk', //点击前往的页面名称
					clkParams: {
						locusName: "视角切换",
						type:this.$parent.actors[nextIndex].actorEum
					}
				};
				util.trackRequest(param);
			},
			showOrHideWebGl(){
				// this.$parent.clearHandle()
				this.showAIImage = !this.showAIImage;
				let param = {
					type: 'CLK', //埋点类型
					clkId: 'clk_2cmina_23080415', //点击ID
					clkName: 'contrast_clk', //点击前往的页面名称
					clkParams: {
						locusName: "对比",
					}
				};
				util.trackRequest(param);
			},
			//空间或者风格切换
			selectAction(selItem,type,index) {
				console.log('点击动作111：', selItem,type,index)
				var self = this;
				if(this.themeIndex == index){
					return false
				}
				this.themeIndex = index;
				let param = {
					type: 'CLK', //埋点类型
					clkId: 'clk_2cmina_23112701', //点击ID
					clkName: 'AIstyle_theme_clk', //点击前往的页面名称
					clkParams: {
						locusName: "AI 主题",
						type:this.themeList[this.themeIndex].text
					}
				};
				util.trackRequest(param);
			},
			//切换模式
			changeModel(){
				this.modelType = (this.modelType + 1) >2 ? 1 : 2;
			},
			//保存到相册
			save() {
			    //表示canvas正在绘制，不能进行保存
			    if (!this.aiImagesList || this.aiImagesList.length==0) {
			        return false;
			    }
				var _resultImg = this.aiImagesList[this.currentIndex].image;
			    //正在选择照片，不能生效
			    if (!_resultImg || _resultImg.length==0) {
					this.showToast("请选中图片后再试！");
			        return false;
			    }
			    var para = {
			        type: 'CLK', //埋点类型
			        clkId: 'clk_2cmina_56', //点击ID,固定
			        clkName: "share-savepic", //点击名称
			        expand: {
			            "resultImg": (_resultImg || ""),
			        },
			    }
			    util.trackRequest(para);
				if(navigator.userAgent.toLocaleLowerCase().includes('micromessenger')){
					this.$message("请长按图片保存！");
				}else{
					this.saveImageHandle(_resultImg);
				}
			},
			downloadIamge(imgsrc) {  //下载图片地址和图片名
				var fileName = "4DImage" + util.formatDate(new Date(), "yyyyMMddhhmmss") + '.jpg';
				const image = new Image();
				// 解决跨域 Canvas 污染问题
				image.setAttribute("crossOrigin", "anonymous");
				image.onload = ()=> {
					// let canvas = document.createElement("canvas");
					// canvas.width = image.width;
					// canvas.height = image.height;
					// const context = canvas.getContext("2d");
					// context.drawImage(image, 0, 0, image.width, image.height);
					// const url = canvas.toDataURL("image/jpg"); //得到图片的base64编码数据
					const a = document.createElement("a"); // 生成一个a元素
					const event = new MouseEvent("click"); // 创建一个单击事件
					a.download = fileName || "photo"; // 设置图片名称
					a.href = imgsrc; // 将生成的URL设置为a.href属性
					a.dispatchEvent(event); // 触发a的单击事件
					this.showToast("保存成功！");
				};
				image.src = imgsrc;
			},
			saveImageHandle(_resultImg){
				let param = {
					type: 'CLK', //埋点类型
					clkId: 'clk_2cmina_23080414', //点击ID
					clkName: 'download_clk', //点击前往的页面名称
					clkParams: {
						locusName: "下载",
						img:_resultImg
					}
				};
				util.trackRequest(param);
				this.downloadIamge(_resultImg);
			},
		
			//点赞喜欢
			changeAIImg() {
				// let lastPage = getCurrentPages()[getCurrentPages().length - 2] ? getCurrentPages()[getCurrentPages().length - 2].$vm : null;
				this.checked = !this.checked;//变更选项
				this.aiImagesList[this.currentIndex].checked = this.checked;
				console.warn("***changeAIImg***",this.checked,this.aiData)
				if(this.aiData){//给上一个页面回传生成的数据
					let space = this.aiData.find(it=>{
						return it.spaceId == this.spaceObj.spaceId
					})
					if(space){
						space.aiImagesList[this.currentIndex].checked = this.checked;
					}
				}
				if(this.checked){
					let param = {
						type: 'CLK', //埋点类型
						clkId: 'clk_2cmina_23080418', //点击ID
						clkName: 'chooseprogramme_clk', //点击前往的页面名称
						clkParams: {
							locusName: "选定风格/视角",
							style:this.styleList[this.curStyleIndex].styleName,
							img:this.aiImagesList[this.currentIndex].image,
						}
					};
					util.trackRequest(param);
				}
			},
			rightScroll(){//右滑
				if(this.currentIndex <= (this.aiImagesList.length - 1) && this.currentIndex > 0){
					// this.currentIndex --;
					this.$refs.carousel.prev();
				}
			},
			leftScroll(){//继续生成
				if(this.currentIndex != this.aiImagesList.length - 1){
					if(this.currentIndex<this.aiImagesList.length - 1){
						// this.currentIndex ++;
						this.$refs.carousel.next();
					}
					return false;
				}
				console.log("***leftScroll***",this.currentIndex,this.aiImagesList.length)
				this.aiSubmit(2);//继续生成下一张
			},
			//返回上一页
			goback(){
				this.$router.go(-1);
			},
			mynavigateFuc(e) {
				if (e) {
					// this.$parent.clearHandle();
					let param = {
						type: 'CLK', //埋点类型
						clkId: 'clk_2cmina_23080408', //点击ID
						clkName: 'WeCom_clk', //点击前往的页面名称
						clkParams: {
							locusName: "联系定制",
						}
					};
					util.trackRequest(param);
					if(window.__wxjs_environment === 'miniprogram'){
						wx.miniProgram.navigateTo({url: '/pages/transfer/transfer?event=openCustomerServiceChat&houseId='+this.$store.state.houseId})
					}else{
						this.$message.warning("敬请期待");
					}
				}
			},
			catchTapEvent:function(){
				return false;
			},
			//获取AI风格列表
			async getAiBeautyFamily() {
				// const spaceName = this.spaceTypes[this.spaceObj.spaceType - 1].title;
				let res = await requestConfig("getHardboundEffects", {
					"houseId": this.$route.query.houseId,
					"spaceType": this.spaceObj.spaceType,
					"spaceName": this.spaceObj.spaceName,
				});
				this.styleList = [];
				if (res.success) {
					let list = res.list;
					this.styleList = list;
				}
				if(!this.styleList || this.styleList.length==0){
					// this.disableAble = true;//不能点击-没有风格
					let unit = this.screenWidth / 750;//单位rpm 对应 px 的值
					this.$parent.canvasHeight = this.screenHeight - (208 * unit);
					this.$parent.camera.aspect = this.screenWidth / this.$parent.canvasHeight;
					this.$parent.camera.updateProjectionMatrix();
					this.$parent.renderer.setSize(this.screenWidth, this.$parent.canvasHeight);
				}else{
					// this.disableAble = false;//可以点击
				}
			},
			clearInterval() {
				if (this.img2imgTimer) {
					clearInterval(this.img2imgTimer);
					this.img2imgTimer = null;
				}
				this.random = 1;
				this.myloading = false;
			},
			//风格选择
			selectStyle(idx){
				if(this.curStyleIndex == idx){
					return false
				}
				this.curStyleIndex = idx;
				let param = {
					type: 'CLK', //埋点类型
					clkId: 'clk_2cmina_23080416', //点击ID
					clkName: 'AIstyle_ret_clk', //点击前往的页面名称
					clkParams: {
						locusName: "AI 风格",
						type:this.styleList[this.curStyleIndex].styleName
					}
				};
				util.trackRequest(param);
			},
			// AI渲染
			async aiSubmit(type) {
				if(!this.styleList || this.styleList.length==0 || this.curStyleIndex==-1
				|| !this.styleList[this.curStyleIndex].prompt || !this.styleList[this.curStyleIndex].negativePrompt){
					return false;
				}
				// 防止连续点击处理
				if (this.aiFlag) {
					return
				}
				this.aiFlag = true;
				if (this.aiImage == "" || !this.aiImage) {
					this.aiImage = ""; // https://dm.static.elab-plus.com/CE4/backImg.png
				}
				this.aiImage = "";
			
				this.clearInterval();
				if(!this.showAIImage){
					this.myloading = true;
					this.loadingMsg = "设计中...";
					// this.$store.state.loading = true;
					// this.$store.state.loadingMsg="设计中...";
				}
				
				// this.inputBase64Url = await this.shottingAction(2);//开始截图-返回的是base64的数据
				// this.startServer();
				// let base64 = await this.$parent.shottingAction(2);//开始截图-返回的是base64
				let shottingImg = await this.$parent.shottingAction();//开始截图-返回的是图片地址
				if(!shottingImg){
					this.showToast("渲染失败，请重试");
					return false;
				}
				// ?x-oss-process=image/auto-orient,1/quality,Q_46/format,jpg //阿里OSS
				// "?imageMogr2/auto-orient/format/webp/blur/1x0/quality/75";//七牛云压缩图片
				shottingImg += "?x-oss-process=image/auto-orient,1/quality,Q_46/format,jpg";//压缩图片
				this.shottingImg = shottingImg;
				this.changeImg2Base64(this.shottingImg, false);
				console.warn("***shottingImg***",this.shottingImg)
				if(type==1){
					let param = {
						type: 'CLK', //埋点类型
						clkId: 'clk_2cmina_23080413', //点击ID
						clkName: 'AIcreate_clk', //点击前往的页面名称
						clkParams: {
							locusName: "AI生成",
							userparamter:{
								shottingImg:this.shottingImg,
								style:this.styleList[this.curStyleIndex].styleName
							}
						}
					};
					util.trackRequest(param);
				}else{
					let param = {
						type: 'CLK', //埋点类型
						clkId: 'clk_2cmina_23080419', //点击ID
						clkName: 'continueAIcreate_clk', //点击前往的页面名称
						clkParams: {
							locusName: "继续生成",
							userparamter:{
								shottingImg:this.shottingImg,
								style:this.styleList[this.curStyleIndex].styleName
							}
						}
					};
					util.trackRequest(param);
				}
			},
			image2Base64(imgUrl) {//导入的图片路径
				var toBase64= new Promise(function(resolve, reject){
				    window.URL = window.URL || window.webkitURL;
				    var xhr = new XMLHttpRequest();
				    xhr.open("get", imgUrl, true);
				    // 至关重要
				    xhr.responseType = "blob";//文件流
				    xhr.onload = function (res) {
				        if (res.currentTarget.status == 200) {
				            //得到一个blob对象
				            var blob = res.currentTarget.response;
				            // 至关重要
				            let oFileReader = new FileReader();
				            oFileReader.onloadend = function (e) {
					            let base64 = e.target.result;//base64
					            resolve(base64)
				            };
				            oFileReader.readAsDataURL(blob);
				        }
			        }
				    xhr.send();
			    });
				return toBase64;
			},
			changeImg2Base64(url, isRepeat) {
				var self = this;
				if(isRepeat && self.inputBase64Url){//重复使用
					self.startServer();
				}else{
					self.startServer();
				}
			},
			//前置逻辑
			async prevHandle(parmas){
				return '';//暂不需要开启
				//不是首次请求，则无需前置判断 用户上传的也不需要前置处理
				if(this.subType!=0 || this.userInput){
					return '';
				}
				return new Promise(async (resolve, reject) => {
					let imgRes = await requestConfig("generateTaskImgToImgForAliyun", parmas);
					if (imgRes.success) {
						let aiPicId = imgRes.single || '';
						let res = await requestConfig('generateProcess', {
							id: aiPicId
						})
						if (res.success && res.single) {
							if(res.single.category == 'scheduler'){//命中了
								let resultImg = res.single.urls[0];
								resolve(resultImg);
							}else{
								resolve('');
							}
						}else{
							resolve('');
						}
					}else{
						resolve('');
					}
				})
			},
			//开始图生图流程
			async startServer() {
				if(!this.styleList || this.curStyleIndex < 0 || !this.styleList[this.curStyleIndex].imgUrl){
					return false
				}
				if(this.$parent.pvCurPageName!="room_show"){//说明用户切换页面了
					console.warn("***用户已经退出页面***")
					return false;
				}
				let imgUrl = this.styleList[this.curStyleIndex].imgUrl;
				let subType = this.subType;
				let session_hash = Date.now();
				let theme = this.themeList[this.themeIndex];//主题数据
				let prompt = this.styleList[this.curStyleIndex].prompt + theme.prot;
				let noPromot = this.styleList[this.curStyleIndex].negativePrompt;
				let unit = 768 / this.screenWidth;
				this.imageWidth = parseInt((this.screenWidth * unit).toFixed());
				this.imageHeight = parseInt((this.$parent.canvasHeight * unit).toFixed());
				this.timeOut = this.modelType==1? 20000: 50000;
				var parmas = {
					negativePrompt: noPromot,
					prompt: prompt,
					"batchSize": 1,
					brandId: $config.brandId,
					height: this.imageHeight,
					width: this.imageWidth,
					"moduleType": "AI_Biography",
					"steps":20,
					"sampler":"DDIM",
					"controlNetSessionHash":session_hash,
					"cfgScale":12,
					"denoising":0.9,
					image:this.shottingImg,
					styleImage:imgUrl,
					keyword: "replicate",
					model: this.modelType==1? "lucataco/ssd-1b" : 'catio-apps/controlnet-interior-design',
				};
				if(this.modelType==2){//精准设计
					if(subType == 0){//首次
						parmas.model = this.reqList[0].model;
					}else{//重试
						parmas.model = this.reqListReset[0].model;
					}
				}else{//创意设计
					if(subType == 0){//首次
						parmas.model = "lucataco/ssd-1b";
					}else{//重试
						parmas.model = "deployments/elabgroup/elab-ssd-1b";
					}
				}
				let result = await this.prevHandle(parmas);
				console.warn("***prevHandle***",result)
				if(result && result.length>0){
					this.randomHandle(result)
					return false;
				}else{
					if(this.modelType==2){//精准设计
						this.otherHandle(parmas);//发送其他AI请求
					}
					let res = await requestConfig("generateTaskImgToImgForAliyun", parmas);
					console.log("图生图结果：", res);
					let that = this;
					if (res.success && res.single) {
						this.taskId = res.single;
						if(this.modelType==2){//精准设计
							if(subType == 0){//首次
								this.reqList[0].aiPicId = this.taskId;
							}else{//重试
								this.reqListReset[0].aiPicId = this.taskId;
							}
						}
						if (!this.img2imgTimer) {
							this.count = 0;
							this.random = 1;
							this.currentImg = false;//当次生成图还没有结果
							this.img2imgTimer = setInterval(() => {
								this.count ++;
								this.getResultForImgToImg();
							}, 1000);
							this.setOutTimer();
						}
					}else{
						this.clearInterval()
						this.aiFlag = false;
						this.aiImage = "";
						this.showToast("渲染失败，请重试")
					}
				}
			},
			//随机处理
			randomHandle(resultImg){
				if(this.timer || !resultImg){
					return false;
				}
				let self = this;
				var count = 1;
				var process = 0;//进度
				var randomNum = Math.floor(Math.random() * 4 + 5);//5-8随机数
				this.img2imgTimer = setInterval(function() {
					process = parseInt(count * 100/(randomNum));
					if(process>=100){
						process = 99;
					}
					if (count < randomNum) {//没有到上限
						if(!self.showAIImage){
							// this.$store.state.loadingMsg='生成中…' + this.random + '%';
							self.loadingMsg = '生成中…' + process + '%';
						}
					}else{
						self.myloading = false;
						self.resultHandle(resultImg);
					}
					count = count + 1;
				}, 1000);
			},
			
			otherHandle(parmas){
				let reqList = [];
				if(this.subType == 0){//首次
					reqList = this.reqList;
				}else{//重试
					reqList = this.reqListReset;
				}
				reqList.forEach(async (it,index)=>{
					let _data = JSON.parse(JSON.stringify(parmas));
					if(index>0){
						_data.model = it.model;
						let res = await requestConfig("generateTaskImgToImgForAliyun", _data);
						if (res.success) {
							console.log('生成结果123：', res);
							it.aiPicId = res.single || '';
						}
					}
				})
			},
			//设置一个超时逻辑，到底指定时间后停止轮询，当前是90s
			setOutTimer() {
				if (this.outTimer) {
					clearTimeout(this.outTimer)
					this.outTimer = null
				}
				var self = this;
				this.outTimer = setTimeout(function() {
					if (self.img2imgTimer) {
						let hasResult = false;
						if(self.modelType==2){//精准设计
							let reqList = [];
							if(self.subType == 0){//首次
								reqList = self.reqList;
							}else{//重试
								reqList = self.reqListReset;
							}
							reqList.some((item,index) => {
								if(item.resultImg){
									hasResult = true;
									self.resultHandle(item.resultImg)
								}
							});
						}
						console.warn("***hasResult***",hasResult)
						if(!hasResult){//没有结果
							self.clearInterval();//停止轮询
							// self.$message.warning("AI开了个小差，请稍后再试");
							self.dialogVisible = true;//弹出超时提示
							self.aiFlag = false;
							self.aiImage = "";
						}
					}
					clearTimeout(self.outTimer);
					self.outTimer = null
				}, this.timeOut);
			},
			confirmHandle(){
				console.log('用户点击确定')
				this.dialogVisible = false;
				this.subType = 1;
				this.startServer();
			},
			cancelHandle(){
				console.log('用户点击取消')
				this.dialogVisible = false;
				this.subType = 0;
			},
			// 轮询获取图片结果
			async getResultForImgToImg() {
				if(this.modelType==2){//精准设计且当次新开始
					let reqList = [];
					if(this.subType == 0){//首次
						reqList = this.reqList;
					}else{//重试
						reqList = this.reqListReset;
					}
					reqList.forEach((item,index) => {
						this.singleHandle(item)
					});
				}
				else{
					this.singleHandle({aiPicId:this.taskId})
				}
			},
			async singleHandle(model){
				if(!model || !model.aiPicId){
					return false;
				}
				var parmas = {
					id: model.aiPicId,
				};
				let res = await requestConfig("generateProcess", parmas);
				if (res.success && res.single) {
					if(this.currentImg){//当前已经有生成图了
						console.warn("***当前已经有最高级生成图了***")
						return false;
					}
					if (res.single.urls) {
						console.warn("图生图轮询结束: ", res);
						if(this.modelType==2){//精准设计
							model.resultImg = res.single.urls[0];
							if(model.level=='5'){//最高级了
								this.currentImg = true;
								this.resultHandle(res.single.urls[0])
							}
						}else{
							this.resultHandle(res.single.urls[0])
						}
						console.warn("***有生成图了***",model)
						
					} else {
						if (!res.success) {
							this.showToast("渲染失败，请重试")
							this.aiFlag = false;
							this.aiImage = "";
							this.clearInterval();
						}else {
							// this.random = parseInt(this.count * 2);
							this.random = parseInt(this.count * 100/(this.timeOut/1000));
							if(this.random>=100){
								this.random = 99;
							}
							if(!this.showAIImage){
								// this.$store.state.loadingMsg='生成中…' + this.random + '%';
								this.loadingMsg = '生成中…' + this.random + '%';
							}else{
							}
						}
					}
				}
			},
			//返回结果处理
			resultHandle(resultImg){
				this.currentImg = true;
				this.aiFlag = false;
				this.random = 100;
				this.aiImage = resultImg;
				this.showAIFlag = true;
				let newImage = this.aiImage;
				let aiStyleName = this.styleList[this.curStyleIndex].styleName;
				let _data = {
					image:newImage,
					checked:false,
					list:[newImage],
				}
				this.aiImagesList.push(_data);
				this.showAIImage = true;//显示AI结果集合-因为生成了AI图片
				if(this.$parent && typeof(this.$parent.clearHandle)=="function" ){
					this.$parent.clearHandle();
				}
				let cpAiData = JSON.parse(JSON.stringify(this.aiData)) || []
				if(cpAiData && this.curHouseObj && this.curHouseObj.houseFloor){//给上一个页面回传生成的数据
					let space = cpAiData.find(it=>{
						return it.houseFloor == this.curHouseObj.houseFloor && it.spaceId == this.spaceObj.spaceId
					})
					if(space){
						let data ={
							aiStyleName:aiStyleName,
							image:newImage,
							checked:false,
						}
						space.aiImagesList.push(data);
					}else{//不存在则构建数据
						let data = {
							houseFloor:this.curHouseObj.houseFloor,//当前的楼层
							spaceId:this.spaceObj.spaceId,
							aiImagesList:[
								{
									aiStyleName:aiStyleName,
									image:newImage,
									checked:false,
								}
							]
						}
						cpAiData.push(data)
					}
					this.$store.dispatch('setAiData', cpAiData)
				}
				this.clearInterval();
				if(this.aiImagesList.length>1){
					setTimeout(()=>{
						// this.$refs.carousel.next();
						this.$refs.carousel.setActiveItem(this.aiImagesList.length-1);//切换到最后一张
					}, 1000);
				}
			},
			showToast(title,time=3000){
				this.$store.state.loading = true;
				this.$store.state.loadingMsg = title || "";
				setTimeout(()=>{
					this.$store.state.loading = false;
				}, time);
			}
		}
	}
</script>
<style lang="scss" scoped>
    @import "./viewMask.scss";
</style>
<style lang="css" scoped>
	/* @import "@/common/css/common.css"; */
</style>
