<template>
    <div class="collection_modal_item">
        <div class="modal_left" >
            <div class="switch_type_list" >
                <div
                    @click.stop="open(1)"
                    class="switch_type_item"
                    :class="[openClick == 1 ? 'select_swtich' : '']"
                >
                    <span>{{ $t('MoodboardUpload.Upload') }}</span>
                </div>
                <div
                    @click.stop="open(2)"
                    class="switch_type_item"
                    :class="[openClick == 2 ? 'select_swtich' : '']"
                >
                    <span>{{ $t('MoodboardUpload.Library') }}</span>
                </div>
                <div
                    @click.stop="open(3)"
                    class="switch_type_item"
                    :class="[openClick == 3 ? 'select_swtich' : '']"
                >
                    <span>{{ $t('MoodboardUpload.Generate') }}</span>
                </div>
            </div>
            <div v-show="openClick == 1" class="moodboard_body">
                <div class="upload_img_body scroll_style">
                    <div class="upload_item">
                        <div
                            class="upload_file_item"
                            v-for="(file, index) in fileList"
                            :key="file"
                        >
                            <div
                                class="upload_file_item_content"
								v-show="file?.status === 'uploading'"
                            >
                                <a-spin
                                    :indicator="indicator"
                                    tip="Uploading..."
                                />
                            </div>
                            <div
                                class="upload_file_item_content"
                                v-show="file?.status === 'done'"
                            >
                                <img :src="file?.imgUrl" class="upload_img" />
                                <div
                                    class="delete_file_block"
                                    @click="deleteFile(file)"
                                >
									{{ $t('MoodboardUpload.Delete') }}
                                </div>
                            </div>
                        </div>
                        <div
                            class="upload_file_item upload_component"
                            v-show="moodboarList.length < 8"
                        >
						
                            <a-upload
                                :action="uploadUrl + '/api/element/upload'"
                                list-type="picture-card"
								:capture="null"
                                :data="{
                                    ...upload,
                                }"
                                :headers="{ Authorization: token }"
                                :before-upload="beforeUpload"
                                v-model:file-list="fileList"
								:maxCount="8 - moodboarList.length+fileList.length"
                                accept=".jpg,.png,.jpeg,.bmp"
                                @change="(file) => fileUploadChange(file)"
                            >

                                <div
                                    class="upload_tip_block"
                                    v-show=" moodboarList.length < 8"
                                >
                                    <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 class="upload_max_tip">
					<span class="icon iconfont icon-zhuyi"></span>
					<span>{{ $t('MoodboardUpload.Maximum') }}</span>
				</div>
                <!-- <div class="upload_max_tip">
                    <span class="icon iconfont icon-zhuyi"></span>
                    <span
                        >Maximum 10 images can be uploaded, Maximum 2M per
                        image</span
                    >
                </div> -->
            </div>
            <Material
                v-show="openClick == 2"
                ref="Material"
                msg="Moodboard"
            ></Material>
            <Generate
                v-show="openClick == 3"
                ref="Generate"
                msg="Moodboard"
            ></Generate>
        </div>
        <div class="modal_right"  v-show="moodboarList.length >= 1 || edieShow">
			<div class="modal_layout" >
				<div class="modal_text">
					<div>
						{{ $t('MoodboardUpload.Thumbnail') }}
					</div>
					<div v-show="moodboarList.length > 1" class="modal_btn started_btn"  @click="layout()">{{ $t('MoodboardUpload.layout') }}</div>
				</div>
				<div class="modal_img" >
					<div class="modal_img_item" v-for="item,index in moodboarList" :key="item" @click="deleteFile(item)">
						<img v-lazy="item.imgUrl">
						<div class="checked" >
							<i class="fi fi-rr-trash"></i>
						</div>
					</div>
				</div>
			</div>
			<div class="modal_accomplish" v-show="modalImg[0]?.id || loadingShow">
				<div class="modal_text">
					<div>{{ $t('MoodboardUpload.selected') }}</div>
					<div class="modal_btn started_btn" @click.stop="changeTemplateModal()">{{ $t('MoodboardUpload.Edit') }}</div>
				</div>
				<div class="modal_img_max">
					<div v-if="!modalImg[0]?.id" class="modal_img" id="modal_img" :class="{active:flex_direction}">
						<div v-for="item,index in layoutList" :class="[moodb_className[index]]"  class="modal_imgItem">
							<img :src="item.imgUrl" v-modelImg>
						</div>
					</div>
					<div v-else class="modal_img">
						<img :src="modalImg[0].imgUrl">
					</div>
					<div class="mark_loading" v-show="loadingShow">
						<a-spin size="large" />
					</div>
				</div>
				
			</div>
			
		</div>
		<layout ref="layout" :moodb_className="moodb_className" :flex_direction="flex_direction" @setmoodbClass="setmoodbClass"></layout>
       
    </div>
</template>
<script lang="ts">
import { defineComponent, h, ref ,computed,nextTick,inject} from "vue";
import { LoadingOutlined } from "@ant-design/icons-vue";
import { getCookie } from "@/tool/cookie";
import { getUploadUrl,isMoible } from "@/tool/util";
import { useStore } from "vuex";
import { message, Upload } from "ant-design-vue";
import { Https } from "@/tool/https";
import Material from "@/component/HomePage/Material.vue";
import Generate from "@/component/HomePage/Generate.vue";
import MoodTemplate from "@/component/HomePage/MoodTemplate.vue";
import layout from "@/component/HomePage/layout.vue";
import domTurnImg from '@/tool/domTurnImg'
import GO from "@/tool/GO";
import moodb from "@/tool/moodb";
import { useI18n } from "vue-i18n";
export default defineComponent({
    components: { Material, MoodTemplate, Generate,layout },
    setup() {
		const store = useStore()
        let lessenList: any = ref([]);
        let fileList: any = ref([]);
        let showFileList: any = ref([]);
        let templateModal: any = ref(false);
        let templateFileList: any = ref([]);
        let openClick: any = ref(1);
		let moodb_className:any = ref([]);
		let flex_direction:any = ref(false)//判断第二种格子类型弹性布局方式
		let layoutList:any = []//选中后随机生成的list
		let layoutOpen = ref(false)
		let loadingShow = ref(false)
		let modalImg:any= computed(()=>{
			return store.state.UploadFilesModule.disposeMoodboard
		})
		let uploading:any = ref([])
		let edieShow:any = ref()
		let {t} = useI18n()

        return {
            fileList,
			showFileList,
            lessenList,
            templateModal,
            templateFileList,
            openClick,
			moodb_className,
			flex_direction,
			layoutList,
			layoutOpen,
			loadingShow,
			modalImg,
			uploading,
			edieShow,
			t,
        };
    },
    data() {
        return {
            indicator: h(LoadingOutlined, {
                style: {
                    fontSize: "2.4rem",
                },
                spin: true,
            }),
            upload: {
                isPin: 0,
				gender:'',
                level1Type: "Moodboard",
                timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
            },
            token: "",
            uploadUrl: "",
            moodTemplateId: "", //模板id
            store: useStore(),
			moodb_:moodb.moodb_,
			moodboarList:computed(()=>{
				return  useStore().state.UploadFilesModule.moodboard
			}),
        };
    },
	// watcheffect(){
	// 	let breviaryList = this.store.state.UploadFilesModule.moodboardFiles.filter(
    //                 (v: any) => v.checked == true
    //             );
	// 	this.store.commit("setMoodboardFile", breviaryList);
	// 	console.log(22);
	// },
    mounted() {
        this.token = getCookie("token") || "";
        this.uploadUrl = getUploadUrl();
    },
	directives:{
		modelImg:{
			mounted(el) {
				let parentNode = el.parentNode
				if(parentNode.offsetHeight >= parentNode.offsetWidth){
					el.style.height = 100+'%'
					el.style.width = 'auto'
				}else{
					el.style.width = 100+'%'
					el.style.height = 'auto'
				}
			},
			updated (el) {
				let parentNode = el.parentNode
				if(parentNode.offsetHeight >= parentNode.offsetWidth){
					el.style.height = 100+'%'
					el.style.width = 'auto'
				}else{
					el.style.width = 100+'%'
					el.style.height = 'auto'
				}
			}
		}
	},
    methods: {
        open(num: Number) {
            this.openClick = num;
			if(num ==2 ){
				let material:any = this.$refs.Material
				material.init('Moodboard')
			}else if (num == 3){
			}
        },
        fileUploadChange(data: any) {
            let file = data.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.resData = res.data;
					file.type_ = {
						type1:'upload',
						type2:'Moodboard'
					};
					file.id_ = GO.id++
					file.id = res.data.id
					let fileList = this.fileList.filter(
						(v: any) => v.status === "done"
					);
					let arr =  this.store.state.UploadFilesModule.moodboard
					if(arr.length >= 8){
						message.info(this.t('MoodboardUpload.jsContent1'))
					}else{
						this.store.commit("setMoodboardFile", fileList);
					}
				}else{
					bor = false
				}
				// this.showFileList = this.fileList
            } else if (file.status === "error") {
				bor = false
            }
			if(!bor){
                let res:any = JSON.parse(file.xhr.response);
				let index = -1;
                this.fileList.forEach((ele: any, index1: any) => {
                    if (file.uid === ele.uid) {
                        index = index1;
                    }
                });
                if (index > -1) {
                    this.fileList.splice(index, 1);
                }
                // message.warning(file.name + this.t('MoodboardUpload.jsContent2'));
                message.warning(res.errMsg);
			}
        },
        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(this.t('MoodboardUpload.jsContent3'));
            }
            const isLt2M = file.size / 1024 / 1024 < 5;
            if (!isLt2M) {
                message.info(this.t('MoodboardUpload.jsContent4'));
            }
            return (isJpgOrPng && isLt2M) || Upload.LIST_IGNORE;
        },

        deleteFile(item: any) {
			if(item.type_.type1 == 'generate' || item.type_.type1 == 'material'){
				item.jsContent1 = this.t('uploadFile.jsContent1',{maxImg:8})
				item.state = 'delete'
				this.store.commit("addGenerateMaterialFils", item);
			}else{
				this.fileList = this.store.state.UploadFilesModule.moodboardFiles
				let moodboard 
				this.store.state.UploadFilesModule.moodboardFiles.forEach((items:any,index:Number)=>{
					if(items.id_ == item.id_){
						moodboard = index
						
					}
				})
				this.fileList.splice(moodboard,1)
				this.store.commit("setMoodboardFile", this.fileList);
			}
			if(this.store.state.UploadFilesModule.moodboard.length == 0){
				this.store.commit("clearMoodTemplateId");
				this.layoutList = []
				this.edieShow = false
			}
        },
        openSetData() {
            let arr = JSON.parse(
                JSON.stringify(
                    this.store.state.UploadFilesModule.allBoardData
                        .moodboardFiles
                )
            ) || [];
			let disposeMoodboard = JSON.parse(
                JSON.stringify(
                    this.store.state.UploadFilesModule.allBoardData
                        .disposeMoodboard
                )
            );
			let moodboardPosition = JSON.parse(
                JSON.stringify(
                    this.store.state.UploadFilesModule.allBoardData
                        .moodboardPosition
                )
            );
			let setboard = {
				generate:[] as any,
				material:[] as any,
				moodboard:[] as any,
			}
			arr.forEach((v:any)=>{
				if(v.type_.type1 == 'generate'){
					setboard.generate.push(v)
				}else if(v.type_.type1 == 'material'){
					setboard.material.push(v)
				}else{
					setboard.moodboard.push(v)
				}
			})
			this.store.commit("setMoodboardGenerateFiles", setboard.generate);
			this.store.commit("setMoodboardMaterialFiles", setboard.material);
			this.store.commit("setMoodboardFile", setboard.moodboard);
			this.store.commit("setDisposeMoodboard", disposeMoodboard[0]);
			this.store.commit("setDisposeMoodboardPosition",moodboardPosition);
			this.fileList = setboard.moodboard
        },

        async changeTemplateModal() {
			if(this.modalImg[0]?.id){
				let layout:any = this.$refs.layout
				if(this.layoutList.length <= 0){
					let styleObj = this.store.state.UploadFilesModule.moodboardPosition
					if(!styleObj.domStyle)await this.layout()
					// 
					let arr = JSON.parse(JSON.stringify(this.store.state.UploadFilesModule.moodboard))
					this.layoutList = arr
				}
				if(window.screen.width<1300){
					layout.isMobile = true
				}else{
					layout.isMobile = false
				}
				
				layout.init()
			}else{
				message.info(this.t('MoodboardUpload.jsContent5'))
			}
			
        },
		async layout(){
			if(this.loadingShow)return
			await new Promise((resolve, reject) => {
				this.loadingShow = true
				this.store.commit("setDisposeMoodboard", []);
				let arr = JSON.parse(JSON.stringify(this.store.state.UploadFilesModule.moodboard))
				this.layoutList = arr
				var random = Math.round(Math.random()*(this.moodb_[arr.length-1].length-1))
				let moodb =  this.moodb_[arr.length-1][random]
				if( moodb.filter((item,index)=> item == 'w2h1').length != 0  && arr.length > 4){
					this.flex_direction = true
				}else{
					this.flex_direction = false
				}
				if(this.moodb_[arr.length-1].length != 1){
					if(JSON.stringify(this.moodb_className) == JSON.stringify(this.moodb_[arr.length-1][random])){
						this.loadingShow = false
						this.layout()
						return resolve('')
					}
				}
				this.edieShow = true
				if(this.moodb_[arr.length-1].length == 2){
					this.moodb_className = this.moodb_[arr.length-1][0]
				}else{
					this.moodb_className = this.moodb_[arr.length-1][random]
				}
				this.layoutOpen = true
				//提交模板
				// this.loadingShow = true
				this.layoutList.forEach((v:any)=>{
					v.setPitch = false
				})
				nextTick().then(()=>{
					let layoutCentent = document.getElementById('modal_img')
					let obj = {
						imgStyle:[],
						domStyle:[],
						borStyle:[],
						rototeStyle:[],
						translateStyle:[],
						angleTRStyle:[],
						angleTLStyle:[],
						angleBRStyle:[],
						angleBLStyle:[],
						class:this.moodb_className,
					}
					this.store.commit("setDisposeMoodboardPosition", obj);
					domTurnImg(layoutCentent).then((rv)=>{
						let file = rv
						let param = new FormData(); 
						param.append('inPin','0')
						param.append('level1Type','Moodboard')
						param.append('gender','')
						param.append('timeZone',Intl.DateTimeFormat().resolvedOptions().timeZone)
						param.append('file',file);
						let config:any = {headers:{'Content-Type':'multipart/form-data','Accept':'*/*'  }}
						Https.axiosPost(Https.httpUrls.elementUpload,param,config)
						.then((rv: any) => {
								let img:any = rv
								img.imgUrl = rv.url
								img.resData = JSON.parse(JSON.stringify(img))
								this.store.commit("setDisposeMoodboard", img);
								this.loadingShow = false
								resolve('')
							}
						).catch(rv=>{
							this.loadingShow = false
						})
					})
					
				})			
			})
			    
		},
		setmoodbClass(val:any){
			this.moodb_className = val
		}
    },
});
</script>
<style lang="less" scoped>
.collection_modal_item {
    // padding: 1.5rem 2.6rem 4rem;
    height: 100%;
	flex: 1;
    display: flex;
	justify-content: space-between;
	.modal_left,.modal_right{
		background: #f7f8fa;
		border-radius: 3rem;
		padding: 2rem 3rem;
	}
    .modal_left {
		width: 71rem;
		display: flex;
		flex-direction: column;
		flex-shrink: 0;
		margin-right: 2rem;
        // width: 50rem*1.2);
        .switch_type_list {
            display: flex;
            align-items: center;
            position: relative;

            .switch_type_item {
                display: flex;
                align-items: center;
                // padding: 0 2rem*1.2);
                height: calc(4rem*1.2);
                border-radius: calc(0.8rem*1.2);
                line-height: calc(4rem*1.2);
                font-size: var(--aida-fsize1-8);
                // margin-right: 2.2rem*1.2);
                margin-right: calc(8rem*1.2);
                color: #000;
                cursor: pointer;
                position: relative;
                text-align: center;
                transform-origin: left;
                transform: scale(1);
                transition: 0.3s all;
                &.switch_type_item::before {
                    position: absolute;
                    content: "";
                    display: block;
                    background: #000;
                    height: calc(.3rem*1.2);
                    left: 50%;
                    transform: translateX(-50%);
                    bottom: calc(.6rem*1.2);
                    width: 0px;
                    transition: 0.3s all;
                }
                &.select_swtich {
                    color: #000;
                    // font-weight: 900;
                    transform: scale(1.15);
                }
                &.select_swtich::before {
                    width: 100%;
                }

                .switch_icon {
                    font-size: calc(1.8rem*1.2);
                    margin-right: calc(0.8rem*1.2);
                }
            }
        }

        .moodboard_body {
            padding-top: calc(2.5rem*1.2);
			flex: 1;
            height: calc(30rem*1.2);
            overflow-x: hidden;
            border-right: 1px solid #e5e5e5;
			display: flex;
			flex-direction: column;
            &.moodboard_body::-webkit-scrollbar {
                display: none;
            }
            .upload_img_body {
				height: 100%;
                overflow-y: auto;
                margin-bottom: calc(1rem*1.2);
            }

            

            .upload_max_tip {
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: calc(1.4rem*1.2);
                color: #030303;

                .icon-zhuyi {
                    font-size: calc(1.6rem*1.2);
                    margin-right: calc(0.7rem*1.2);
                }
            }
        }
    }
	.modal_right{
		flex: 1;
		display: flex;
		min-width: calc(57rem*1.2);
		flex-direction: column;
		overflow: hidden;
		.modal_layout,.modal_accomplish{
			.modal_text{
				font-size:var(--aida-fsize1-4);
				font-weight: 400;
				color: rgba(0, 0, 0, 0.45);
				display: flex;
				align-items: center;
				justify-content: space-between;
			}
		}
		.modal_layout{
			.modal_img{
				width: calc(40rem*1.2);
				height: calc(5rem*1.2);
				overflow-x: hidden;
				display: flex;
				&.modal_img::-webkit-scrollbar {
					display: none;
				}
				.modal_img_item{
					width: calc(4rem*1.2);
					height: calc(4rem*1.2);
					text-align: center;
					margin: 0 calc(1rem*1.2) calc(1rem*1.2) 0;
					position: relative;
					cursor: pointer;
					overflow: hidden;
					img{
						width: auto;
						height: 100%;
						max-width: 100%;
						object-fit: cover;
					}
					.checked{
						position: absolute;
						top: 0;
						left: 0;
						width: 100%;
						height: 100%;
						cursor: pointer;
						display: none;
						justify-content: center;
						align-items: center;
					}
					&.modal_img_item:hover .checked{
						display: flex;
					}
				}
				
			}
		}
		.modal_accomplish{
			// margin-top: 2rem*1.2);
			height: calc(30rem*1.2);
			display: flex;
			flex: 1;
			flex-direction: column;
			.modal_text{
				padding-top: calc(2rem*1.2);
				padding-block: calc(2rem*1.2);
			}
			.modal_img_max{
				// flex: 1;
				// width: 57rem;
				// height: 35rem;
				width: 92rem;
				height: 56.5rem;
				position: relative;
				.mark_loading{
					position: absolute;
				}
			}
			.modal_img{
				height: 100%;
				display: flex;
				flex-direction: column;
				justify-content: space-between;
				flex-wrap: wrap;
				align-items: center;
				flex-direction: column;
				position: relative;
				
				>img{
					// height: 100%;
					width: 100%;
					max-height: 100%;
					object-fit: contain;
				}
				&.active{
					flex-direction: row;
				}
				.modal_imgItem{
					position: relative;
					overflow: hidden;
					text-align: center;
					img{
						position: absolute;
						top: 50%;
						left: 50%;
						transform: translate(-50%,-50%);
						float: left;
						user-select:none;
						-webkit-user-drag: none;
					}
				}
				.wh1{
					width: 23%;
					height: 48%;
				}
				.wh4{
					width: 48.5%;
					height: 100%;
				}
				.wh8{
					width: 100%;
					height: 48.5%;
				}
				.w1h2{
					width: 23%;
					height: 100%;
				}
				.w2h1{
					width: 48.5%;
					height: 48%;
				}
			}
		}
	}
}
</style>

