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

</template>
<script>
	const util = require('@/utils/util.js').default;
	const config = require('@/services/urlConfig.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,
				imageWidth: 320,
				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",
					},
				],
			}
		},
		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;
			// }
		},
		// 页面被展示时执行
		onPageShow: function() {  
			
		},
		//页面被隐藏时执行
        onPageHide: function() {
        },
		beforeDestroy:function(){
			console.warn("***beforeDestroy***");//更新到页面上的数据
			this.clearInterval();
		},
		methods:{
			swiperChangeImg(e){
			    console.log(e);
				this.currentIndex = e.detail.current;
				this.checked = this.aiImagesList[this.currentIndex].checked;
				console.warn("***changeAIImg***",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);
				setTimeout(()=> {
					if(this.showAIImage==true){
						this.$parent.clearHandle()
					}else{
						this.$parent.attendEvent()
					}
				}, 100);
			},
			//保存到相册
			save() {
			    //表示canvas正在绘制，不能进行保存
			    if (!this.aiImagesList || this.aiImagesList.length==0) {
			        return false;
			    }
				var _resultImg = this.aiImagesList[this.currentIndex].image;
			    //正在选择照片，不能生效
			    if (!_resultImg || _resultImg.length==0) {
					// uni.showToast({
					//     title: "请选中图片后再试!",
					//     icon: 'none',
					//     duration: 1500,
					// })
					this.$store.state.loadingMsg="请选中图片后再试";
			        return false;
			    }
			    let that = this;
			    var para = {
			        type: 'CLK', //埋点类型
			        clkId: 'clk_2cmina_56', //点击ID,固定
			        clkName: "share-savepic", //点击名称
			        expand: {
			            "resultImg": (_resultImg || ""),
			        },
			    }
			    util.trackRequest(para);
			    uni.getSetting({
			        success: (response) => {
			            console.log("***rtcroomCom.onLoad***getSetting", response)
			            // 没有授权
			            if (!response.authSetting['scope.writePhotosAlbum']) {
			                console.warn("***scope.writePhotosAlbum-false***")
			                uni.authorize({
			                    scope: 'scope.writePhotosAlbum',
			                    success() {
			                        that.saveImageHandle(_resultImg);
			                    },
			                    fail(res) {
			                        console.log("***scope.writePhotosAlbum***")
			                        uni.hideLoading();
			                    }
			                })
			            } else {
			                console.log("***scope.writePhotosAlbum-ok***")
			                that.saveImageHandle(_resultImg);
			            }
			        }
			    })
			},
			saveImageHandle(_resultImg){
				let param = {
					type: 'CLK', //埋点类型
					clkId: 'clk_2cmina_23080414', //点击ID
					clkName: 'download_clk', //点击前往的页面名称
					clkParams: {
						locusName: "下载",
						img:_resultImg
					}
				};
				util.trackRequest(param);
				//表示图是临时文件，则可以直接保存
				if (_resultImg.startsWith("http://tmp/") || _resultImg.startsWith("wxfile://")) {
				    uni.saveImageToPhotosAlbum({
				        filePath: _resultImg,
				        success(result) {
				            // uni.hideLoading();
				            // uni.showToast({
				            //     title: "保存成功！",
				            //     icon: 'success',
				            //     duration: 1500,
				            // })
							this.$store.state.loadingMsg="保存成功！";
				        },
				        fail(err) {
				            uni.hideLoading();
				        }
				    })
				} else { //表示该图是网络图片，需要先下载才能保存
				    console.log("***getSetting.save***网络图片", _resultImg);
				    uni.downloadFile({
				        url: _resultImg,
				        success: function(res) {
				            uni.saveImageToPhotosAlbum({
				                filePath: res.tempFilePath,
				                success(result) {
				                    // uni.hideLoading();
				                    // uni.showToast({
				                    //     title: "保存成功！",
				                    //     icon: 'success',
				                    //     duration: 1500,
				                    // })
									this.$store.state.loadingMsg="保存成功！";
				                },
				                fail(err) {
				                    uni.hideLoading();
				                }
				            })
				        },
				        fail(err) {
				            uni.hideLoading();
				        }
				    });
				}
			},
		
			//选项变更
			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)
				if(lastPage){//给上一个页面回传生成的数据
					let space = lastPage.postAIData.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);
				}
			},
			leftScroll(){//继续生成
				if(this.currentIndex != this.aiImagesList.length - 1){
					return false;
				}
				console.log("***leftScroll***",this.currentIndex,this.aiImagesList.length)
				this.aiSubmit(2);//继续生成下一张
			},
			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,
				});
				this.styleList = [];
				if (res.success) {
					let list = res.list;
					this.styleList = list;
				}
				if(!this.styleList || this.styleList.length==0){
					this.disableAble = true;//不能点击-没有风格
					let unit = app.globalData.systemInfo.screenWidth / 750;//单位rpx 对应 px 的值
					this.$parent.canvasHeight = app.globalData.systemInfo.screenHeight - (208 * unit);
					this.$parent.camera.aspect = app.globalData.systemInfo.screenWidth / this.$parent.canvasHeight;
					this.$parent.camera.updateProjectionMatrix();
					this.$parent.renderer.setSize(app.globalData.systemInfo.screenWidth, this.$parent.canvasHeight);
				}else{
					this.disableAble = false;//可以点击
				}
			},
			clearInterval() {
				if (this.img2imgTimer) {
					clearInterval(this.img2imgTimer);
					this.img2imgTimer = null;
					this.random = 1;
				}
			},
			//风格选择
			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){
					// uni.showLoading({
					// 	title: "设计中...",
					// });
					this.$store.state.loadingMsg="设计中...";
				}
				
				// this.inputBase64Url = await this.shottingAction(2);//开始截图-返回的是base64的数据
				// this.startServer();
				// if(type==1){//AI生成时，重新截图，继续生成时，不重新截图
					this.$emit('hideOrShowActor','hide');//隐藏所有视角
					let base64 = await this.$parent.shottingAction(2);//开始截图-返回的是base64
					// let shottingImg = await this.$parent.shottingAction(2);//开始截图-返回的是base64
					// shottingImg += "?imageMogr2/auto-orient/format/webp/blur/1x0/quality/75";//压缩图片
					// this.shottingImg = shottingImg;
					this.$emit('hideOrShowActor','show');//显示选中的视角
				// }
				this.changeImg2Base64(base64, 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);
				}
			},
			changeImg2Base64(Base64Url, isRepeat) {
				var self = this;
				if(isRepeat && self.inputBase64Url){//重复使用
					self.startServer();
				}else{
					self.inputBase64Url = Base64Url;
					console.log("生成inputBase64Url");
					self.startServer();
					// uni.request({
					// 	url: url,
					// 	method: "GET",
					// 	responseType: "arraybuffer",
					// 	success: async (res) => {
					// 		let base64 = wx.arrayBufferToBase64(res.data);
					// 		let Base64Url = "data:image/jpeg;base64," + base64;
					// 		// console.log('base64：', Base64Url);
					// 		self.inputBase64Url = Base64Url;
					// 		console.log("生成inputBase64Url");
					// 		self.startServer();
					// 	},
					// });
				}
			},
			//开始图生图流程
			async startServer() {
				let data = {
					"configType": "ControlNet_Config",
					"keyvalue": "mix混合风_controlnet_upload",
					"server": "simple_and_quiet",
					"model": "control_v11p_sd15_mlsd_fp16 [77b5ad24]",
					"cpu": "mlsd",
					"session_hash": Date.now(),
					"weight": 0.8,
					"number1": 0.2,
					"number2": 1,
					"number3": 0.1,
					"number4": 1,
					"imageBase64": this.inputBase64Url
				}
				let res1 = await requestConfig("AIuploadImgControlNet", data);
				if(!res1 || !res1.single){
					this.aiFlag = false;
					this.$store.state.loadingMsg="渲染失败，请重试";
					this.aiImage = "";
					return false;
				}
				let session_hash = res1.single;
				data.model = "control_v11p_sd15_seg_fp16 [ab613144]";
				data.cpu =  "seg_ofade20k";
				data.weight =  0.5;
				data.number1 =  0.1;
				data.number2 =  0.2;
				data.number3 =  0;
				data.number4 =  0.1;
				data.session_hash = session_hash;
				
				let res2 = await requestConfig("AIuploadImgControlNet", data);
				if(!res2 || !res2.success){
					this.aiFlag = false;
					this.$store.state.loadingMsg="渲染失败，请重试";
					this.aiImage = "";
					return false;
				}
				
				const prompt = this.styleList[this.curStyleIndex].prompt;
				const noPromot = this.styleList[this.curStyleIndex].negativePrompt;
				
				var parmas = {
					negativePrompt: noPromot,
					prompt: prompt,
					"batchSize": 1,
					brandId: config.brandId,
					height: this.imageHeight,
					width: this.imageWidth,
					"moduleType": "simple_and_quiet",
					"keyword":"img_2_img",
					"steps":50,
					"sampler":"DDIM",
					"controlNetSessionHash":session_hash,
					"cfgScale":12,
					"denoising":0.9
				};
				let res = await requestConfig("generateTaskImgToImgForAliyun", parmas);
				console.log("图生图结果：", res);
				if(this.$parent.pvCurPageName!="room_show"){//说明用户切换页面了
					console.warn("***用户已经退出页面***")
					return false;
				}
				let that = this;
				if (res.success && res.single) {
					if(typeof(res.single)=="object"){
						// uni.showToast({
						// 	icon: "none",
						// 	title: `${
						// 		res.single.queueCount | 0
						// 	}人排队中，预计等待${Math.round(Math.random() * 20)}秒`,
						// });
						this.$store.state.loadingMsg=`${res.single.queueCount | 0 }人排队中，预计等待${Math.round(Math.random() * 20)}秒`;
						this.aiImage = "";
						this.aiFlag = false;
						this.clearInterval();
						return false;
					}
					this.taskId = res.single;
					if (!this.img2imgTimer) {
						this.count = 0;
						this.random = 1;
						this.img2imgTimer = setInterval(() => {
							this.count ++;
							this.getResultForImgToImg();
						}, 1000);
					}
				}else{
					this.aiFlag = false;
					// uni.showToast({
					// 	icon: "none",
					// 	title: "渲染失败，请重试",
					// });
					this.$store.state.loadingMsg="渲染失败，请重试";
					this.aiImage = "";
				}
			},
			// 轮询获取图片结果
			async getResultForImgToImg() {
				var parmas = {
					id: this.taskId,
				};
				let res = await requestConfig("generateProcess", parmas);
				let lastPage = getCurrentPages()[getCurrentPages().length - 2] ? getCurrentPages()[getCurrentPages().length - 2].$vm : null;
				// console.warn("图生图轮询结果：", res);
				if (res.success && res.single) {
					if (res.single.inQueue == false) {
						if (res.single.urls) {
							uni.hideLoading();
							this.aiFlag = false;
							this.random = 100;
							console.warn("图生图轮询结束: ", res);
							this.aiImage = res.single.urls[0];
							this.showAIFlag = true;
							let newImage = this.aiImage;
							let aiStyleName = this.styleList[this.curStyleIndex].styleName;
							let _data = {
								image:newImage,
								checked:false,
							}
							this.aiImagesList.push(_data);
							this.showAIImage = true;//显示AI结果集合-因为生成了AI图片
							if(this.$parent && typeof(this.$parent.clearHandle)=="function" ){
								this.$parent.clearHandle();
							}
							if(lastPage && lastPage.postAIData){//给上一个页面回传生成的数据
								let space = lastPage.postAIData.find(it=>{
									return it.houseFloor == lastPage.curHouseFloor && it.spaceId == this.spaceObj.spaceId
								})
								if(space){
									let data ={
										aiStyleName:aiStyleName,
										image:newImage,
										checked:false,
									}
									space.aiImagesList.push(data);
								}else{//不存在则构建数据
									let data = {
										houseFloor:lastPage.curHouseFloor,//当前的楼层
										spaceId:this.spaceObj.spaceId,
										aiImagesList:[
											{
												aiStyleName:aiStyleName,
												image:newImage,
												checked:false,
											}
										]
									}
									lastPage.postAIData.push(data)
								}
							}
							this.clearInterval();
						} else {
							if (!res.success) {
								// uni.hideLoading();
								this.aiFlag = false;
								// uni.showToast({
								// 	icon: "none",
								// 	title: "渲染失败，请重试",
								// });
								this.$store.state.loadingMsg="渲染失败，请重试";
								this.aiImage = "";
								this.clearInterval();
							}else {
								this.random = parseInt(this.count * 2);
								if(this.random>100){
									this.random = 99;
								}
								if(!this.showAIImage){
									// uni.showLoading({
									// 	icon: 'loading',
									// 	title: '生成中…' + this.random + '%'
									// })
									this.$store.state.loadingMsg='生成中…' + this.random + '%';
								}else{
									uni.hideLoading();
								}
							}
						}
					} else {
						this.$store.state.loadingMsg=`${res.single.queueCount | 0}人排队中，预计等待${Math.round(Math.random() * 20)}秒`;
						this.aiImage = "";
						this.aiFlag = false;
						this.clearInterval();
					}
				}
			},
			
		}
	}
</script>
<style lang="scss" scoped>
    @import "./viewMask.scss";
</style>
<style lang="css" scoped>
	/* @import "@/common/css/common.css"; */
</style>
