import { getTaskidResult } from '@/api/flow-canvas'
import { ElMessage } from 'element-plus'
import { updateVersionSketchUrlApi } from '@/api/flow-canvas'
import i18n from '@/lang'

// interface NodeOptions {
// }
const t = i18n.global.t

export class GenerateManager {
	stateManager: any
	taskIds: string[] = []
	getTaskIdsImgTime: any
	constructor(options) {
		this.stateManager = options.stateManager;
	}

	/** 删除taskId */
	deleteTaskId(taskId: string) {

	}
	/** 添加taskId */
	addTaskId(generateData: any,nodeId: string) {
		this.taskIds.push({
			...generateData,
			nodeId,
		})
		this.getTasksIdImg()
	}
	/** 添加taskId */
	async getTasksIdImg() {
		clearInterval(this.getTaskIdsImgTime)
		this.getTaskIdsImgTime = setInterval(()=>{
			const taskIds = this.taskIds.map((item)=>item.taskId)
			getTaskidResult({taskIds}).then((rv:any)=>{
				//找出成功和失败的任务
				const returnedTasks = rv.filter((item)=>item.status == 'RETURNED' || item.status == 'FAILED')
				if(returnedTasks.length == 0)return
				//剔除调成功的
				const taskIds_ = JSON.parse(JSON.stringify(this.taskIds))
				this.taskIds = taskIds_.filter(itemA => 
					!returnedTasks.some(itemB => itemB.taskId === itemA.taskId)
				)
				//把成功的提取出来并且更新到node中
				const result = returnedTasks.filter(itemA => 
					taskIds_.some(itemB => {
						itemA.nodeId = itemB.nodeId
						return itemB.taskId === itemA.taskId
					})
				)
				result.forEach(item => {
					this.stateManager.getNodeById(item.nodeId).data.data.imageProcessTasks.forEach((nodeDataItem:any)=>{
						if(item.taskId == nodeDataItem.taskId){
							if(item.status == 'FAILED'){
								this.stateManager.deleteNode(item.nodeId)
								ElMessage.error(item.errorMessage)	
							}else if(item.status == 'RETURNED'){
								nodeDataItem.url = item.url
								nodeDataItem.createTime = item.createTime
								nodeDataItem.status = item.status
								//更新VersionNode的sketchIDAndUrl中指定key的URL值
								updateVersionSketchUrlApi({
									sketchId: this.stateManager.sketchId.value,
									newUrl: item.url,
								}).then(()=>{
									//更新VersionNode的versionImgUpdataList中指定key的URL值
									let initialNode = this.stateManager.getInitialNode()
									initialNode.data.versionImgUpdataList.push(item.url)
								})
								if(item.glbPath){
									nodeDataItem.glbPath = item.glbPath
									nodeDataItem.glbInfoObj = item.glbInfoObj
								}
								ElMessage.success(t('FlowCanvas.generateSuccess'))	
							}
						}
					})
				})
				
				if(this.taskIds.length == 0)clearInterval(this.getTaskIdsImgTime)
			}).catch(()=>{
				clearInterval(this.getTaskIdsImgTime)
				console.warn('获取taskId图片失败')
			})
		}, 3000)
	}
	/** 更新taskId */
	updateTaskId(taskId: string) {
		this.stateManager.getNodeById()
	}
	
	dispose() {
		this.taskIds = []
		clearInterval(this.getTaskIdsImgTime)
	}
}
