<template>
	<div class="poseTransfer">
		<div class="configuratioBox" :class="{active:button.left}">
			<div class="configuratio">
				<div class="title">Give pose for them to select</div>
				<div class="content">
					<!-- <selectList @selectImgItem="selectImgItem" level1Type="Printboard" type="print"></selectList> -->
					<div class="selectImg">
						<div class="head">
							<div class="text">Current</div>
						</div>
						<div class="imgBox">
							<div class="item" :class="{active:item.id == selectImg.id}" v-for="item in currentList" @click="selectImgItem(item)">
								<img :src="item.imgUrl || item.url" alt="">	
							</div>
							<div class="item" :class="{active:item.id == selectImg.id}" v-for="item in fileList" @click="selectImgItem(item)">
								<img :src="item.imgUrl || item.url" alt="">	
							</div>
							<div class="upload_item item">
								<div class="upload_file_item">
									<a-upload
										:action="getUploadUrl() + '/api/history/toProductImageElementUpload'"
										list-type="picture-card"
										:capture="null"
										:data="{
											...upload,
										}"
										:headers="{ Authorization: token }"
										:before-upload="beforeUpload"
										v-model:file-list="fileList"
										:multiple="true"
										accept=".jpg,.png,.jpeg,.bmp"
										@change="(file) => fileUploadChange(file)"
									>
										<div
											class="upload_tip_block"
										>
											<i class="fi fi-br-upload"></i>
											<!-- <img class="upload_img_icon" src="@/assets/images/homePage/add_file.png"> -->
										</div>
									</a-upload>
								</div>	
							</div>

						</div>
					</div>
					<div class="poses">
						<div class="head">
							<div class="text">Target poses</div>
						</div>
						<div class="imgBox">
							<div class="item" v-for="item in currentList">
								<img :src="item.imgUrl" alt="">	
							</div>
						</div>
					</div>
				</div>	
			</div>
			<div class="generate">
				<div class="gallery_btn" v-show="!isGenerate" @click="getgenerate">
					{{ $t('Generate.Generate') }}
				</div>
				<div v-show="isGenerate && !remGenerate" class="gallery_btn">
					<i class="fi fi-br-loading"></i>
				</div>
				<div v-show="remGenerate" @click="removeGenerate" class="gallery_btn">
					{{$t('Generate.Close')}}
				</div>
			</div>
		</div>
		<div class="likeBox">
			<div class="element">
				<div class="title">Selected Product</div>
				<div class="content">
					<generalDrag ref="generalDragLeft" v-if="isState" :list="likeList" :isVideo="true" @setBtn="likeSetBtn"></generalDrag>
				</div>
				<div class="btnLeft" @click="setSize('left')">
					<span class="icon iconfont icon-xiala" :class="{'active':button.left}"></span>
				</div>
				<div class="btnRight" @click="setSize('right')">
					<span class="icon iconfont icon-xiala" :class="{'active':button.right}"></span>
				</div>
			</div>
		</div>
		<div class="noLikeBox" :class="{active:button.right}">
			<div class="element">
				<div class="title">Generate Product</div>
				<div class="content">
					<generalDrag ref="generalDragRight" v-if="isState" :list="noLikeList" :isVideo="true" @setBtn="noLikeSetBtn"></generalDrag>
				</div>
			</div>
		</div>
	</div>
</template>
<script lang="ts">
import { defineComponent,computed,ref,inject,nextTick,createVNode,toRefs, reactive, onMounted} from 'vue'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { Https } from "@/tool/https";
import { useStore } from "vuex";
import { Upload,message,Modal } from 'ant-design-vue';
import { useI18n } from 'vue-i18n'
import generalDrag from '@/component/modules/generalDrag.vue';
import { getUploadUrl,isMoible,getMinioUrl } from "@/tool/util";
import { getCookie,setCookie } from "@/tool/cookie";
import  showViewVideo from "@/tool/mount";

// import selectList from '@/component/DetailCopy/module/selectList.vue';
export default defineComponent({
	components:{
		generalDrag,
		// selectList,
	},
	props:{
		isState:{
			type:Boolean,
			default:false,
		}
	},
	emits:[],
	setup(props,{emit}) {
		const {t} = useI18n()
		const store = useStore();
		const data:any = reactive({
			button:{
				left:false,
				right:false,
			},
			currentList:[],
			fileList:[],
			selectImg:{},
			token:getCookie('token'),
			upload:{
				projectId:store.state.Workspace.probjects.id
			},
			waitList:[],
			likeList:computed(()=>store.state.HomeStoreModule.poseTransfer),
			noLikeList:[{id:1},{id:2},{id:3},{id:4},{id:5},{id:6},],
			isGenerate:false,//判断是否正在进行generate
			remGenerate:false,
			removeGenerate:false,
		})
		const setIsShowMark:any = inject('setIsShowMark')
		const dataDom = reactive({
			generalDragLeft:null as any,
			generalDragRight:null as any,
			scaleVideo:null as any,
		})
		const selectImgItem = (item:any)=>{
			data.selectImg = item
			data.selectImg.minioUrl = getMinioUrl(item.url)
		}
		const openSetData = ()=>{
			// dataDom.generalDrag.openSetData()
			data.currentList = store.state.UploadFilesModule.modularData.toProduct
			setIsShowMark(false)
		}
		const setSize = (str:any)=>{
			data.button[str] = !data.button[str]
			setItemPosition()
		}
		const setItemPosition = ()=>{
			setTimeout(()=>{
				dataDom.generalDragLeft.setItemPosition()
				dataDom.generalDragRight.setItemPosition()
			},200)
		}
		const getgenerate = ()=>{
			if(!data.selectImg.minioUrl)return
			if(data.isGenerate)return

			data.isGenerate = true
			data.remGenerateTime = setTimeout(()=>{
				data.remGenerate = true
			},10000)
			let value = {
				poseId:1,
				projectId:store.state.Workspace.probjects.id,
				productImage:data.selectImg.minioUrl,
			}
			Https.axiosGet(Https.httpUrls.poseTransform,{params:value}).then((rv)=>{
				data.noLikeList.unshift({taskId:rv})
				setGenerate(rv)
			}).catch((res:any)=>{
				data.isGenerate = false
				clearInterval(data.remGenerateTime)
				data.remGenerate = false
			})
		}
		const setGenerate = (dataList:any)=>{
			let list = dataList
			let dataNum = dataList.length
			let state = true
			data.generateTime = setInterval(()=>{
				if(!data.isGenerate || data.remGenerate)return
				if(!state)return
				state = false
				Https.axiosGet(Https.httpUrls.poseTransformResult,{params:{taskId:list}}).then(
					(rv) => {
						rv=[rv]
						state = true
						if(data.isGenerate){//防止取消后有正在执行的获取状态
							// data.waitList = rv.filter((item:any)=>item.status != 'Success' && item.status != 'Fail' && item.status != 'Invalid')
							rv.forEach((element:any) => {
								if(element.status == 'Success'){
									element.url = element.firstFrameUrl
									let index = data.noLikeList.findIndex((obj:any) => obj.taskId === element.taskId);
									data.noLikeList[index] = element
									list = list.filter((item:any) => item !== element.taskId);
								}
							});
							data.waitList = list
							if((list.length == 0)|| (rv.filter((item:any)=>item.status == 'Invalid').length ==list.length)){
								if(rv.filter((item:any)=>item.status == 'Invalid').length ==dataNum){
									message.info(t('Generate.effectPoor'));
								}else{
								}
								
								// this.store.dispatch('getCredits')
								clearInterval(data.generateTime)
								clearInterval(data.remGenerateTime)
								data.remGenerate = false
								data.isGenerate = false
							}
						}
					}
				).catch(res=>{
					clearInterval(data.generateTime)
					clearInterval(data.remGenerateTime)
					data.isGenerate = false
					data.remGenerate = false
				});
			},1000)
		}
		const removeGenerate = ()=>{
			//取消操作
			data.isGenerate = false
			data.remGenerate = false
			clearInterval(data.generateTime)
			if(data.waitList){
				// let str = data.waitList.map((obj:any) => obj.taskId).join(',');
				let value = {
					uniqueId:data.waitList,
					userId:store.state.UserHabit.userDetail.userId,
					timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,
					type: 'PoseTransferation'
				}
				Https.axiosGet(Https.httpUrls.generateStopWaiting, {params:value}).then(
					(rv) => {
						data.waitList = []
						data.noLikeList = data.noLikeList.filter((item:any)=>item.status == 'Success')
					}
				).catch(res=>{
				});
			}
		}
		let beforeUpload = (file: any)=>{
            const isJpgOrPng =
                file.type === "image/jpeg" ||
                file.type === "image/png" ||
                file.type === "image/jpg" ||
                file.type === "image/bmp";
            if (!isJpgOrPng) {
                message.info(useI18n().t('MoodboardUpload.jsContent3'));
            }
            const isLt2M = file.size / 1024 / 1024 < 5;
            if (!isLt2M) {
                message.info(useI18n().t('MoodboardUpload.jsContent4'));
            }
            return (isJpgOrPng && isLt2M) || Upload.LIST_IGNORE;
        }
		const fileUploadChange = (value: any)=> {
            let file = value.file;
			let bor = true
            if (file.status === "done") {
                let res = JSON.parse(file.xhr.response);
				if(res.errCode == 0){
					file.imgUrl = res.data.url;
					file.id = res.data.id
					file.isChecked = true
					file.type = 'ProductElement'
					// if(props.productimgMenu.value == 'Relight'){
					// 	file.type = "ToProductImage"
					// }
					data.selectImg = res.data
					data.fileList.filter((v: any) => v.status === "done");
				}else{
					bor = false
				}
				// this.showFileList = productImgData.fileList
            } else if (file.status === "error") {
				bor = false
            }
        }
		const likeSetBtn = (id:any,str:string)=>{
			data.likeList.forEach((item:any,index:any)=>{
				if(item.id == id){
					if(str == 'zoom'){
						showViewVideo({url:item.videoUrl})
					}else if(str == 'like'){
						likeFile(item,'noLike',index)
					}
				}
			})
			
		}
		const noLikeSetBtn = (id:any,str:string)=>{
			data.noLikeList.forEach((item:any,index:any)=>{
				if(item.id == id){
					if(str == 'zoom'){
						showViewVideo({url:item.videoUrl})
					}else if(str == 'like'){
						likeFile(item,'like',index)
					}
				}
			})
		}
		let likeFile = (item:any,str:any,index:any) =>{
			let url
			let value = {
			}
			if(str == 'like'){
				value = {
					likeOrDislike:'like',
					transformedId:item.id,
				}
			}else{
				value = {
					likeOrDislike:'dislike',
					transformedId:item.id,
				}
			}
			Https.axiosPost(Https.httpUrls.poselikeOrDisike, {},{params:value}).then(
				(rv) => {
					if(str == 'like'){
						let value = {
							list:[item],
							str:'add',
							index:-1,
						}
						store.commit("setPoseTransfer", value);
						data.noLikeList.splice(index,1)
					}else{
						let value = {
							list:[item],
							str:'splice',
							index:index,
						}
						data.noLikeList.push(item)
						store.commit("setPoseTransfer", value);
						
					}
				}
			).catch(res=>{
			});
		}
		onMounted(()=>{

		})
		return{
			...toRefs(dataDom),
			...toRefs(data),
			openSetData,
			selectImgItem,
			setSize,
			setItemPosition,
			getgenerate,
			getUploadUrl,
			beforeUpload,
			fileUploadChange,
			removeGenerate,
			likeSetBtn,
			noLikeSetBtn,
		}
	},
	provide() {
		return {
		}
	},
})
</script>
<style lang="less" scoped>
	.poseTransfer{
		width: 100%;
		height: 100%;
		position: relative;
		font-size: 2rem;
		font-weight: 900;
		display: flex;
		> .configuratioBox{
			display: flex;
			flex-direction: column;
			align-items: center;
			&.active{
				width: 0;
				overflow: hidden;
			}
			> .generate{
				margin-top: auto;
			}
		}
		> .configuratioBox > .configuratio{
			padding-right: 3.8rem;
			width: 31.8rem;
			> .title{
				// font-size: 2.6rem;
			}
			> .content{
				margin-top: 4rem;
				> .selectImg,> .poses{
					display: flex;
					flex-direction: column;
					> .imgBox{
						flex: 1;
						max-height: 45rem;
						margin-top: 2rem;
						display: flex;
						flex-wrap: wrap;
						justify-content: space-between;
						width: 100%;
						overflow: hidden;
						overflow-y: auto;
						> .item{
							width: calc(100% / 2 - .5rem);
							margin-bottom: 1rem;
							cursor: pointer;
							border-radius: 2rem;
							border: 2px solid #8e8e8e;
							overflow: hidden;
							display: flex;
							justify-content: center;
							flex-shrink: 0;
							height: 25rem;
							&.active{
								border: 2px solid;
							}
							> img{
								width: 100%;
								object-fit: contain;
							}
						}
						> .upload_item{
							border: none;
						}
					}
					> .head{
						color: #000;
						font-weight: 600;
						> .text{
							display: inline-block;
						}
					}
				}
				> .selectImg{
					> .head{
						> .text{
							position: relative;
							&::before {
								position: absolute;
								content: "";
								display: block;
								background: #000;
								height: calc(.4rem*1.2);
								left: 50%;
								transform: translateX(-50%);
								bottom: -.5rem;
								width: 0px;
								width: 100%;
								transition: 0.3s all;
							}
						}
					}
				}
				> .poses{
					margin-top: 3rem;
				}
			}
		}
		> .likeBox ,> .noLikeBox{

			margin-top: 1.8rem;
			flex: 1;
			position: relative;
			> .element{
				width: 100%;
				height: 100%;
				display: flex;
				flex-direction: column;
				> .btnLeft,> .btnRight{
					position: absolute;
					width: 4rem;
					height: 7rem;
					background: #fff;
					border: 2px solid;
					border-right: none;
					border-radius: 2rem 0 0 2rem;
					top: 50%;
					transform: translate(-100%,-50%);
					left: 0;
					display: flex;
					align-items: center;
					justify-content: center;
					z-index: 2;
					cursor: pointer;
					>span{
						transition: all .3s;
						transform: rotate(90deg);
						&.active{
							transform: rotate(270deg);
						}
					}
				}
				> .btnRight{
					left: calc(100% + 4rem) ;
					transform: translate(-100%,-50%) rotate(180deg);
				}
				> .content{
					flex: 1;
					padding: 1.7rem 2rem;
					border-radius: 3rem;
					background: #f7f8fa;
				}
				> .title{
					margin-bottom: 2rem;
				}
			}
			
		}
		> .noLikeBox{
			padding-left: 2.3rem;
			&.active{
				flex: 0;
				overflow: hidden;
			}
		}
	}
</style>