<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">Choose design to transfer</div>
						</div>
						<div class="imgBox" v-mousewheel>
							<div class="item" :class="{active:item.id == selectImg.id}" v-for="item in currentList" @click="selectImgItem(item)">
								<img :src="item.imgUrl || item.url" alt="">	
								<a-checkbox v-model:checked="item.isChecked"></a-checkbox>
							</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="">	
								<a-checkbox v-model:checked="item.isChecked"></a-checkbox>
							</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">Choose pose</div>
						</div>
						<div class="imgBox" v-mousewheel>
							<div class="item" v-for="item in poseList" @click="selectPose(item)">
								<img :src="item.firstFrame" 
									alt=""
									@mouseenter.stop="gifPlay($event,item)"
									@mouseleave.stop="gifPause($event,item)" 
								>	
								<a-checkbox v-model:checked="item.isChecked"></a-checkbox>
							</div>
						</div>
					</div>
				</div>	
			</div>
			<div class="generate input_border">
				<div class="generage_btn started_btn" v-show="!isGenerate" @click="getgenerate">
					{{ $t('Generate.Generate') }}
				</div>
				<div v-show="isGenerate && !remGenerate" class="generage_btn started_btn">
					<i class="fi fi-br-loading"></i>
				</div>
				<div v-show="remGenerate" @click="removeGenerate" class="generage_btn started_btn">
					{{$t('Generate.Close')}}
				</div>
			</div>
		</div>
		<div class="likeBox">
			<div class="element">
				<div class="title"><i class="fi fi-rs-comments"></i><span>Selected Video</span></div>
				<div class="content">
					<generalDrag ref="generalDragLeft" v-if="isState" :list="likeList" :isVideo="true" @setBtn="likeSetBtn"></generalDrag>
				</div>
				<!-- <div class="btnLeft" @click="setSize('left')" :class="{'active':button.left}">
					<span class="icon iconfont icon-xiala"></span>
				</div> -->
				<div class="btnRight" @click="setSize('right')" :class="{'active':button.right}">
					<span class="icon iconfont icon-xiala"></span>
				</div>
			</div>
		</div>
		<div class="noLikeBox" :class="{active:button.right}">
			<div class="element">
				<div class="title"><i class="fi fi-rs-comments"></i><span>Generated Video</span></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:[],
			isGenerate:false,//判断是否正在进行generate
			remGenerate:false,
			removeGenerate:false,
			generateTime:null as any,
			poseList:[],
			selectPose:null as any,
		})
		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.fileList.forEach((listItem:any)=>listItem.isChecked = false)
			data.currentList.forEach((listItem:any)=>listItem.isChecked = false)
			item.isChecked = true
			if(item.url || item.imgUrl)data.selectImg.minioUrl = getMinioUrl(item.url || item.imgUrl)
		}
		const openSetData = ()=>{
			// dataDom.generalDrag.openSetData()
			data.currentList = store.state.UploadFilesModule.modularData.toProduct
			setIsShowMark(false)
			if(data.poseList.length == 0){
				getPoseList()		
			}
		}
		const gifPlay = (e:any,item:any)=>{
			e.target.src = item.gif//使用gif图片
		}
		const gifPause = (e:any,item:any)=>{
			e.target.src = item.firstFrame//静态图片
		}
		const getPoseList = ()=>{
			Https.axiosGet(Https.httpUrls.getAllPose).then((rv)=>{
				rv[0].isChecked = true
				data.selectPose = rv[0]?.id || 1
				data.poseList = rv
			})	
		}
		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:data.selectPose,
				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:any = 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
									console.log(list)
									list = ''
									// if(list?.filter)list = list?.filter((item:any) => item !== element.taskId);
								}else if(element.status == 'Fail'){
									
								}
							});
							data.waitList = list
							if((!list)|| (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=>{
					data.noLikeList = data.noLikeList.filter((item:any)=>item.taskId != list)
					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
					data.fileList.forEach((listItem:any)=>listItem.isChecked = false)
					data.currentList.forEach((listItem:any)=>listItem.isChecked = false)
					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=>{
			});
		}
		const selectPose = (item:any)=>{
			item.isChecked = true
			data.selectPose = item?.id || 1
			data.poseList.forEach((listItem:any)=>listItem.isChecked = false)
		}
		onMounted(()=>{
			// showViewVideo({url:'https://www.minio.aida.com.hk:12025/api/v1/download-shared-object/aHR0cHM6Ly93d3cubWluaW8uYWlkYS5jb20uaGs6MTIwMjQvYWlkYS11c2Vycy84OS9wb3NlX3RyYW5zZm9ybV92aWRlby8xMjMtODkubXA0P1gtQW16LUFsZ29yaXRobT1BV1M0LUhNQUMtU0hBMjU2JlgtQW16LUNyZWRlbnRpYWw9N0tOVDdNWlNLWkRXM1RVOEJZVlklMkYyMDI1MDQwOCUyRnVzLWVhc3QtMSUyRnMzJTJGYXdzNF9yZXF1ZXN0JlgtQW16LURhdGU9MjAyNTA0MDhUMDUxOTM1WiZYLUFtei1FeHBpcmVzPTQzMTk5JlgtQW16LVNlY3VyaXR5LVRva2VuPWV5SmhiR2NpT2lKSVV6VXhNaUlzSW5SNWNDSTZJa3BYVkNKOS5leUpoWTJObGMzTkxaWGtpT2lJM1MwNVVOMDFhVTB0YVJGY3pWRlU0UWxsV1dTSXNJbVY0Y0NJNk1UYzBOREV4T0RneE9Td2ljR0Z5Wlc1MElqb2lZV1J0YVc0aWZRLmY0Z3RoTU1BeC1GUnM3eGhWNFdjTUFCUW5lU19BVkIxUDlYbnJQbEFNWUFsVnJwY3RpYXgtU2cyY2FkZHZ0a0VCOU1NbWxGeUlIbU90aGhUWDlqN2lnJlgtQW16LVNpZ25lZEhlYWRlcnM9aG9zdCZ2ZXJzaW9uSWQ9bnVsbCZYLUFtei1TaWduYXR1cmU9Yjg5YmQ4ZDg5M2I4ZjBjYmYxZDI3NDFjZmY0NGRiZGNmYWM2NmU0ZGM2OGIwYzQzZDA2OGI4YjYzZjE5YjhhOA'})
		})
		return{
			...toRefs(dataDom),
			...toRefs(data),
			openSetData,
			selectImgItem,
			setSize,
			setItemPosition,
			gifPlay,
			gifPause,
			getgenerate,
			getUploadUrl,
			beforeUpload,
			fileUploadChange,
			removeGenerate,
			likeSetBtn,
			noLikeSetBtn,
			selectPose,
		}
	},
	directives:{
		mousewheel:{
			mounted (el) {
				el.addEventListener('wheel',(e:WheelEvent)=>{
					let num = 0
					if(e.deltaY > 0){
						num = 25
					}else{
						num = -25
					}
					el.scrollBy(num, 0);
				},{ passive: true })
			}
		},
	},
	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;
			padding-right: 3.8rem;
			&.active{
				width: 0;
				overflow: hidden;
			}
			> .generate{
				margin-left: auto;
				> .started_btn{
					font-weight: 300;
				}
			}
		}
		> .configuratioBox > .configuratio{
			width: 31.8rem;
			padding-bottom: 1rem;
			> .title{
				// font-size: 2.6rem;
			}
			> .content{
				// margin-top: 4rem;
				margin-top: 1.8rem;
				> .selectImg,> .poses{
					display: flex;
					flex-direction: column;
					> .imgBox{
						flex: 1;
						max-height: 45rem;
						margin-top: 2rem;
						display: flex;
						flex-direction: row;
						flex-wrap: nowrap;
						justify-content: space-between;
						width: 100%;
						overflow: hidden;
						overflow-x: auto;
						> .item{
							margin-right: 1rem;
							width: calc(100% / 2 - .5rem);
							cursor: pointer;
							overflow: hidden;
							display: flex;
							justify-content: center;
							flex-shrink: 0;
							height: 25rem;
							position: relative;
							// &.active{
							// 	border: 2px solid;
							// }
							:deep(.ant-checkbox-wrapper){
								position: absolute;
								top: 2rem;
								right: 2rem;
							}
							> img{
								width: 100%;
								object-fit: contain;
							}
						}
						> .upload_item{
							border: none;
						}
					}
					> .head{
						color: #000;
						font-weight: 600;
						> .text{
							display: inline-block;
							font-size: 1.6rem;
						}
					}
				}
			
				> .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{
						>span{
							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;
					font-size: 1.6rem;
					font-weight: 900;
					> span{
						margin-left: 1rem;
					}
				}
			}
			
		}
		> .noLikeBox{
			padding-left: 2.3rem;
			&.active{
				flex: 0;
				overflow: hidden;
			}
		}
	}
</style>