<template>
    <div class="printboard_upload_modal">
		
        <div class="printboard_left_upload">
            <div class="left_upload_header">
                <div class="upload_header_item">
                    <div class="switch_type_list">
                        <div
							@click.stop="open(1)"
							class="switch_type_item"
							:class="[openClick == 1 ? 'select_swtich' : '']"
						>
							<span>{{ $t('PrintboardUpload.Upload') }}</span>
						</div>
						<div
							@click.stop="open(2)"
							class="switch_type_item"
							:class="[openClick == 2 ? 'select_swtich' : '']"
						>
							<span>{{ $t('PrintboardUpload.Library') }}</span>
						</div>
						<div
							@click.stop="open(3)"
							class="switch_type_item"
							:class="[openClick == 3 ? 'select_swtich' : '']"
						>
							<span>{{ $t('PrintboardUpload.Generate') }}</span>
						</div>
                    </div>
                </div>
            </div>
             <div v-show="openClick == 1" class="printboard_body">
                <div class="upload_img_body">
                    <div class="upload_item">
                        <div :class="['upload_file_item']" v-for="(file, index) in fileList" :key="file">
                            <div class="upload_file_img_block">
                                <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  v-lazy="file.imgUrl" class="upload_img" :key="file.imgUrl">
                                    <div class="delete_like_file_block" @click.stop="deleteFile(file)">
										<span
											class="icon iconfont icon-shanchu"
										></span>
									</div>
                                </div>
                            </div>
                            <div class="pin_block" v-show="file?.status === 'done'">
                                <a-checkbox v-model:checked="file.pin">{{ $t('PrintboardUpload.PIN') }}</a-checkbox>
                            </div>
                            
                        </div>
                        <div class="upload_file_item upload_component" v-show="printboardList.length < 8">
                            <a-upload
                                :action="uploadUrl + '/api/element/upload'"
                                list-type="picture-card"
                                :before-upload="beforeUpload"
                                :data="{
                                    ...upload
                                }"
                                :headers="{Authorization:token}"
                                v-model:file-list="fileList"
                                :customRequest="function(){}"
                                multiple
                                :maxCount="8 - printboardList.length+fileList.length"
                                accept=".jpg,.png,.jpeg,.bmp"
                                @change="fileUploadChange"
                                >
								<div
                                    class="upload_tip_block"
									v-show="printboardList.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>
			<Material v-show="openClick == 2" ref="Material" msg="Printboard" @confirmSelect="confirmSelect"></Material>
			<Generate v-show="openClick == 3" ref="Generate" msg="Printboard" @generateCheckbox="getgenerateCheckbox"></Generate>
        </div>
		<div class="modal_right">
			<div class="modal_layout">
				<div class="modal_text">
					<div>{{ $t('PrintboardUpload.Thumbnail') }}</div>
					<!-- <div class="modal_btn started_btn" @click="layout()">layout</div> -->
				</div>
				<div class="modal_img">
					<div class="modal_img_item" v-for="item,index in printboardList" :key="item" @click.stop="deleteFile(item)">
						<img v-lazy="item.imgUrl">
						<div class="checked" >
							<i class="fi fi-rr-trash"></i>
						</div>
					</div>
				</div>
			</div>
			<div v-show="openClick == 3" class="modal_accomplish">
				<div class="input_box" :class="{active:inputShow}">
					<input class="search_input" @input="ifMaximumLength" :maxlength='inputShow?0:9999' :class="{forbidden:generateCheckbox}" :readonly="generateCheckbox" :placeholder="$t('PrintboardUpload.inputContent1')" v-model="captionGeneration">
					<div class="generage_btn started_btn" @click.stop="getgenerate">{{ $t('PrintboardUpload.Generate') }}</div>
					<span>{{ $t('PrintboardUpload.maximumLength') }}</span>
				</div>
				<div class="modal_img">
					<div v-for="item,index in generateList" class="modal_imgItem" :class="{ active: item?.checked }" >
						<img :src="item.imgUrl" @click.stop="generageAdd(item)">
						<div
							class="delete_like_file_block"
						>
							<i v-if="!item.like" class="fi fi-rr-heart" @click.stop="likeFile(item,'like')"></i>
							<i v-else class="fi fi-sr-heart" @click.stop="likeFile(item,'noLike')"></i>
						</div>
						<div class="pin_block">
							<a-checkbox v-model:checked="item.pin">{{ $t('PrintboardUpload.PIN') }}</a-checkbox>
						</div>
					</div>
					<div class="mark_loading" v-show="loadingShow">
						<a-spin size="large" />
					</div>
				</div>
			</div>
		</div>
		
        <Cropper ref="Cropper" @handleCropperSuccess="handleCropperSuccess" @closeCropper="deletUploadFile()" :cropperFileData="cropperFileData" :isUpload="isUpload"></Cropper>
    </div>
</template>
<script lang="ts">
import { defineComponent,h,ref,computed } from 'vue'
import { LoadingOutlined } from '@ant-design/icons-vue';
import {getCookie} from '@/tool/cookie'
import {getUploadUrl} from '@/tool/util'
import {useStore} from 'vuex'
import { Https } from "@/tool/https";
import { message,Upload} from 'ant-design-vue';
import Cropper from '@/component/HomePage/Cropper.vue'
import Material from '@/component/HomePage/Material.vue'
import Generate from "@/component/HomePage/Generate.vue";
import GO from "@/tool/GO";
import { useI18n } from 'vue-i18n';

export default defineComponent({
    components:{
        Cropper,
        Material,
		Generate
    },
    setup(){
        let store:any =useStore()
        let fileList:any = ref([]),//选中的文件id数据
            printImgList:any = ref([]), //print的印花图片
            moodBoards:any = computed(()=>{return store.state.UploadFilesModule.moodboardFiles})
        let openClick: any = ref(1);
		let generateCheckbox:any = ref()
		let generateList:any = ref([])
		let loadingShow = ref(false)
		let inputShow = ref(false)
		let inputTime = ref()
		let {t} = useI18n()
        return {
            fileList,
            printImgList,
            moodBoards,
			openClick,
			generateCheckbox,
			generateList,
			loadingShow,
			inputShow,
			inputTime,
			t,
        }
    },
    computed:{
        getPinLength(){
            let selectLength:any =  0 
            for(let item of this.fileList){
                if(item.pin){
                    selectLength++
                }
            }
            return selectLength
           
        }
    },
    data(){
        return {
            swtich_type:'upload',
            indicator : h(LoadingOutlined, {
                style: {
                    fontSize: '2.4rem',
                },
                spin: true,
            }),
            upload:{
                isPin:0,
                level1Type:'Printboard',
                timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,
            },
            token:'',
            uploadUrl:'',
            store:useStore(),
            cropperFileData:{name:'',uid:''}, //裁剪的原始文件数据
            currentFileNum:0, //当前上传的文件数
            isUpload:false,
            generateloading:false,
			captionGeneration:'',
			printboardList:computed(()=>{
				return  useStore().state.UploadFilesModule.printboard
			}),

        }
    },
    mounted(){
        this.token = getCookie('token') || ''
        this.uploadUrl = getUploadUrl()
    },
     methods:{
		open(num: Number) {
            this.openClick = num;
			let material:any = this.$refs.Material
			if(num == 2){
				material.init('Printboard')
			}
        },
        fileUploadChange(data:any){
            let file = data.file
			file.id_ = GO.id++
			file.type_ = {
				type1:'upload',
				type2:'Printboard'
			};
			file.pin = false;
            let Cropper:any = this.$refs.Cropper
            if(this.currentFileNum === 1){
                var reader = new FileReader();
                reader.onload = (e:any) => {
                    let data_new;
                    if (typeof e.target.result === 'object') {
                    // 把Array Buffer转化为blob 如果是base64不需要
                    data_new = window.URL.createObjectURL(new Blob([e.target.result]));
                    } else {
                    data_new = e.target.result;
                    }
                    Cropper.getOptionImg(data_new)
                };
                // 转化为base64
                // reader.readAsDataURL(file)
                // 转化为blob
                reader.readAsArrayBuffer(file.originFileObj);
                this.cropperFileData = file
                Cropper.changeShowModal(true)
                
            }else{
                this.customRequest(file)
            }
        },

        beforeUpload(file:any,fileList:any){
            const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/bmp';
            if (!isJpgOrPng) {
                message.warning(this.t('PrintboardUpload.jsContent1'));
            }
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isLt2M) {
                message.warning(this.t('PrintboardUpload.jsContent2'));
            }
            if(isJpgOrPng && isLt2M){
                this.currentFileNum = fileList.length
            }else{
                return (isJpgOrPng && isLt2M) || Upload.LIST_IGNORE;
            }
            
        },

        deleteFile(item:any){
            // this.fileList.splice(item, 1)
            // this.store.commit('setPrintboardFile',this.fileList)
			if(item.type_.type1 == 'generate' || item.type_.type1 == 'material'){
				item.jsContent1 = this.t('uploadFile.jsContent1')
				this.store.commit("addGenerateMaterialFils", item);
			}else{
				this.fileList = this.store.state.UploadFilesModule.printboardFiles
				let moodboard 
				this.store.state.UploadFilesModule.printboardFiles.forEach((items:any,index:Number)=>{
					if(items.id_ == item.id_){
						moodboard = index
						
					}
				})
				this.fileList.splice(moodboard,1)
				this.store.commit("setPrintboardFile", this.fileList);
			}
        },
		likeFile(item:any,str:string){
			if(str == 'like'){
				let data = {
					generateDetailId:item.id,
					level1Type:"Printboard",
					level2Type: '',
					timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone
				}
				Https.axiosPost(Https.httpUrls.generateLike, data).then(
					(rv) => {
						item.like = true
					}
				).catch(res=>{
				});
			}else{
				let data = {
					generateDetailId:item.id,
					timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone
				}
				Https.axiosGet(Https.httpUrls.generateDislike, {params:data}).then(
					(rv) => {
						item.like = false
					}
				).catch(res=>{
				});
			}

		},

        
        customRequest(data:any){
            let new_data = {
                ...this.upload,
                file:data.originFileObj
            }
            let fileUid = data.uid
            Https.axiosPost('/api/element/upload', new_data,{headers:{'Content-Type': 'multipart/form-data'}}).then(
                (rv: any) => {
                    if (rv) {
                        for(let file of this.fileList){
                            if(fileUid === file.uid){
                                file.status = 'done'
                                file.imgUrl = rv.url
                                file.pin = false
                                file.id = rv.id
                                file.resData = rv

                            }
                        }
                        let fileList = this.fileList.filter((v:any)=> v.status === 'done')
                        this.store.commit('setPrintboardFile',fileList)
                    }
                }
            ).catch((res)=>{
                let index = -1
                this.fileList.forEach((ele:any,index1:any) => {
                    if(fileUid === ele.uid){
                        index = index1
                    }
                });
                if(index > -1){
                    this.fileList.splice(index, 1)
                }
            });
        },

        closeCropper(type:any){
            if(this.isUpload){
                return
            }
            if(type == 'error'){
                let index = -1
                this.fileList.forEach((ele:any,index1:any) => {
                    if(this.cropperFileData.uid === ele.uid){
                        index = index1
                    }
                });
                if(index > -1){
                    this.fileList.splice(index, 1)
                }
            }
            let Cropper:any = this.$refs.Cropper
            Cropper.closeCropper()

        },

        deletUploadFile(){
            let index = -1
            this.fileList.forEach((ele:any,index1:any) => {
                if(this.cropperFileData.uid === ele.uid){
                    index = index1
                }
            });
            if(index > -1){
                this.fileList.splice(index, 1)
            }
        },


        handleCropperSuccess(event:any){
            let {file, fileData} =event
            let new_data = {
                ...this.upload,
                file:file
            }
            if(this.isUpload){
                return
            }
            this.isUpload = true
            const hide = message.loading('loading', 0);
            Https.axiosPost('/api/element/upload', new_data,{headers:{'Content-Type': 'multipart/form-data'}}).then(
                (rv: any) => {
                    for(let file of this.fileList){
                        if(fileData.uid === file.uid){
                            file.status = 'done'
                            file.imgUrl = rv.url
                            file.id = rv.id
                            file.resData = rv
                        }
                    }
                    let fileList = this.fileList.filter((v:any)=> v.status === 'done')
                    this.isUpload = false
                    this.closeCropper('success')
                    this.cropperFileData = {name:'',uid:''}
                    this.store.commit('setPrintboardFile',fileList)
                    hide()
                }
            ).catch(res=>{
                let index = -1
                this.fileList.forEach((ele:any,index1:any) => {
                    if(fileData.uid === ele.uid){
                        index = index1
                    }
                });
                if(index > -1){
                    this.fileList.splice(index, 1)
                }
                this.cropperFileData = {name:'',uid:''}
                this.isUpload = false
                this.closeCropper('error')
                hide()
            });
        },

        recollection(){
            let arr = JSON.parse(JSON.stringify(this.store.state.UploadFilesModule.allBoardData.printboardFiles))
			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("setPrintboardGenerateFiles", setboard.generate);
			this.store.commit("setPrintboardMaterialFiles", setboard.material);
			this.store.commit("setPrintboardFile", setboard.moodboard);
			this.fileList = setboard.moodboard
            // this.printImgList = JSON.parse(JSON.stringify(this.store.state.UploadFilesModule.allBoardData.generatePrintFiles))
            this.store.commit('setPrintboardFile',this.fileList)
            // this.store.commit('setGeneratePrintFile',this.printImgList)

        },

        confirmSelect(event:any){
            for(let item of event){
                let data = {
                    imgUrl:item.url,
                    resData:item,
                    pin:false,
                    id:item.id,
                    status:'done',
                }
                if(this.fileList.length == 15){
                    message.warning(this.t('PrintboardUpload.jsContent3'))
                    break
                }
                this.fileList.push(data)
            }
            this.store.commit('setPrintboardFile',this.fileList)
            
        },
		getgenerateCheckbox(value:any){
			this.generateCheckbox = value
		},
		ifMaximumLength(){
			clearTimeout(this.inputTime)
			this.inputTime = setTimeout(()=>{
				if(this.captionGeneration.split(/\s+/).length > 75){
					this.inputShow = true
				}else{
					this.inputShow = false
				}
			},500)
		},
		getgenerate(){
			let generage:any = this.$refs.Generate
			let generateType = generage.checkbox.filter((v:any)=>v.type)[0].name
			let data = {
				generateType:generateType,
				designType:'',
				collectionElementId:generage?.collectionElementid,
				level1Type:generage.upload.level1Type,
				level2Type:'',
				text:this.captionGeneration,
				timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,
				version:generage.printModel.num,//为1就是Print
				gender:'',
			}
			if(generateType == 'image'||generateType == 'text-image'){
				if(generage?.collectionElementid){
					
				}else{
					message.warning(
						this.t('PrintboardUpload.jsContent4')
					);
					return
				}
			}else if(generateType == 'text'){
				data.collectionElementId = ''
				data.level2Type = ''
				// this.beforeUpload(false)
				if(this.captionGeneration){
					let arr = this.captionGeneration.split(/\s+/).length
					if(arr > 75){
						message.warning(
							this.t('PrintboardUpload.jsContent5')
						);
					return

					}
				}else{
					message.warning(
						this.t('PrintboardUpload.jsContent6')
					);
					return
				}
			}
			this.loadingShow = true
			Https.axiosPost(Https.httpUrls.sketchAndPrintGenerate, data).then(
                (rv) => {
					if(rv){
						this.generateList = []
						let arr
						rv.generatedCollectionItems.forEach((v:any,index:number)=>{
							arr = {
								id:v.generateItemId,
								imgUrl:v.generateItemUrl,
								id_:GO.id++
							}
						this.generateList.push(arr)
						this.loadingShow = false
						})
					}
                }
            ).catch(res=>{
				this.loadingShow = false
            });
		},
		generageAdd(item:any){
			item.type_ = {
                type1: "generate",
                type2: 'Printboard',
            },
			item.resData = JSON.parse(JSON.stringify(item))
			item.jsContent1 = this.t('uploadFile.jsContent1')
            this.store.commit("addGenerateMaterialFils", item);
		}
     }

})
</script>
<style lang="less" scoped>
.printboard_upload_modal{
    // padding: 1rem 1rem 1.8rem 1rem;
	height: 100%;
    display: flex;
    .printboard_left_upload{
        // width: calc(100% - 39.8rem);
        // height: 100%;
        // background: #fff;
        // padding: 0.5rem 2.2rem 2rem 2.6rem;
        // box-sizing: border-box;
		display: flex;
		flex-direction: column;
        padding-top: 4rem;
        width: 47%;
        .switch_type_list {
            display: flex;
            align-items: center;
            position: relative;

            .switch_type_item {
                display: flex;
                align-items: center;
                // padding: 0 2rem;
                height: 4rem;
                background: #fff;
                border-radius: 0.8rem;
                line-height: 4rem;
                font-size: 1.6rem;
                // margin-right: 2.2rem;
                margin-right: 8rem;
                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: .3rem;
                    left: 50%;
                    transform: translateX(-50%);
                    bottom: .6rem;
                    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: 1.8rem;
                    margin-right: 0.8rem;
                }
            }
        }

        .printboard_body{
            // height: calc(100% - 5rem);
			flex: 1;
			padding-top: 2.5rem;
			height: 30rem;
			overflow-x: hidden;
			border-right: 1px solid #e5e5e5;
			&.printboard_body::-webkit-scrollbar {
            display: none;
        }
            .upload_img_body{
                height: calc(100% - 3rem);
                overflow-y: auto;
                margin-bottom: 1rem;
				&.upload_img_body::-webkit-scrollbar {
					display: none;
				}
            }
		
            .upload_file_item{
                margin: 0 2rem 5rem 0;
				// margin: 0 2rem 2rem 0;
				display: inline-block;
				width: 10rem;
				height: 10rem;
				border: 1px solid #f5f5f5;
				vertical-align: top;
				position: relative;
				text-align: center;
				img{
					width: auto;
					object-fit: cover;
					height: 100%;
					max-width: 100%;
				}

              .upload_file_img_block{
				height: 100%;
			  }

                &.upload_component{
                    border: none;
					:deep(.ant-upload-picture-card-wrapper) {
						position: absolute;
						top: 50%;
						left: 50%;
						transform: translate(-50%, -50%);
					}
					:deep(.ant-upload-select-picture-card) {
						width: 6rem;
						height: 6rem;
						border: 0.3rem solid #ededed;
						border-radius: 1rem;
						margin: 0;
					}
                }
				.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;
				}
				.upload_file_item_content{
					display: flex;
					align-items: center;
					justify-content: center;
					height: 100%;
					position: relative;
					cursor: pointer;
					.upload_img{
						display: block;
						max-height: 100%;
						width: auto;
						max-width: 100%;
						object-fit: cover;
					}
					&:hover .delete_like_file_block{
						display: block;
					}
				}
			}
        }
    }
	.delete_like_file_block{
		display: none;
		width: 3.2rem;
		height: 3.2rem;
		background: rgba(0,0,0,0.6);
		border-radius: 0.4rem;
		position: absolute;
		top: 0.9rem;
		right: 0.9rem;
		text-align: center;
		line-height: 3.2rem;
		left: auto;
		.icon-shanchu{
			font-size: 1.6rem;
			color: #fff;
		}
		i{
			font-size: 1.6rem;
			color: #fff;
			&.fi-rr-heart{

			}
			&.fi-sr-heart{
				color: red;
			}
		}
	}
	
	.modal_right{
		flex: 1;
		margin-left: 3rem;
		display: flex;
		flex-direction: column;
		.modal_layout,.modal_accomplish{
			.modal_text{
				font-size: 1.2rem;
				font-weight: 400;
				color: rgba(0, 0, 0, 0.45);
				display: flex;
				align-items: center;
				justify-content: space-between;
			}
		}
		.modal_layout{
			.modal_img{
				width: 40rem;
				height: 5rem;
				overflow-x: hidden;
				display: flex;
				flex-direction: row;
				&.modal_img::-webkit-scrollbar {
					display: none;
				}
				.modal_img_item{
					width: 4rem;
					height: 4rem;
					margin: 0 1rem 1rem 0;
					position: relative;
					cursor: pointer;
					text-align: center;
					img{
						width: auto;
						height: 100%;
						object-fit: cover;
						max-width: 100%;
					}
					.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;
			height: 30rem;
			display: flex;
			flex-direction: column;
			flex: 1;
            // overflow-x: hidden;
			&.modal_accomplish::-webkit-scrollbar {
                display: none;
            }
			.modal_text{
				padding-top: 2rem;
				padding-block: 2rem;
			}
			.input_box{
				input{
					&.forbidden{ 
					}
				}
			}
			.modal_img{
				flex: 1;
				display: flex;
				flex-wrap: wrap;
				justify-content: flex-start;
				position: relative;
				align-content: flex-start;

				.mark_loading{
					position: absolute;
					width: 100%;
					height: 100%;
					z-index: 99;
				}
				.modal_imgItem{
					margin: 0 2rem 5rem 0;
					display: inline-block;
					width: 10rem;
					height: 10rem;
					border: 1px solid #f5f5f5;
					position: relative;
					cursor: pointer;
					img{
						object-fit: cover;
						height: 100%;
						max-width: 100%;
						width: auto;
					}
					&:hover .delete_like_file_block{
						display: block;
					}
					&.active{
						opacity: 0.5;
					// border: 2px solid;
						border-radius: 1rem;
						transform: scale(0.9);
						img {
						}
						.pin_block{
							pointer-events:none;
						}
						.delete_like_file_block{
							pointer-events:none
						}
					}
				}
			}
		}
	}
}


</style>
