<template>
	<div ref="publishModal"></div>
		<a-modal
            class="publish_modal generalModel"
            v-model:visible="publish"
            :footer="null"
			:get-container="() => $refs.publishModal"
            width="50%"
            :maskClosable="false"
            :centered="true"
            :closable="false"
            :mask="publishMask"
			:keyboard="false"
        >
		<div class="generalModel_btn">
			<div class="generalModel_closeIcon" @click.stop="cancelDsign()">
				<svg width="46" height="46" viewBox="0 0 46 46" fill="none" xmlns="http://www.w3.org/2000/svg">
						<circle cx="23" cy="23" r="23" fill="white" fill-opacity="0.3"/>
						<rect x="32.5063" y="12" width="3" height="29" rx="1.5" transform="rotate(45 32.5063 12)" fill="white"/>
						<rect x="34.6274" y="32.5059" width="3" height="29" rx="1.5" transform="rotate(135 34.6274 32.5059)" fill="white"/>
					</svg>

			</div>
		</div>
		<div class="publish_content">
			<div class="modal_title_text">
				<div>{{$t('Publish.Publish')}}</div>
				<div class="modal_title_text_intro"></div>
			</div>
			<div class="publish_content_bottom">
				<div class="publidh_left">
					<div class="publidh_content_item">
						<div class="publidh_content_item_title">{{$t('Publish.CoverPicture')}}</div>
						<div class="publish_content_shrink publish_content_item">
							<img v-lazy="selectDate.url" alt="">
						</div>
					</div>
				</div>
				<div class="publidh_right">
					<div class="publidh_right_name publidh_content_item">
						<div class="publidh_content_item_title">{{$t('Publish.CollectionTitle')}}</div>
						<input type="text" v-model="subPublishDate.portfolioName">
						<!-- <div class="publidh_content_item_tag">
							<a-tag closable color="purple">#RCAworkshop_2024</a-tag> 
						</div> -->
					</div>
					<div class="publidh_right_name publidh_content_item">
						<div class="publidh_content_item_title">{{$t('Publish.Description')}}</div>
						<!-- <textarea @input="textareaChange()" ref="textarea" v-model="subPublishDate.portfolioDes"></textarea> -->
						<textarea ref="textarea" v-model="subPublishDate.portfolioDes"></textarea>
					</div>
					<div class="publidh_content_item_tagList">
						<div v-for="item,index in tagList" @click="pushTag(item,index)">
							<a-tag color="purple" :title="item.title">{{ item.tagName }}</a-tag> 
						</div>
					</div>
					<div class="publidh_right_detail publidh_content_item">
						<div class="publidh_content_item_title">{{$t('Publish.Permissions')}}</div>
						<div>
							<a-checkbox @change="setPermissionsItem()" v-model:checked="selectPermissions.isSecondaryCreation">{{$t('Publish.PermissionsItem1')}}</a-checkbox>
						</div>
					</div>
					<div class="publidh_content_item publidh_right_zhuyi">
					</div>
					<div class="publidh_right_btn">
						<div class="started_btn" @click="cancelDsign">{{$t('Publish.Close')}}</div>
						<div class="started_btn" @click="setPublish">{{!subPublishDate?.id?$t('Publish.Publish'):$t('Publish.UpdatePublish')}}</div>
					</div>
				</div>
			</div>
		</div>
		<div class="mark_loading" v-show="isShowMark">
			<a-spin size="large" />
		</div>
	</a-modal>
</template>

<script lang="ts">
import { defineComponent,watch,createVNode, inject, ref ,toRefs,computed,reactive,triggerRef, nextTick} from "vue";
import { Https } from "@/tool/https";
// import domTurnImg from '@/tool/domTurnImg'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { Modal,message } from 'ant-design-vue';
import { downloadIamge,base64ToFile } from "@/tool/util";
import { useI18n } from 'vue-i18n';
import { useStore } from "vuex";

export default defineComponent({
	emits: ['clearPublish'],
    setup(prop,{emit}) {
		let {t} = useI18n()
        const store = useStore();
        let publish: any = ref(false);//弹窗
		let publishMask:any = ref(false)//弹窗遮罩
		let publishData:any = reactive({
			selectObject:computed(()=>store.state.Workspace.probjects),//选择的项目
			publishName:'',
			loadingShow:false,
			publishMarginTop:0,
			publishList:[],
			publishIndex:0,//当前图片索引
			isShowMark:false,
			setPermissionsAll:true,
			selectDate:{
				url:'',
			},
			subPublishDate:{
				id:'',
				portfolioDes:''
			},
			selectPermissions:{
				isAllowComment:true,
				isDisplayArea:true,
				isSecondaryCreation:true,
			},
		})
		// let portfolio:any = inject('portfolio')

		// let setPortfolio:any = inject('setPortfolio')
		let tagList = ref([
			// {id:1,tagName:'#AiDAworkshop_2024',title:'The process is simple: use AiDA to post your design work on the "Gallery ", and the one with the most likes(at least 20 likes) will be invited to the AiDA Workshop offline event in Hong Kong on November 14th, to exchange ideas with the Royal College of Art (RCA), Jae Lim, co-founder of the renowned fashion brand BESFXXK, and outstanding designers! '},
			{id:3,tagName:'#NewYear_2025',title:"✨New Year 2025！🎉Let's kick off the year with a burst of inspiration and design!"}
		])
		// let textarea: any = ref(null)
		// let setCopy = ()=>{
		// 	textarea.value.select()
		// 	document.execCommand("copy");
		// }
		let init = (data:any)=>{
			let userInfo:any = store.state.UserHabit.userDetail
			// console.log(data);
			publish.value = true
			publishData.selectDate.url = data.imgUrl
			publishData.subPublishDate = {
				userLikeGroupId : data.userlikeGroupId,
				// userLikeGroupId : data.id,
				coverId : '',
				// coverId : data.groupDetails[0].designOutfitId,
				accountId : userInfo.userId,
				createDate:'',
				idDeleted:'',
				id:publishData.selectObject.publishData.id,
				portfolioDes:publishData.selectObject.publishData.portfolioDes,
				portfolioName:publishData.selectObject.publishData.portfolioName,
				portfolioType:'History',
				status:'',
				updateDate:'',
				collectionId:'',
				tagsDTO:publishData.selectObject.publishData.tagsDTO,
				// isAllowLikes:true,
			}
		}
		let setCover = (item:any)=>{
		    publishData.subPublishDate.coverId = item.designOutfitId
			publishData.selectDate.url = item.url

		}
		let extractHashtags = (text:any)=>{
			// const regex = /#\S+\s{2}/g;
			const regex = /#\S+\s/g;
			// 使用match方法提取匹配的字符串
			const matches = text.match(regex);
			// 处理提取结果，去掉空格并返回
			return matches ? matches.map((match:any) => match.replace(/\s+/g, '')) : []; // 去掉所有空格
		}
		let textareaChange = ()=>{
			let tagListArr =  extractHashtags(publishData.subPublishDate.portfolioDes)
			let tagsDTO:any = []
			for (let i = 0; i < tagListArr.length; i++) {
				const index = tagList.value.findIndex((obj:any) => obj.tagName === tagListArr[i]);
				const tagsDTOIndex = publishData.subPublishDate.tagsDTO.findIndex((obj:any) => obj.tagName === tagListArr[i]);
				let obj
				if(tagsDTOIndex>-1){
					obj = {
						tagName:publishData.subPublishDate.tagsDTO[tagsDTOIndex].tagName,
						id:publishData.subPublishDate.tagsDTO[tagsDTOIndex].id
					}
				}else if(index > -1){
					obj = {
						tagName:tagList.value[index].tagName,
						id:tagList.value[index].id
					}
				}else {
					obj = {tagName:tagListArr[i]}
				}
				tagsDTO.push(obj)
			}
			// publishData.subPublishDate.tagsDTO = tagsDTO
			return tagsDTO
		}
		let setPermissionsItem = ()=>{
			// publishData.selectPermissions.isAllowLikes && 
			if(publishData.selectPermissions.isAllowComment && publishData.selectPermissions.isDisplayArea && publishData.selectPermissions.isSecondaryCreation){
				publishData.setPermissionsAll = true
			}else{
				publishData.setPermissionsAll = false
			}
		}
		let setPermissions = ()=>{
			// publishData.selectPermissions.isAllowLikes = publishData.setPermissionsAll;
			publishData.selectPermissions.isAllowComment = publishData.setPermissionsAll
			publishData.selectPermissions.isDisplayArea = publishData.setPermissionsAll
			publishData.selectPermissions.isSecondaryCreation = publishData.setPermissionsAll
		}
		let cleardata = ()=>{
		    publish.value = false
			publishData.isShowMark = false
			publishData.subPublishDate = {}
			emit('clearPublish')
		}
		let cancelDsign = ()=>{
			Modal.confirm({
                title: t('Publish.jsContent1'),
                icon: createVNode(ExclamationCircleOutlined),
                okText: 'Yes',
                cancelText: 'No',
				mask:false,
                centered:true,
                onOk() {
					cleardata()
                }
            });
		}
		let setPublish= ()=>{
			if(!publishData.subPublishDate.portfolioName){
				return message.info(t('Publish.jsContent2'))
			}
			// if(!publishData.subPublishDate.portfolioDes){
			// 	return message.info('Please enter a description')
			// }
			Modal.confirm({
                title: t('Publish.jsContent3'),
                icon: createVNode(ExclamationCircleOutlined),
                okText: 'Yes',
                cancelText: 'No',
				mask:false,
                centered:true,
                onOk() {
					subPublish()
                }
            });
		}
		let subPublish = ()=>{
			
			let param = new FormData(); 
			// let fill = dataURLtoFile(publishData.selectDate.url,'collection')
			// let aa = new File([fill], 'collection' + ".jpg");

			let file = base64ToFile(publishData.selectDate.url,'collection')
			param.append('file',file)
			publishData.subPublishDate.openSource = publishData.selectPermissions.isSecondaryCreation?1:0
			let tagDTO = textareaChange()
			publishData.subPublishDate.tagsDTO = tagDTO
			param.append('data',JSON.stringify(publishData.subPublishDate))
			let config:any = {headers:{'Content-Type':'multipart/form-data','Accept':'*/*'  }}
			// let data = publishData.subPublishDate
			publishData.isShowMark = true
			Https.axiosPost(Https.httpUrls.publish, param,config)
                .then((rv) => {
					publishData.isShowMark = false
					let obj = {
						id:rv,
						portfolioName:publishData.subPublishDate.portfolioName,
						portfolioDes:publishData.subPublishDate.portfolioDes,
						tagsDTO:publishData.subPublishDate.tagsDTO,
					}
					cleardata()
					// setPortfolio(obj)
					message.success(t('Publish.jsContent4'))
                })
                .catch((rv) => {
					publishData.isShowMark = false

				});
		}
		let pushTag = (tag:any,index:number)=>{
			// let selectTag = tagList.value.splice(index,1)[0]
			// if(tag.tag == 'RCAworkshop_2024'){
			// 	publishData.subPublishDate.portfolioDes = '#AiDA x RCA workshop  '
			// }
			if(!publishData.subPublishDate.portfolioDes) publishData.subPublishDate.portfolioDes = ''
			publishData.subPublishDate.portfolioDes = publishData.subPublishDate.portfolioDes+tag.tagName + ' '
		}
        return {
            publish,
			publishMask,
			...toRefs(publishData),
			tagList,
			// textarea,
			// setCopy,
			init,
			textareaChange,
			setPermissionsItem,
			setPermissions,
			// download,
			// setScaleImageIndex,
			// LikeFile,
			setCover,
			cancelDsign,
			setPublish,
			pushTag,
        };
    },
    data() {
        return {
            // moodTemplateId: "", //模板id
			
        };
    },
    mounted() {
    },
    methods: {
    },
});
</script>

<style lang="less">
.publish_modal {
	.publish_page{
		overflow-y: auto;
		height: 100%;
		&.publish_page::-webkit-scrollbar{display: none;}
	}
	.publish_content{
		display: flex;
	    flex-direction: column;
		height: 100%;
		
	}
	:deep(.ant-tag){
		// position: absolute;
		// left: 10px;
		// top: 50%;
		// transform: translateY(-50%);
	}
	// .publidh_content_item_tag{
	// 	position: relative;
	// 	.ant-tag{
	// 		position: absolute;
	// 		left: 10px;
	// 		top: 50%;
	// 		transform: translateY(-50%);
	// 	}
	// }
	.publish_content_bottom{
		--border-color: #c4c4c4;
		display: flex;
		justify-content: space-between;
		flex: 1;
		height: calc(100% - 10rem);
		.publidh_content_item_tagList,.publidh_content_item_tag{
				// height: 4rem;
				border-radius: 1rem;
				display: flex;
				align-items: center;
				flex-wrap: wrap;
			}
			.publidh_content_item_tagList{
				margin-top: 1rem;
				.ant-tag{
					cursor: pointer;
					margin-bottom: 8px;
				}
			}
		.publidh_left,.publidh_right{
			display: flex;
			flex-direction: column;
		}
		.publidh_content_item{
			margin-bottom: 2rem;
			.publidh_content_item_title{
				font-weight: 600;
				font-size: 1.8rem;
				margin-bottom: 1rem;
				
			}
			.publidh_content_item_tagList,.publidh_content_item_tag{
				// height: 4rem;
				border-radius: 1rem;
				display: flex;
				align-items: center;
				flex-wrap: wrap;
			}
			.publidh_content_item_tagList{
				margin-top: 1rem;
				.ant-tag{
					cursor: pointer;
					margin-bottom: 8px;
				}
			}
			.publidh_content_item_tag{
				border: .2rem solid var(--border-color);
				// height: 4rem;
				padding: 2rem;
				padding-right: 0rem;
				.ant-tag{
					cursor: pointer;
					margin-bottom: 8px;
				}

			}
			
			.publidh_content_item_intro{
				font-size: 1.4rem;
			}
			input{
				width: 100%;
				border-radius: 1rem;
				height: 4rem;
				padding-left: 2rem;
				font-size: 2rem;
				border: .2rem solid var(--border-color);
			}
			textarea{
				flex: 1;
				margin-top: var(--padding);
				width: 100% !important;
				height: 10rem !important;
				border-radius: 1rem;
				border: .2rem solid var(--border-color);
				font-size: 1.8rem;
				padding: 1rem;
				color: #575757;
				outline: none; /* 清除默认焦点样式 */
			}
			textarea:focus{
				border: .2rem solid var(--border-color);
				outline: none; /* 清除默认焦点样式 */
			}
		}
		.publidh_content_item:last-child{
			margin-bottom: 0;
		}
		.publidh_left{
			width: 45%;
			.publidh_content_item{
				height: 100%;
			}
			.publish_content_shrink{
				width: 100%;
				height: calc(100% - 4rem);
				img{
					width: 100%;
					object-fit: contain;
					// object-fit: cover;
					// max-height: 30rem;
					max-height: 100%;
				}
			}
			.publidh_left_thubnai{
				flex: 1;
				.publidh_left_thubnail_list{
					display: flex;
					overflow-x: auto;
					height: 24rem;
					img{
						cursor: pointer;
						height: 100%;
						margin-right: 1rem;
					}
					img:last-child{
					    margin-right: 0;
					}
				}
			}
		}
		.publidh_right{
			width: 45%;
			.publidh_right_zhuyi{
				margin-top: auto;
			}
			.publidh_right_btn{
				display: flex;
				align-items: center;
				justify-content: flex-end;
				>div:nth-child(1){
					margin-right: auto;
				}
				>div:nth-child(2){
					margin-right: 1rem;
				}
			}
			.publidh_right_detail{
				display: flex;
				flex-direction: column;
				label{
					display: flex;
				}
			}
		}
	
	}
}
</style>