import {
	MessageBox
} from 'mint-ui';
import {
	Toast
} from 'mint-ui';
export default {
	data() {
		return {
			timeOut: 50000, //超时时间
			subType: 0, //0 首次 1 再次
			aiPicId: "", // 图生图任务ID
			count: 0, //轮询次数
			randomTimer: null,
			timer: null,
			currentImg: null, //当次生成图的结果
			startCreate:false,	//是否开始生成AI图了
			// myloading: false, //加载中
			loadingMsg: '', //加载中的话术
			reqList: [{
				model: 'batouresearch/sdxl-controlnet-lora',
				level: '5',
				aiPicId: '',
				resultImg: '',
			}],
			reqListReset: [{
				model: 'deployments/elabgroup/elab-sdxl-controlnet-lora',
				level: '3',
				aiPicId: '',
				resultImg: '',
			}, {
				model: 'batouresearch/sdxl-controlnet-lora',
				level: '5',
				aiPicId: '',
				resultImg: '',
			}],
			createTabIndex:0,	//生成AI图时记录下当前AI图的类型序号
			createOptionIndex:0,//生成AI图时记录下当前AI图的选项序号
			paramObj:null,	//启动参数-外界传进来的
		}
	},
	methods: {
		//前置逻辑
		async prevHandle(parmas) {
			//不是首次请求，则无需前置判断 用户上传的也不需要前置处理
			if (this.subType != 0) {
				return '';
			}
			return new Promise(async (resolve, reject) => {
				let _data = JSON.parse(JSON.stringify(parmas))
                _data.keyword = "zhiqite";
                _data.model = "controlnet";
				delete _data.webhook;
				let res = await requestConfig("img2img_local", _data);
				if (res.success) {
					if (res.success && res.single) {
						let resultImg = res.single;
						resolve(resultImg);
					} else {
						resolve('');
					}
				} else {
					resolve('');
				}
			})
		},
		//随机处理
		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.randomTimer = setInterval(function() {
				process = parseInt(count * 100 / (randomNum));
				if (process >= 100) {
					process = 99;
				}
				if (count < randomNum) { //没有到上限
					// self.myloading = true;
					self.loadingMsg = '生成中…' + process + '%';
				} else {
					// self.myloading = false;
					this.loadingMsg = '生成中…100%';
					self.resultHandle(resultImg);
				}
				count = count + 1;
			}, 1000);
		},
		//开始图生图流程
		async startServer(obj) {
			if (!obj || !obj.imgUrl || !obj.prompt || !obj.negativePrompt) {
				Toast({
					message: '数据不全',
				});
				return false
			}
			// if(this.$parent.pvCurPageName!="room_show"){//说明用户切换页面了
			// 	console.warn("***用户已经退出页面***")
			// 	return false;
			// }
			let imgUrl = obj.imgUrl;
			let subType = this.subType;
			let session_hash = Date.now();
			let prompt = obj.prompt;
			let noPromot = obj.negativePrompt;
			// let unit = 768 / this.screenWidth;
			// this.imageWidth = parseInt((this.screenWidth * unit).toFixed());
			// this.imageHeight = parseInt((this.$parent.canvasHeight * unit).toFixed());
			if(this.startCreate){
				return false
			}
			this.startCreate = true;
			this.paramObj = obj;
			this.loadingMsg = '启动中';
			this.createTabIndex = obj.tabIndex;
			this.createOptionIndex = obj.optionIndex;
			var parmas = {
				negativePrompt: noPromot,
				prompt: prompt,
				"batchSize": 1,
				brandId: $config.brandId,
				height: 512,
				width: 768,
				"moduleType": "AI_Biography",
				"steps": 20,
				"sampler": "DDIM",
				"controlNetSessionHash": session_hash,
				"cfgScale": 12,
				"denoising": 0.9,
				image: imgUrl,
				// styleImage:imgUrl,
				// keyword: "zhiqite",
                // model: 'controlnet',
                keyword: "elabSd",
				model: 'lucataco/ssd-1b',
			};
			let result = await this.prevHandle(parmas);
			console.warn("***prevHandle***", result)
			if (result && result.length > 0) { //匹配到了，则随机处理
				this.randomHandle(result)
				return false;
			} else {
				this.otherHandle(parmas); //发送其他AI请求
				let res = await requestConfig("generateTaskImgToImgForAliyun", parmas);
				console.log("图生图结果：", res);
				let that = this;
				if (res.success && res.single) {
					this.aiPicId = res.single;
					if (subType == 0) { //首次
						this.reqList[0].aiPicId = this.aiPicId;
					} else { //重试
						this.reqListReset[0].aiPicId = this.aiPicId;
					}
					if (this.aiPicId) {
						this.startInterval(); //开始轮询AI生成图的结果
					} else {
						this.stopInterval()
					}
				} else {
					this.stopInterval()
					// this.showToast("渲染失败，请重试")
				}
			}
		},
		stopInterval() {
			if (this.randomTimer) {
				clearInterval(this.randomTimer);
				this.randomTimer = null;
			}
			if (this.timer) {
				// clearInterval(this.timer);
				this.timer = null;
			}
			if (this.outTimer) {
				clearTimeout(this.outTimer)
				this.outTimer = null
			}
			this.subType = 0;
			this.reqList.forEach(it => {
				it.aiPicId = '';
				it.resultImg = '';
			})
			this.reqListReset.forEach(it => {
				it.aiPicId = '';
				it.resultImg = '';
			})
			// this.myloading = false;
			// this.aiFlag = false;
			this.startCreate = false;//释放标志
		},
		//从请求接口队列里面挨个发出请求
		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 || '';
					}
				}
			})
		},
		//开始生成AI图的轮询，每隔1s轮询一次
		startInterval() {
			if (this.timer) {
				return false;
			}
			let self = this;
			this.count = 1; //轮询次数
			var random = 0;
			this.currentImg = false; //当次生成图还没有结果
			this.timer = 1; //标志进入了轮询流程
			this.getOutPicture(); //不在轮询，而是等结果
			this.setOutTimer(); //设置超时逻辑
		},
		//设置一个超时逻辑，到底指定时间后停止轮询，当前是90s
		setOutTimer() {
			if (this.outTimer) {
				clearTimeout(this.outTimer)
				this.outTimer = null
			}
			var self = this;
			this.outTimer = setTimeout(function() {
				if (self.timer) {
					let hasResult = false;
					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.stopInterval(); //停止轮询
						MessageBox.confirm('', {
							title: '提示',
							message: '当前AI使用火爆，请继续尝试?',
							showCancelButton: true,
							confirmButtonText: '继续尝试',
							cancelButtonText: '取消等待',
						}).then(action => {
							console.warn("***MessageBox-action***", action)
							if (action == 'confirm') {
								self.confirmHandle(1);
							}
						}).catch(err => {
							console.warn("***MessageBox-err***", err)
							if (err == 'cancel') {
								self.cancelHandle();
							}
						});
					}
				}
				clearTimeout(self.outTimer);
				self.outTimer = null
			}, this.timeOut);
		},
		confirmHandle(type) {
			this.subType = type || 0;
			this.startServer(this.paramObj);
		},
		cancelHandle() {
			this.subType = 0;
		},
		//获取生成图结果
		getOutPicture() {
			if (this.timer == null) {
				console.warn("***当前轮询已经结束了1***")
				return false;
			}
			let reqList = [];
			if (this.subType == 0) { //首次
				reqList = this.reqList;
			} else { //重试
				reqList = this.reqListReset;
			}
			reqList.forEach((item, index) => {
				this.singleHandle(item)
			});
		},
		//发出获取结果请求获取AI生成结果
		async singleHandle(model) {
			if (!model || !model.aiPicId) {
				return false;
			}
			var parmas = {
				id: model.aiPicId,
			};
			let res = await requestConfig("getPredictions", parmas);
			if (res.success && res.single) {
				if (this.currentImg) { //当前已经有生成图了
					console.warn("***当前已经有最高级生成图了***")
					return false;
				}
				if (this.timer == null) {
					console.warn("***当前轮询已经结束了***")
					return false;
				}
				if (res.single.status == 'succeeded' && res.single.output) {
					model.resultImg = res.single.output; //把生成图结果记录到请求接口对象里面
					if (model.level == '5') { //最高级的生成图，可以直接用
						this.currentImg = true;
						setTimeout(() => {
							this.resultHandle(res.single.output)
						}, 1500)
					}
					console.warn("***有生成图了***", model)
				}
				if (model.level == '5') { //最高优先级的接口返回的结果
					this.processHandle(res.single);
				}
			} else if (!res.success && model.level == '5') { //最高优先级的接口返回失败
				this.stopInterval(); //停止轮询
				// this.showToast("渲染失败，请重试")
			}
		},
		//进度处理
		processHandle(single) {
			console.warn("***single***", single.status, single.progress, this.count, single);
			let self = this;
			if (single.status == 'starting') { //启动中的逻辑
				if (this.count >= 20) {
					this.stopInterval(); //停止轮询
					MessageBox.confirm('', {
						title: '提示',
						message: 'AI开了小差，是否重新生成?',
						showCancelButton: true,
						confirmButtonText: '继续生成',
						cancelButtonText: '放弃生成',
					}).then(action => {
						console.warn("***MessageBox-action***", action)
						if (action == 'confirm') { //继续生成
							this.confirmHandle(0);
						}
					}).catch(err => {
						if (err == 'cancel') {
							this.cancelHandle();
						}
					});
				} else {
					// this.myloading = true;
					this.loadingMsg = '启动中';
				}
				this.count = this.count + 1;
                setTimeout(()=>{
                    this.getOutPicture();
                },10000)
			} else if (single.status == 'processing') {
				let random = single.progress || 0;
				if (random >= 100) {
					random = 99;
				}
				// this.myloading = true;
				this.loadingMsg = '生成中…' + parseInt(random) + '%';
				setTimeout(()=>{
				    this.getOutPicture();
				},10000)
			} else if (single.status == 'succeeded') {
				// this.myloading = true;
				this.loadingMsg = '生成中…100%';
			}
		},
		//返回结果处理
		resultHandle(resultImg) {
			this.currentImg = true;
			this.aiImage = resultImg;
			this.stopInterval();
			let newImage = resultImg;
			// let aiStyleName = this.styleList[this.curStyleIndex].styleName;
			let _data = {
				imageUrl: newImage,
				checked: false,
				type:'AI',//表示AI生成的
			}
			// this.aiImagesList.push(_data);
			this.paramObj = null;//生成成功后，清楚外界传入参数
			// this.tabData[this.createTabIndex].options[this.createOptionIndex].hardboundEffect.push(_data);
			if (this.createTabIndex == this.tabIndex) {
				let len = this.aiImagesList.length;
				this.aiImagesList.push(_data);
				setTimeout(() => {
					this.$refs.carousel.setActiveItem(len); //切换到最后一张
				}, 200);
			}else{
				this.tabData[this.createTabIndex].options[this.createOptionIndex].hardboundEffect.push(_data);
			}
			// this.subDataList[this.tabIndex].hardboundEffect.push(_data);//把数据同步到对应的待提交对象中
		},
	}
}