<template>
   <a-modal class="modal_component Export" 
            v-model:visible="showUpgradePlan" 
            :footer="null" 
            width="78%"
            :maskClosable="false"
            :centered="true"
			:closable="false"
			:keyboard="false"
        >
        <div class="UpgradePlan_closeIcon">
			<i class="fi fi-rr-cross-small" @click.stop="cancelDsign()"></i>
		</div>
		<div class="UpgradePlan_content">
			<div>Export</div>
		</div>
		<!-- <div>
			<canvas ref="exportCanvas"></canvas>
		</div> -->
		<div class="exportCanvasBox">
			<div class="exportCanvasBox_left">
				<div class="exportCanvasBox_title">
					Canvas Title
				</div>
				<label>
					<div>Width:</div>
					<input type="number" @input="setMaxInput('width',600)" v-model="canvasWH.width">
				</label>
				<label>
					<div>Height:</div>
					<input type="number" @input="setMaxInput('height',1000)" v-model="canvasWH.height">
				</label>
			</div>
			<div class="exportCanvasBox_center">
				<!-- <canvas ref="canvasDom" id="exportCanvas"></canvas> -->
			</div>
			<!-- <ExportNewCoolection ref="ExportNewCoolection"></ExportNewCoolection> -->
			<div class="exportCanvasBox_right">
				<div class="" @click="setExport">export</div>
			</div>
		</div>
	</a-modal>
</template>
<script>
import { defineComponent, computed, h, ref, nextTick, inject,reactive, onMounted } from "vue";
import { Https } from "@/tool/https";
import scaleImage from "@/component/HomePage/scaleImage.vue";
import ExportNewCoolection from "@/component/HomePage/ExportNewCoolection.vue";
import { useStore } from "vuex";
import { forEach } from "jszip";
export default defineComponent({
	components: {
		scaleImage,	
		ExportNewCoolection,
	},
    props: ["msg",'sketchCatecoryList'],
    setup() {
        const store = useStore();

        let showUpgradePlan = ref(false)
		let canvas = reactive({})
		// let canvasDom = ref()
		let canvasWH = ref({
			width:400,
			height:1400,
		})

		let sketch = computed(()=>{
			return store.state.HomeStoreModule.showSketchList})
		// let sketch = ref([[],[],[]])
		let sketchList = computed(()=>{
			return store.state.UploadFilesModule.showSketchboard})
		let allBoardData = computed(()=>{return store.state.UploadFilesModule.allBoardData})
        let likeDesignCollectionList = computed(()=>{return store.state.HomeStoreModule.likeDesignCollectionList})
		let allImage = Object.assign(allBoardData.value,{likeDesignCollectionList:likeDesignCollectionList.value})
		let init = () =>{
			showUpgradePlan.value = true
			nextTick().then(async ()=>{
				let canvasBox = document.querySelector('.Export .exportCanvasBox_center')
				canvasBox.innerHTML = ''; // 清空原有内容
				var canvasDom = document.createElement('canvas')
				canvasBox.appendChild(canvasDom);
				canvas = new fabric.Canvas(canvasDom, {
					backgroundColor: "rgba(255, 255, 255)",
					// fill: '#ffde7d',
					// selection: false, //设置多选
					width: canvasWH.value.width,
					height: canvasWH.value.height,
					isDrawingMode: false, // 开启绘图模式
				});
				let disposeMoodboardShow = true
				let arr = ['disposeMoodboard','moodboardFiles','printboardFiles','colorBoards','sketchboardFiles','likeDesignCollectionList']
				let position = { //设置每个图形位置的初始值
					x:0,
					y:0,
					height:0,
				}
				let sketchGrouping = 3//sketch分组
				let likeDesign = 4//整体图分组
				let oldKey = ''
				let margin = 20//每个图形边距
				// arr.forEach((item,index)=>{
				for (const item of arr) {
					for (const key in allBoardData.value) {
						if(item == key){//循环渲染顺序
							let setImgWidth = canvasWH.value.width//这是设置画布等宽
							let sketchGroupingItem = []
							if(disposeMoodboardShow && item == 'disposeMoodboard' && allBoardData.value[key].length != 0 && allBoardData.value[key][0] != null){//如果是mood 需要判断用户是否点击layout
								disposeMoodboardShow = false
							}
							if(item == 'moodboardFiles' && !disposeMoodboardShow){
								continue
							}
							if(item == 'printboardFiles'){
								setImgWidth = canvasWH.value.width/8
							}
							if(item == 'sketchboardFiles'){
								setImgWidth = (canvasWH.value.width-(sketchGrouping-1)*20)/sketchGrouping
							}
							if(item == 'likeDesignCollectionList'){
								setImgWidth = (canvasWH.value.width-(likeDesign-1)*20)/likeDesign
							}
							for (const [allItemIndex, allItem] of allBoardData.value[key].entries()) {
								await new Promise((resolve,reject)=>{
									if(key == 'colorBoards'){
										position.x = 0
										position.y += position.height
										var text = new fabric.Text(allItem.tcx, {
											left: 0,
											top: 60,
											fontSize: 14,
											fontFamily: 'Arial',
											textAlign: "left",
											fill: 'black',
										});
										let text1 = new fabric.Text(allItem.name, {
											left:0,
											top: 80,
											width:20,
											fontSize: 14,
											fontFamily: 'Arial',
											textAlign: "left",
										});
										var color = new fabric.Rect({
											width: 130>text1.width?130:text1.width,
											height: 60,
											textAlign: "left",
											fill: `rgb(${allItem.r},${allItem.g},${allItem.b})`,
										});
										var group = new fabric.Group([color, text, text1], {
											left: position.x,
											top: position.y,
											width:130,
											fill:'rgb(255,255,255)',
											cornerSize: 10, // 选中时，角的大小为20
											transparentCorners: false, // 选中时，角是被填充了。true 空心；false 实心
											stroke: '#212121',
											strokeWidth: 1,
										});
										// 将矩形对象添加到 canvas 中
										canvas.add(group);
										position.height = group.height+margin
										resolve()
									}else{
										let itemCanvasImg = allItem.imgUrl
										if(key == 'likeDesignCollectionList'){
											itemCanvasImg = allItem.designOutfitUrl
										}
										fabric.Image.fromURL(itemCanvasImg, (img) => {
											let proportion = img.height/img.width//计算图形宽高比例
											let scaleWH = setImgWidth/img.width//计算放到画布上缩小倍率
											if((position.x+img.width*scaleWH > canvasWH.value.width) || (oldKey != key)){
												position.x = 0
												position.y += position.height
											}
											img.set({
												// width: setImgWidth/img.width,
												// height: canvasWH.value.height/img.height,
												left: position.x,
												top: position.y,
												scaleX: setImgWidth/img.width,
												scaleY: img.width*proportion*scaleWH/img.height,
												cornerSize: 10, // 选中时，角的大小为20
												// lockRotation:true,
												// lockScalingX:true,
												lockRotation:true,
												transparentCorners: false, // 选中时，角是被填充了。true 空心；false 实心
												// cornerColor: "#a1de93", // 选中时，角的颜色是 青色
											},{ crossOrigin: 'Anonymous' })
											position.height = img.height*scaleWH+margin
											if(key == 'sketchboardFiles'){
												position.x += img.width*scaleWH+margin
												if(sketchGroupingItem.length>=3){
												}else{
													sketchGroupingItem.push(JSON.parse(JSON.stringify(position)))
												}
												if(sketchGroupingItem.length>=3){
													let sketchXyIndex = {
														maxIndex:0,
														maxNum: 9999999999,
														minNum:0,
														minIndex:0,
													}
													sketchGroupingItem.forEach((sketchItem,sketchIndex)=>{
														if(sketchItem.height < sketchXyIndex.maxNum){
															sketchXyIndex.maxNum = sketchItem.height
															sketchXyIndex.maxIndex = sketchIndex
														}
														if(sketchItem.height > sketchXyIndex.minNum){
															sketchXyIndex.minNum = sketchItem.height
															sketchXyIndex.minIndex = sketchIndex
														}
													})
													if(allBoardData.value[key].length == allItemIndex+1){
														position = sketchGroupingItem[sketchXyIndex.minIndex]
													}else{
														position = sketchGroupingItem[sketchXyIndex.maxIndex]
														position.y += position.height
														position.x -= img.width*scaleWH+margin
													}
												}
												
											}else{
												position.x += img.width*scaleWH
											}
											img.lock_rotation = true
											canvas.add(img);
											oldKey = key
											resolve()
										})
									}
								});
							}
						}
					}
				}

			})
		}
		//设置导出
		let setExport = ()=>{
			var imageDataURL = canvas.toDataURL({
				format: 'png', // 导出格式为 PNG
				quality: 1 // 图片质量为 1（最高质量）
			});
			console.log(imageDataURL);
		}
		//关闭画布
		let cancelDsign = () =>{
			showUpgradePlan.value = false
		}
		//设置画布宽高
		let setMaxInput = (str,maxNum) =>{
			if(str == 'width' && canvasWH.value.width >= maxNum){
				canvasWH.value.width = maxNum
			}else if(str == 'height' && canvasWH.value.height >= maxNum){
				canvasWH.value.height = maxNum
			}
			canvas.setHeight(canvasWH.value.height);
			canvas.setWidth(canvasWH.value.width);
		}
	
		onMounted (()=>{
			
 			
		})

        return {
			showUpgradePlan,
			canvasWH,
			init,
			setExport,
			cancelDsign,
			setMaxInput,
        };
    },
    data(prop) {
        return {
		}
    },
	
    mounted() {
    },
	watch:{
		// driver__:{
		// 	handler(newVal,oldVal){
		// 		if(this.type_.type2 == 'Printboard'){
		// 			if(newVal.index >= 14 && newVal.index < 15){
		// 				this.setKeyword(newVal.index-14)
		// 			}else{
		// 			}
		// 		}else if(this.type_.type2 == 'Sketchboard'){
					
		// 		}
				
		// 	}
		// },
		
	},
    methods: {
        
		
		
    },
});
</script>
<style lang="less" scoped>
.Export {
	flex: 1;
    // height: 30rem;
    // overflow-x: hidden;
	display: flex;
    flex-direction: column;
    border-right: 1px solid #e5e5e5;
	position: relative;
	.UpgradePlan_content{
		font-size: var(--aida-fsize2);
		font-weight: 900;
		color: rgba(0, 0, 0, 0.65);
	}
    .UpgradePlan_closeIcon{
		top: calc(2rem*1.2);
		right: calc(2rem*1.2);
        cursor: pointer;
		width: calc(4rem*1.2);
		height: calc(4rem*1.2);
		display: flex;
		align-items: center;
		justify-content: center;
		position: absolute;
		.fi-rr-cross-small::before{
			padding: calc(.2rem*1.2);
			border-radius: 5px;
			border: solid 2px rgba(0, 0, 0, 0.25);
			transition: 1s all;
			color: rgba(0, 0, 0, 0.55);
		}
		&.UpgradePlan_closeIcon:hover .fi-rr-cross-small::before{
			border: solid 2px rgba(0, 0, 0, 0.55);
			color: rgba(0, 0, 0, 1);
		}
	}
	.exportCanvasBox{
		flex: 1;
		overflow-x: hidden;
		display: flex;
		margin-top: 2rem;
		.exportCanvasBox_title{
			margin-bottom: 1rem;
			font-size: 1.8rem;
			font-weight: 600;
		}
		.exportCanvasBox_left{
			label{
				cursor: pointer;
				display: flex;
				div{
					width: 5rem;
				}
				input{
					width: 10em;
				}
			}
		}
		.exportCanvasBox_center{
			height: 100%;
			overflow-x: hidden;
		}
		.export_new_collection_review{
			position: initial;
			margin: 10rem auto;
			margin-bottom: 0;
		}
	}
	
}
	

</style>
<style lang="less">
.Export{
	.ant-modal-content{
		border-radius: calc(1rem*1.2);
		overflow: hidden;
		.ant-modal-header{
			background-color: #fff;
			border-bottom: none;
		}
		.ant-modal-body{
			display: flex;
			flex-direction: column;
			padding: calc(5rem*1.2) calc(5rem*1.2) !important;
			// height: calc(65vh - 6.4rem);
			height: calc(65rem*1.2);
			background: #f9fafb;
		}
		//进度完成字体颜色
		.ant-progress-circle.ant-progress-status-success .ant-progress-text{
			color: #000;
		}
		.ant-progress-circle .ant-progress-text{
			color:rgba(0, 0, 0, 0.55);
			font-size: calc(1.6rem*1.2);
		}
	}
}
</style>