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

</template>
<script>
	const util = require('@/static/utils/util.js');
	const config = require('@/static/config.js');
	import Bus from '@/common/bus';
	import commonMethod from '@/common/commonMethod.js';
	import requestConfig from '@/static/lib/requestConfig';
	// import screenshot from '@/webgl/mixins/screenshot.js';
	import { language } from '@/static/utils/conf.js'
	const plugin = requirePlugin("WechatSI");
	// import bgLoading from "@/components/bgLoading/bgLoading.vue"
	// import { nextTick } from "vue";
	// const app = getApp(); //获取应用实例
	// let positions = new Set();
	export default {
		data: function() {
			return {
				styleList: [], //风格列表数据
				curStyleIndex: 0, //当前选中的风格序号
				aiFlag:false,
				markImage:'',
				aiImage: "",
				maskBase64Url: "",
				inputBase64Url: "",
				timestamp: null,
				taskId: "", // 图生图任务ID
				img2imgTimer: null,
				imageWidth: 320,
				imageHeight: 448,
				showAIFlag:false,
				aiImagesIndex:0,
				checked: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",
					},
				],
			}
		},
		// mixins:[screenshot],
		props: {
			spaceObj: {
				type: Object,
				default: null,
			},
		},
		watch: {
			spaceObj(newVal, oldVal) {
				if (newVal == null) {
					return;
				}
				console.log("当前空间数据-watch:", newVal);
				// this.curSpaceArea = parseFloat(
				// 	(newVal.spaceWidth * newVal.spaceHeight) / 10000
				// ).toFixed(2);
				// this.getOverallArrangementDetailsList();
			},
		},
		// components:{
		// 	bgLoading
		// },
		async mounted() {
			// await this.getCityHouseList();
			const size = `${this.imageWidth}x${this.imageHeight}`;
			// this.markImage =
			// 	`https://test.static.elab-plus.com/AIBeautyHouse/mask/YYYY04DDHH1347.png?imageMogr2/auto-orient/thumbnail/!${size}r/gravity/Center/crop/${size}/interlace/1/blur/1x0/quality/100|imageslim`;
			console.log("图片尺寸:", this.imageWidth, this.imageHeight, this.markImage);
			console.log("当前空间数据:", this.spaceObj);
			// this.changeImg2Base64(this.markImage, true);
			this.getAiBeautyFamily();
			var currPage = getCurrentPages()[getCurrentPages().length - 1] ? getCurrentPages()[getCurrentPages().length - 1].$vm : null;
			Bus.$on("swiperChangeImg",(index)=>{
				this.aiImagesIndex = index;
				this.checked = currPage.aiImagesList[index].checked;
				console.warn("***swiperChangeImg***",index,this.checked)
			})
		},
		// 页面被展示时执行
		onPageShow: function() {

		},
		//页面被隐藏时执行
		onPageHide: function() {
			var currPage = getCurrentPages()[getCurrentPages().length - 1] ? getCurrentPages()[getCurrentPages()
				.length - 1].$vm : null;
			console.warn("***detached-hide***")

		},
		methods: {
			//选项变更
			changeAIImg() {
				let currPage = getCurrentPages()[getCurrentPages().length - 1] ? getCurrentPages()[getCurrentPages().length - 1].$vm : null;
				let lastPage = getCurrentPages()[getCurrentPages().length - 2] ? getCurrentPages()[getCurrentPages().length - 2].$vm : null;
				this.checked = !this.checked;//变更选项
				console.warn("***changeAIImg***",this.checked)
				currPage.aiImagesList[this.aiImagesIndex].checked = this.checked;
				if(lastPage){//给上一个页面回传生成的数据
					let space = lastPage.postAIData.find(it=>{
						return it.spaceId == this.spaceObj.spaceId
					})
					if(space){
						space.aiImagesList[this.aiImagesIndex].checked = this.checked;
					}
				}
			},
			
			catchTapEvent:function(){
				return false;
			},
			//获取AI风格列表
			async getAiBeautyFamily() {
				let res = await requestConfig("choiceList", {});
				this.styleList = [];
				if (res.success) {
					let list = res.list;
					for (let i = 0; i < list.length; i++) {
						if (list[i].title == "风格") {
							this.styleList = list[i].choiceList;
							console.log("AI风格", this.styleList);
						}
					}
				}
			},
			clearInterval() {
				uni.hideLoading();
				if (this.img2imgTimer) {
					clearInterval(this.img2imgTimer);
					this.img2imgTimer = null;
				}
			},
			// AI渲染
			async aiSubmit() {
				// 防止连续点击处理
				if (this.aiFlag) {
					return
				}
				this.aiFlag = true;
				let currPage = getCurrentPages()[getCurrentPages().length - 1] ? getCurrentPages()[getCurrentPages().length - 1].$vm : null;
				this.isHideAIImage = false;
				if (this.aiImage == "" || !this.aiImage) {
					this.aiImage = ""; // https://dm.static.elab-plus.com/CE4/backImg.png
				}
				this.aiImage = "";
				this.timestamp = new Date().getTime();
				console.log("this.timestamp: ", this.timestamp);
			
				this.clearInterval();
				uni.showLoading({
					title: "设计中...",
				});
				// this.inputBase64Url = await this.shottingAction(2);//开始截图-返回的是base64的数据
				// this.startServer();
				this.$emit('hideOrShowActor','hide');//隐藏所有视角
				let shottingImg = await currPage.shottingAction();//开始截图-返回的是图片
				shottingImg += "?imageMogr2/auto-orient/format/webp/blur/1x0/quality/75";//压缩图片
				this.changeImg2Base64(shottingImg, false);
				console.warn("***shottingImg***",shottingImg)
				this.$emit('hideOrShowActor','show');//显示选中的视角
			},
			clearAiImage() {
				this.spaceObj.aiImage = null;
				this.spaceObj.aiStyleName = null;
				this.aiImage = null;
			},
			changeImg2Base64(url, isMask) {
				var self = this;
				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);
						if (isMask) {
							self.maskBase64Url = Base64Url;
							console.log("生成maskBase64Url");
						} else {
							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.1,
					"number2": 0.1,
					"number3": 0.1,
					"number4": 1,
					"imageBase64": this.inputBase64Url
				}
				let res1 = await requestConfig("AIuploadImgControlNet", data);
				if(!res1 || !res1.single){
					uni.hideLoading();
					this.aiFlag = false;
					uni.showToast({
						icon: "none",
						title: "渲染失败，请重试",
					});
					this.aiImage = "";
					return false;
				}
				let session_hash = res1.single;
				data.model = "control_v11p_sd15_seg_fp16 [ab613144]";
				data.cpu =  "seg_ofade20k";
				data.session_hash = session_hash;
				
				let res2 = await requestConfig("AIuploadImgControlNet", data);
				if(!res2 || !res2.success){
					uni.hideLoading();
					this.aiFlag = false;
					uni.showToast({
						icon: "none",
						title: "渲染失败，请重试",
					});
					this.aiImage = "";
					return false;
				}
				
				const spaceType = this.spaceTypes[this.spaceObj.spaceType - 1].englishRemark;
				const spaceStyle = this.styleList[this.curStyleIndex].englishRemark;
				
				const prompt =
					"(((high resolution))),(((photography))),(((highly details))),(((realistic))),(((Sophisticated))),((master piece)),((best quality)),\n((decoration)),lamp,floor lamp,\nsense of tranquility and relaxation and vacation,\n(((designed in wabi-sabi style features))),\nMinimalist Furniture,Grey Textile,Simple Lighting,Minimalist Pendant Light,Abstract Art Decorations,a lot of indoor potted flowers and plants,\nMinimalist Furniture,Grey Textile,Simple Lighting,Minimalist Pendant Light,Abstract Art Decorations,a lot of indoor potted flowers and plants,living room,\n(((window and curtain))),tv,tv cabinet,sofa,tea table,carpet,(((cloesd entance door))),";
				const noPromot =
					"cluttered,paintings, (worst quality:2), (low quality:2), (normal quality:2), lowres,signature, blurry, drawing, sketch, poor quality, ugly, (text:2),(logo:2), pixelated, low resolution,Signature,soft,blurry,drawing,sketch,poor quality,ugly,text,typr,word,logo,pixelated,low resolution,saturated,high contrast,oversharpened,\tcomplex and chaotic home decoration accessories,large dark area,";
				var parmas = {
					negativePrompt: noPromot,
					prompt: prompt,
					"batchSize": 1,
					brandId: $config.brandId,
					height: this.imageHeight,
					width: this.imageWidth,
					"moduleType": "simple_and_quiet",
					"keyword":"elabSd",
					"steps":50,
					"sampler":"DDIM",
					"controlNetSessionHash":session_hash,
					"cfgScale":12,
					"denoising":0.6
				};
				let res = await requestConfig("generateTaskImgToImgForAliyun", parmas);
				console.log("图生图结果：", res);
				let that = this;
				if (res.success) {
					this.taskId = res.id;
					if (!this.img2imgTimer) {
						this.img2imgTimer = setInterval(() => {
							that.getResultForImgToImg();
						}, 1000);
					}
				}else{
					uni.hideLoading();
					this.aiFlag = false;
					uni.showToast({
						icon: "none",
						title: "渲染失败，请重试",
					});
					this.aiImage = "";
				}
			},
			// 轮询获取图片结果
			async getResultForImgToImg() {
				var parmas = {
					id: this.taskId,
				};
				let res = await requestConfig("generateProcess", parmas);
				let currPage = getCurrentPages()[getCurrentPages().length - 1] ? getCurrentPages()[getCurrentPages().length - 1].$vm : null;
				let lastPage = getCurrentPages()[getCurrentPages().length - 2] ? getCurrentPages()[getCurrentPages().length - 2].$vm : null;
				// console.log("图生图轮询结果：", res);
				if (res.success && res.single) {
					if (res.single.inQueue == false) {
						if (res.single.urls) {
							uni.hideLoading();
							this.aiFlag = false;
							console.log("图生图轮询结束: ", res.single.urls);
							this.aiImage = res.single.urls[0];
							this.showAIFlag = true;
							let newImage = this.aiImage;
							let aiStyleName = this.styleList[this.curStyleIndex].item;
							let _data = {
								image:newImage,
								checked:false,
							}
							currPage.aiImagesList.push(_data);//补充图片-只展示图片 风格不回传
							// currPage.$refs.viewMask.showAI();//显示AI结果图
							if(lastPage){//给上一个页面回传生成的数据
								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.aiImage = "";
								this.clearInterval();
							}
						}
					} else {
						uni.showToast({
							icon: "none",
							title: `${
								res.single.queueCount | 0
							}人排队中，预计等待${Math.round(Math.random() * 20)}秒`,
						});
						this.aiImage = "";
						this.aiFlag = false;
						this.clearInterval();
					}
				}
			},
			
		}
	}
</script>
<style lang="scss" scoped>
	@import "./viewStyle.scss";
</style>
<style lang="css" scoped>
	@import "@/common/css/common.css";
</style>