<template>
	<div class="deReconstruction">
		<div class="selectSektch itemBox">
			<!-- <div class="type">
				<a-select
					v-model:value="segmentationType"
					show-search
					:allowClear="false"
					style="width: 100%"
					placeholder="Please select"
					:options="[{value:'product',label:'product'},{value:'sketch',label:'sketch'}]"
				></a-select>
			</div> -->
			<selectList @selectImgItem="selectImgItem" :deReconstructionList="segmentationTypeList" :isSegmentation="true" upLoadHttpsUrl="/api/element/imageSegmentation" level1Type="Sketchboard" :randomId="false" type="sketch" :catecoryList="sketchCatecoryList">
				<template v-slot:selectSex>
					<div class="generalModel_state" style="margin-left: auto">
						<div class="generalModel_state_item smail" style="margin-right: 0">
							<a-select
								ref="select"
								v-model:value="sexId"
								:options="sexList"
								size="large"
								:fieldNames="{ label: 'name', value: 'id' }"
								style="width:13rem"
								@change="sexChange"
							>
								<template #suffixIcon
									><span
										class="icon iconfont icon-xiala"
										style="color: #000"
									></span
								></template>
							</a-select>
						</div>
					</div>
				</template>
			</selectList>
		</div>
		<div class="canvas itemBox">
			<canvasBox @setGenerateImg="setGenerateImg" :selectSexAge="selectSexAge" @setCanvasJSON="setCanvasJSON" ref="canvasBox"></canvasBox>
			<!-- <canvasUpload :config="ceditorConfig" clothingImageUrl="https://www.minio-api.aida.com.hk/aida-sys-image/models/female/2e4815b9-1191-419d-94ed-5771239ca4a5.png?response-content-type=image%2Fpng&response-content-disposition=inline&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=admin%2F20250608%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20250608T161025Z&X-Amz-Expires=86400&X-Amz-SignedHeaders=host&X-Amz-Signature=a4374c0954d11c2490ef3b86a1924cf6d423ed8ac56023b3c3ccabcdf0672620"></canvasUpload> -->
		</div>
		<div class="finished itemBox">
			<div class="btnTop">
				<div class="gallery_btn" @click="getCanvasImg">{{ $t('DeReconstruction.GenerateLineDrawing') }}</div>
				<div v-show="!generateImg?.[0]?.isLike && generateImg" class="icon iconfont icon-jushoucang icon_like" @click="generateLike('like')"></div>
				<div v-show="generateImg?.[0]?.isLike" class="icon iconfont icon-jushoucanggift" @click="generateLike('noLike')"></div>
			</div>
			<div class="content">
				<img v-if="generateImg?.[0]?.url" :src="generateImg?.[0]?.url" alt="">
				<sketchCategory v-if="generateImg?.[0]?.url" v-model:disignTypeList="sketchCatecoryList" :item="generateImg[0]" :isSetSketchCategory="true" :isSpread="false"></sketchCategory>
			</div>
			<div class="btnBottom" @click="getCanvasData">
				<div class="gallery_btn">{{ $t('DeReconstruction.Download') }}</div>
			</div>
		</div>
	</div>
</template>
<script lang="ts">
import { defineComponent,computed,ref,provide,nextTick,createVNode,toRefs, reactive, inject} from 'vue'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { Https } from "@/tool/https";
import { useStore } from "vuex";
import { downloadIamge,getMinioUrl } from "@/tool/util";
import { useI18n } from 'vue-i18n'
import selectList from '@/component/Detail/detailLeft/module/selectList.vue'
import sketchCategory from "@/component/HomePage/sketchCategory.vue";
import canvasBox from "./canvas/index.vue";
import canvasUpload from "@/component/Canvas/CanvasEditor/index.vue";
// import defaultModel from '@/assets/images/homePage/defaultModel.png'
export default defineComponent({
	components:{
		selectList,sketchCategory,canvasBox,canvasUpload
	},
	props:{
	},
	emits:[],
	setup(props,{emit}) {
		const store = useStore();
		const {t} = useI18n()
		const data = reactive({
			sketchCatecoryList:[],
			segmentationType:'product',
			segmentationTypeList:[{value:'product',name:'product'},{value:'sketch',name:'sketch'}],
			generateImg:computed(()=>store.state.HomeStoreModule.deReconstruction) as any,
			selectObject:computed(()=>store.state.Workspace.probjects),//选择的项目
			sexList:[
				
			],
			// sexList:computed(()=>store.state.UserHabit.sex.value),
			femalePosition:computed(()=>store.state.UserHabit.FemalePosition),//男性衣服位置
			malePosition:computed(()=>store.state.UserHabit.MalePosition),//女性衣服位置
			sex:'Male',
			sexId:1,
			ceditorConfig:{
				width: 800,
				height: 600,
				backgroundColor: "#f8f8f8",
			},
			defaultModel:'',
			selectSexAge:{},
		})
		const createProbject:any = inject('createProbject',()=>{}) as any
		const setIsShowMark:any = inject('setIsShowMark')
		const dataDom = reactive({
			canvasBox:null as any,
		})
		const selectImgItem = async (value:any)=>{
			// getSegmentation(data)
			if(!data.selectObject?.id)await createProbject()
			getSegmentation(value)

		}
		const canvasAddImg = (list:any)=>{
			console.log(list)
			list.segmentedImages.forEach((url:any) => {
				list.imgUrl = url
				dataDom.canvasBox.addImage({url})
			});
		}
		const getSegmentation = (value:any)=>{
			console.log(value)
			let segmentationType = ''
			if(value.designType == "Library"){
				segmentationType = 'sketch'
			}else{
				segmentationType = value.categoryValue
			}
			let param = new FormData(); 
			param.append('id',value.id)
			param.append('file','')
			param.append('type',segmentationType)
			let sourceType = value.designType || 'Upload'
			param.append('sourceType',sourceType)
			let config:any = {headers:{'Content-Type':'multipart/form-data','Accept':'*/*'  }}
			Https.axiosPost(Https.httpUrls.imageSegmentation,param,config)
			.then((rv:any) => {
					// console.log(rv);
					canvasAddImg(rv[0])
				}
			).catch(rv=>{
			})
		}
		const openSetData = ()=>{
			dataDom.canvasBox.openSetData()
		}
		const getCanvasImg = ()=>{
			dataDom.canvasBox.getData()
		}
		const setGenerateImg = (base64:any)=>{
			let value = {
				"collagePicture": base64,
				"gender": store.state.Workspace.probjects.sex,
				"projectId": store.state.Workspace.probjects.id
			}
			setIsShowMark(true)
			Https.axiosPost(Https.httpUrls.genSketchRecon,value).then((rv)=>{
				if(rv){
					data.sketchCatecoryList.forEach((item:any)=>{
						if(item.value == rv.category){
							rv.categoryValue = item.value
							rv.category = item.name
						}
					})
					rv.isLike = false
					let value = {
						list: [rv],
						str:'add',
						index:-1,
					}
					store.commit('setDeReconstruction',value)
					setIsShowMark(false)
				}
			})
			
		}
		const generateLike = (str:string)=>{
			if(data.generateImg[0].id == -1)return
			if(str == 'like'){
				let value={
					"gender": store.state.Workspace.probjects.sex,
					"generateDetailId": data.generateImg[0].id,
					"level1Type": "Sketchboard",
					"level2Type": data.generateImg[0].categoryValue,
					timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone
				}
				Https.axiosPost(Https.httpUrls.generateLike,value).then((rv)=>{
					if(rv){
						data.generateImg[0].isLike = true
					}
				})
			}else{
				let value = {
					"generateDetailId": data.generateImg[0].id,
					timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone
				}
				Https.axiosGet(Https.httpUrls.generateDislike, {params:value}).then(
					(rv) => {
						data.generateImg[0].isLike = false
					}
				).catch(res=>{
				});
			}
		}
		const setCanvasJSON = (canvasJSON)=>{
			if(!canvasJSON)return
			if(!store.state.Workspace.probjects?.id)return
			let canvasData = JSON.parse(canvasJSON)
			function deepProcessObjects(data:any, callback:any) {
				if (!Array.isArray(data)) return data;
				return data.map(item => {
					callback(item)
					const processedItem = {...item};
					if (processedItem.objects && 
						Array.isArray(processedItem.objects) && 
						processedItem.objects.length > 0) {
					processedItem.objects = deepProcessObjects(processedItem.objects, callback);
					}
					return processedItem;
				});
			}
			canvasData = deepProcessObjects(canvasData.canvas.objects,(item:any)=>{
				if(item.type == 'image')item.minioUrl = getMinioUrl(item.src)
			})
			let blob = new Blob([JSON.stringify(canvasData)], { type: "application/json" });
			let formData = new FormData();
			formData.append("file", blob, "data.json");
			formData.append("module", "deReconstruction");
			formData.append("projectId", store.state.Workspace.probjects.id)
			let config = {
				headers: { "Content-Type": "multipart/form-data", Accept: "*/*" },
			};
			Https.axiosPost(Https.httpUrls.exportSave, formData, config).then(
				(rv) => {
				}
			);
		}
		const setCanvas = (str:string)=>{
			dataDom.canvasBox.setCanvas(str)
		}
		const getCanvasData = ()=>{
			downloadIamge(data.generateImg[0].url,'downloadIamge')
		}
		const sexChange = ()=>{
			data.selectSexAge = data.sexList.filter((item)=>item.id == data.sexId)[0]
			store.commit('setProbject',{sex:data.selectSexAge.value})
			if(data.selectSexAge.value == 'Male'){
				data.sketchCatecoryList = data.malePosition
			}else{
				data.sketchCatecoryList = data.femalePosition
			}
			if(dataDom.canvasBox?.canvasLoad)dataDom.canvasBox.changeFixedImage()
		}
		onMounted(()=>{
			let sexList = store.state.UserHabit.sex.value
			let id = 0
			data.sexList = []
			sexList.forEach((item:any,index) => {
				let obj = {
					age:'Adult',
					name:item.name,
					value:item.value,
					id:index + 1,
				} as any
				id = index+1;
				data.sexList.push(obj)
			});
			data.sexList.push({age:'Child',name:t('DeReconstruction.Girls'),value:'Female',id:id+=1})
			data.sexList.push({age:'Child',name:t('DeReconstruction.Boys'),value:'Male',id:id+=1})
			data.sex = data.sexList[0].value
			data.selectSexAge = data.sexList[0]
			data.sexId = 1
			sexChange()
		})
		return{
			...toRefs(dataDom),
			...toRefs(data),
			selectImgItem,
			openSetData,
			getCanvasImg,
			setGenerateImg,
			generateLike,
			getCanvasData,
			setCanvas,
			setCanvasJSON,
			sexChange,
		}
	},
	provide() {
		return {
		}
	},
})
</script>
<style lang="less" scoped>
	.deReconstruction{
		width: 100%;
		height: 100%;
		position: relative;
		display: flex;
		> .itemBox{
			margin-right: 2rem;
			padding: 2rem;
			background: #f7f8fa;
			border-radius: 3rem;
			// flex: 1;
			&.selectSektch{
				width: 37rem;
				display:flex;
				flex-direction: column;
				flex-shrink: 0;
				> .type{
					display: flex;
					justify-content: space-between;
					> :deep(.ant-select){
						margin: 1rem 0;
						.ant-select-selector{
							border-radius: 2rem;
						}
					}
					>label{
						display: flex;
						align-items: center;
						>div{
							font-size: 2rem;
							margin-left: 1rem;
						}
					}
				}
			}
			&.canvas{
				flex: 1;
				position: relative;
			}
			&.finished{
				width: 45rem;
				// width: 58rem;
				display: flex;
				height: 100%;
				overflow: hidden;
				flex-direction: column;
				> .btnTop{
					display: flex;
					justify-content: space-between;
					> .icon{
						cursor: pointer;
						display: flex;
						justify-content: center;
						align-items: center;
						font-size: 2rem;
						width: 6rem;
						height: 6rem;
						border: 1px solid;
						border-radius: 50%;
					}
				}
				> .content{
					flex: 1;
					// overflow: hidden;
					margin: 2rem 0;
					position: relative;
					overflow: hidden;
					> img{
						width: 100%;
						height: 100%;
						object-fit: contain;
					}
				}
				> .btnBottom{
					text-align: right;
				}
			}
		}
		> .itemBox:last-child{
			margin-right: 0;
		}
	}
</style>