<template>
   <div class="modelNavBox" ref="modelNavBox" :class="{'modelNavBox_active':designDetail.clothes.length == 5}">
	<div class="modelNav" ref="modelNav" :style="{height:prentHeight}">
		<div class="modelNav_item item" 
			v-for="item,index in designDetail.clothes" 
			:class="{active:(selectDetail && item.id == selectDetail.id)}" 
			@mousedown.stop="designMousedown(getMousePosition($event,false),item.uniqueId,'disLike')" 
			@touchstart.passive="designMousedown(getMousePosition($event,true),item.uniqueId,'disLike')"
			@click="selectDetailItem(item,index)">
			<div class="iconList">
				<i class="fi fi-rr-add" :class="{ active:item.scope == 'sys'}" @click.stop="sketchSystemToLibrary(item)"></i>
				<i class="fi fi-rr-trash" @click.stop="deleteDetailItem(item?.id)"></i>
			</div>
			<img :src="item.path" alt="">
			<div class="type">{{ getTypeLang(item.type) }}</div>
		</div>
    </div>
	<div v-show="singleOveral.value == 'overall'" v-if="(currentDetailType == 'sketch' || currentDetailType == '') && designDetail.clothes.length < 5 && !isEditPattern.value" :class="{active:!selectDetail?.id && currentDetailType == 'sketch'}" class="add" @click="addSketch">
		<i class="fi fi-bs-plus"></i>
	</div>
   </div>
</template>
<script lang="ts">
import { defineComponent,computed,createVNode,inject,watch,onBeforeUnmount,toRefs, reactive} from 'vue'
// import setDesignItem from '@/component/Detail/setDesignItem2.vue'
import { ExclamationCircleOutlined, } from '@ant-design/icons-vue';
import { Https } from "@/tool/https";
import { Modal,message } from 'ant-design-vue';
import { useStore } from "vuex";
import { useI18n } from 'vue-i18n'
import position from './modelPosition.vue';
import { getMousePosition } from "@/tool/mdEvent"
export default defineComponent({
    components:{
		position,
    },
	emits:['addSketch','deleteItem','sketchSysToLibrary'],
	props:{
	},
    setup(props,{emit}) {
        const store = useStore();
		const {t} = useI18n()
		const detailData = reactive({
			selectDetail:computed(()=>store.state.DesignDetail.selectDetail),
			frontBack_:computed(()=>store.state.DesignDetail.frontBack),
			designDetail:computed(()=>store.state.DesignDetail.designDetail),
			currentDetailType:computed(()=>store.state.DesignDetail.currentDetailType),
			isEditPattern:inject('isEditPattern') as any,
			singleOveral:inject('singleOveral') as any,
			getCanvasIfEdit:inject('getCanvasIfEdit')as any,
			modelNav:null as any,
			modelNavBox:null as any,
		})
		const collItemSize = reactive({
			collValue:18,
			num:1,
			prentHeight:0 as any,
			padding:10,
			likeStyle:{
				
			},
			itemStyle:{
				width:0,
				height:0,
			},
			collTime:null as any,
			isMove:false,
			elList:[] as any,
			selectIndex:0,
		})
		watch(()=>detailData.designDetail.clothes.length,(newVal)=>{
			nextTick(()=>{
				setItemPosition()
			})
		},{immediate:true})
		const selectDetailItem = (item:any,index:number)=>{
			new Promise((resolve, reject) => {
				if(detailData.isEditPattern.value && 
					detailData.selectDetail?.id && 
					detailData?.getCanvasIfEdit?.fun&&detailData?.getCanvasIfEdit?.fun() > 0
				){
					resolve()
					// Modal.confirm({
					// 	title: t('collectionModal.jsContent6'),
					// 	icon: createVNode(ExclamationCircleOutlined),
					// 	okText: 'Yes',
					// 	cancelText: 'No',
					// 	mask:false,
					// 	centered:true,
					// 	onOk() {
					// 		resolve(true)
					// 		emit('canvasReload')
					// 	},
					// 	onCancel(){
					// 		resolve(false)
					// 	}
					// });
				}else{
					resolve(true)
					if(detailData.selectDetail.id !== item.id){
					}
				}
			}).then((rv)=>{
				if(rv)store.commit('DesignDetail/setDesignColthes',item.id)
			})
		}
		const deleteDetailItem = (id:number)=>{
			detailData.designDetail.clothes = detailData.designDetail.clothes.filter((item:any)=>item.id != id)
			detailData.frontBack_.back = detailData.frontBack_.back.filter((item:any)=>item.id != id)
			detailData.frontBack_.front = detailData.frontBack_.front.filter((item:any)=>item.id != id)
			//判断删除后是否还有服装
			if(detailData.designDetail.clothes.length == 0){
				addSketch()
			}else{
				//获取当前最大的priority值
				const maxValue = Math.max(...detailData.designDetail.clothes.map(item => item.priority));
				const maxObj = detailData.designDetail.clothes.find(item => item.priority === maxValue);
				store.commit('DesignDetail/setDesignColthes',maxObj.id)
			}
			emit('deleteItem')
		}
		const addSketch = ()=>{
			if(detailData.currentDetailType != 'sketch')store.commit('DesignDetail/setCurrentDetailType','sketch')
			store.commit('DesignDetail/addDesignColthes')
			emit('addSketch')
		}



		const designMousedown = (e:any,uniqueId:number,str:string)=>{
			let item:any  = collItemSize.elList.filter((item:any)=>item.uniqueId == uniqueId)[0]
			if(!item)return
			item.el.style.zIndex = 2;
			item.el.style.transition = 'all 0s';
			let startX = e.clientX,
			startY = e.clientY,
			top = item.el.offsetTop;
			collItemSize.isMove = false
			let moveFun = (e:any) => {
				collItemSize.isMove = true
				let X = 0;
				let Y = e.clientY - startY + top;
				item.el.style.left = `${X}px`;
				item.el.style.top = `${Y}px`;
				reRange(item, X, Y,str);
			};
			let mouseUpFun = ()=>{
				document.removeEventListener('mousemove',mouseMove)
				document.removeEventListener('touchmove',touchmove)

				document.removeEventListener('mouseup',mouseUpFun) 
				document.removeEventListener('touchend',mouseUpFun) 
				item.el.style.zIndex = 1;
				item.el.style.transition = 'top .5s';
				moveItem();
				sortDesignCollection()
			}
			let mouseMove = function(event:any){
				let e = getMousePosition(event,false)
				moveFun(e)
			}
			let touchmove = function(event:any){
				let e = getMousePosition(event,true)
				moveFun(e)
			}

			document.addEventListener('mousemove',mouseMove)
			document.addEventListener('touchmove',touchmove)

			document.addEventListener('mouseup',mouseUpFun) 
			document.addEventListener('touchend',mouseUpFun) 
		}
		//排序  从大到小
		const sortDesignCollection = ()=> {
		
		}
		const reRange = (item:any, x:number, y:number,str:string)=>{
			let elList:any = collItemSize.elList
			let index = collItemSize.selectIndex
			let width,height,num
			num = collItemSize.num
			width = collItemSize.itemStyle.width
			height = collItemSize.itemStyle.height
			
			let moveIndex = Math.round(x / (width + 10)) + Math.round(y / (height + 10)) * num;
			moveIndex = elList.length - 1 - moveIndex
			moveIndex = moveIndex < 0 ? 0 : moveIndex;
			moveIndex = moveIndex > elList.length - 1 ? elList.length - 1 : moveIndex;
			if(moveIndex != index){
				collItemSize.selectIndex = moveIndex;
				let currentSort = item.sort;
				for(let i = 0;i < elList.length;i++){
					if(currentSort < moveIndex){
						if(elList[i].sort > currentSort && elList[i].sort <= moveIndex){
							elList[i].sort -= 1;
						};
					}else if(currentSort > moveIndex){
						if(elList[i].sort < currentSort && elList[i].sort >= moveIndex){
							elList[i].sort += 1;
						};
					}
				};
				elList[item.index].sort = moveIndex;
				moveItem();
			}
		}
		const moveItem = ()=>{
			let value = collItemSize.num
			for(let i = 0;i < collItemSize.elList.length;i++){
				let height = parseInt(String((collItemSize.elList.length - 1 - collItemSize.elList[i].sort) / value)) * (collItemSize.itemStyle.height +collItemSize.padding) + 'px';
				collItemSize.elList[i].el.style.top = height
			}
			setZIndex()
		}
		const setZIndex = ()=>{
			collItemSize.elList.forEach((elItem:any)=>{
				let clothesIndex = detailData.designDetail.clothes.findIndex((item:any)=>item.uniqueId == elItem.uniqueId)
				let clothesId = detailData.designDetail.clothes[clothesIndex].id
				detailData.designDetail.clothes[clothesIndex].priority = elItem.sort
				let frontIndex = detailData.frontBack_.front.findIndex((item:any)=>item.id == clothesId)
				detailData.frontBack_.front[frontIndex].style.zIndex = elItem.sort + 10
				// detailData.frontBack_.back[frontIndex].style.zIndex = elItem.sort + 1
			})
		}
		const setItemPosition = ()=>{
			let parent = detailData.modelNav.offsetWidth
			let elArr = detailData.modelNav.querySelectorAll('.item')
			let value = collItemSize.num
			const htmlFontSize = parseFloat(getComputedStyle(document.documentElement).fontSize);
			const remValue = 12 * htmlFontSize;
			//子元素宽度 = (父容器总宽度 - (列数-1)*间隙) / 列数
			collItemSize.itemStyle.height = remValue
			collItemSize.elList = []
			let arr:any = detailData.designDetail.clothes
			arr.forEach((item,index) => {item.uniqueId  = `${Date.now()}_${index}`});

			const sortedArray = [...arr].sort((a, b) => a.priority - b.priority);
			const sortMap = {} as any;
			sortedArray.forEach((item, index) => {
				sortMap[item.priority] = index ; // 1, 2, 3, 4...
			});
			for(let i = 0;i < elArr.length;i++){
				collItemSize.elList.push({
					el: elArr[i], 
					// sort: elArr.length - i -1, 
					sort: sortMap[arr[i].priority],
					index: i,
					uniqueId:arr[i]?.uniqueId || 99999,
				});
			}
			collItemSize.prentHeight = (collItemSize.padding + remValue) * elArr.length + 'px'
			moveItem()
		} 
		const sketchSystemToLibrary = (item)=>{
			let value = {
				clothId:item.id,
				path:item.minIOPath
			}
			Https.axiosGet(Https.httpUrls.addSysSketchToLibrary,{params:value})
			.then((rv:any)=>{
				item.scope = 'user'
				emit('sketchSysToLibrary')
			})
		}
		const getTypeLang = (type:any)=>{
			// return navTypeList.find((item:any)=>item.value == type)?.label || type
			let allPostition = store.state.Workspace.workspaceAllPosition
			return allPostition.find(item => item.value === type)?.name
		}
	
		onBeforeUnmount(()=>{
		})
        return{
			...toRefs(detailData),
			...toRefs(collItemSize),
			selectDetailItem,
			deleteDetailItem,
			designMousedown,
			addSketch,
			getMousePosition,
			sketchSystemToLibrary,
			getTypeLang,
        }
    },

	provide() {
		return {
		}
	},
		
})
</script>
<style lang="less" scoped>
	.modelNavBox{
		&.modelNavBox_active{
			margin-top: 12rem;
		}
		.modelNav_item{
			width: 12rem;
			height: 12rem;
			padding: 1rem;
			border-radius: 2rem;
			border: 2px solid #B4B4B4;
			margin-bottom: 1.5rem;
			cursor: pointer;
			position: absolute;
			background: #fff;
			transition: top .3s;
			overflow: hidden;
			> .type{
				position: absolute;
				bottom: 0rem;
				left: 0rem;
				font-size: 1.2rem;
				width: 100%;
				text-align: center;
				line-height: 2.4rem;
				font-size: 1.4rem;
				color: #fff;
				background: #666666CC;
			}
			> .iconList{
				position: absolute;
				top: 1rem;
				right: 1rem;
				display: none;
				flex-direction: column;
				align-items: center;
				> i{
					margin-bottom: .2rem;
					font-size: 1.8rem;
				}
				> .fi-rr-add{
					pointer-events: none;
					color: #acacac;
					&.active{
						pointer-events: auto;
						color: #000;
					}
				}
				>i:not(.fi-rr-add){
					font-size: 2rem;
				}
			}
			i:not(.fi-bs-plus){
			}
			
			&:hover{
				> .iconList{
					display: flex;
				}
			}
			&:last-child{
			    margin-bottom: 0;
			}
			&.active{
				border: 3px solid #000;
			}
			> img{
				width: 100%;
				height: 100%;
				object-fit: contain;
			}
		}
		.add{
			width: 12rem;
			height: 12rem;
			text-align: center;
			line-height: 12rem;
			padding: 1rem;
			border-radius: 2rem;
			border: 2px solid #B4B4B4;
			font-size: 8rem;
			border-radius: 2rem;
			border: 2px solid #B4B4B4;
			cursor: pointer;
			display: flex;
			align-items: center;
			justify-content: center;
			i{
				font-size: 4rem;
				display: flex;
			}
		}
	}
    .modelNav{
		position: relative;
		width: 12rem;
	}
</style>