<template>
    <div class="sketchboard_upload_modal">
        <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('SketchboardUpload.Upload') }}</span>
                </div>
                <div
                    @click.stop="open(2)"
                    class="switch_type_item"
                    :class="[openClick == 2 ? 'select_swtich' : '']"
                >
                    <span>{{ $t('SketchboardUpload.Library') }}</span>
                </div>
                <div
                    @click.stop="open(3)"
                    class="switch_type_item"
                    :class="[openClick == 3 ? 'select_swtich' : '']"
                >
                    <span>{{ $t('SketchboardUpload.Generate') }}</span>
                </div>
            </div>
            <div v-show="openClick == 1" class="sketchboard_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="operate_file_block">
                                    <div class="select_img_type">
                                        <div
                                            class="select_category"
                                            @click.stop="showFileCategory(file)"
                                        >
                                            {{ file.category }}
                                            <div
                                                :class="[
                                                    'icon',
                                                    'iconfont',
                                                    'icon-xiala',
                                                    file.categoryShow
                                                        ? 'icon_rotate'
                                                        : '',
                                                ]"
                                            ></div>
                                        </div>
                                        <div
                                            class="category_list"
                                            v-show="file.categoryShow"
                                        >
                                            <div
                                                :class="[
                                                    'category_item',
                                                    file.category == cate.value
                                                        ? 'select_category_item'
                                                        : '',
                                                ]"
                                                v-for="(
                                                    cate, index
                                                ) in sketchCatecoryList"
                                                :key="index"
                                                @click="
                                                    selectFileCategory(
                                                        file,
                                                        cate
                                                    )
                                                "
                                            >
                                                {{ cate.label }}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div
                                    class="delete_like_file_block"
                                    @click.stop="deleteFile(file)"
                                >
                                    <span
                                        class="icon iconfont icon-shanchu"
                                    ></span>
                                </div>
                            </div>
                            <div
                                class="pin_block"
                                v-show="file?.status === 'done'"
                            >
                                <a-checkbox v-model:checked="file.pin"
                                    >{{ $t('SketchboardUpload.PIN') }}</a-checkbox
                                >
                            </div>
                        </div>
                        <div
                            class="upload_file_item upload_component"
                            v-show="sketchboardList.length < 8"
                        >
                            <a-upload
                                :action="uploadUrl + '/api/element/upload'"
                                list-type="picture-card"
                                :data="{
                                    ...upload,
                                }"
                                :before-upload="beforeUpload"
                                :headers="{ Authorization: token }"
                                v-model:file-list="fileList"
                                multiple
                                :maxCount="8 - sketchboardList.length+fileList.length"
                                accept=".jpg,.png,.jpeg,.bmp"
                                @change="(file) => fileUploadChange(file)"
                            >
								<div
                                    class="upload_tip_block"
									v-show="sketchboardList.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="Sketchboard"
                @confirmSelect="confirmSelect"
				:disignTypeList="sketchCatecoryList"
            ></Material>
            <Generate
                v-show="openClick == 3"
                ref="Generate"
                msg="Sketchboard"
				:sketchCatecoryList="sketchCatecoryList"
                @generateCheckbox="getgenerateCheckbox"
            ></Generate>
        </div>
		<div class="modal_right">
			<div class="modal_layout">
				<div class="modal_text">
					<div>{{ $t('SketchboardUpload.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 sketchboardList" :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 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('SketchboardUpload.inputContent1')" v-model="captionGeneration">
					<div class="generage_btn started_btn" @click.stop="getgenerate">Generate</div>
					<span>{{ $t('SketchboardUpload.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="generageAdd(item)">
						<div class="operate_file_block">
							<div class="select_img_type">
								<div
									class="select_category"
									@click.stop="showFileCategory(item)"
								>
									{{ item.category }}
									<div
										:class="[
											'icon',
											'iconfont',
											'icon-xiala',
											item.categoryShow
												? 'icon_rotate'
												: '',
										]"
									></div>
									
								</div>
								<div
									class="category_list"
									v-show="item.categoryShow"
								>
									<div
										:class="[
											'category_item',
											item.category == cate.value
												? 'select_category_item'
												: '',
										]"
										v-for="(
											cate, index
										) in sketchCatecoryList"
										:key="index"
										@click.stop="
											selectFileCategory(
												item,
												cate
											)
										"
									>
										{{ cate.label }}
									</div>
								</div>
							</div>
						</div>
						<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('SketchboardUpload.PIN') }}</a-checkbox>
						</div>
					</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 } from "vue";
import { LoadingOutlined } from "@ant-design/icons-vue";
import { getCookie } from "@/tool/cookie";
import { getUploadUrl } from "@/tool/util";
import GO from "@/tool/GO";
import { useStore } from "vuex";
import { message, Upload } from "ant-design-vue";
import Material from "@/component/HomePage/Material.vue";
import Generate from "@/component/HomePage/Generate.vue";
import { Https } from "@/tool/https";
import { useI18n } from "vue-i18n";
export default defineComponent({
    components: { Material, Generate },
    setup() {
        let fileList: any = ref([]);
        let openClick: any = ref(1);
		let generateList:any = ref([
	
		])
		let generateCheckbox:any = ref()
		let loadingShow = ref(false)
			
		let sketchCatecoryList:any = ref({})
		let workspace:any = ref({})
		let inputShow = ref(false)
		let inputTime = ref()
		
		let {t} = useI18n()
        return {
            fileList,
            openClick,
			generateList,
			generateCheckbox,
			loadingShow,
			sketchCatecoryList,
			workspace,
			inputShow,
			inputTime,
			t,
        };
    },
    data() {
        return {
            swtich_type: "upload",
            indicator: h(LoadingOutlined, {
                style: {
                    fontSize: "2.4rem",
                },
                spin: true,
            }),
            upload: {
                isPin: 0,
                level1Type: "Sketchboard",
                timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
            },
            token: "",
            uploadUrl: "",
            store: useStore(),
			captionGeneration:'',
			sketchboardList:computed(()=>{
				return  useStore().state.UploadFilesModule.sketchboard
			}),
			workspaceCom:{}
        };
    },
    computed: {
        getSketchLabel(value) {
            return (value: any) => {
                let lable = "";
                for (let item of this.sketchCatecoryList) {
                    if (item.value === value) {
                        lable = item.label;
                        break;
                    }
                }
                return lable;
            };
        },
    },
	watch:{
		workspaceCom(newVal,oldVal){
			this.workspace = newVal
			this.getPosition()
		},
	},
    mounted() {
        this.token = getCookie("token") || "";
        this.uploadUrl = getUploadUrl();
		this.workspaceCom = computed(()=>{
			return  this.store?.state?.Workspace?.workspace
		})
    },
    methods: {
        open(num: Number) {
            this.openClick = num;
            if (num == 2) {
                let material: any = this.$refs.Material;
                material.init("Sketchboard");
            } else if (num == 3) {
                // let Generate:any = this.$refs.Generate
                // Generate.init('generate')
            }
        },
		getPosition(){
			let params
			if(this.workspace.sex == 'Female'){
				params = 'FemalePosition'
			}else{
				params = 'MalePosition'
			}
			Https.axiosGet(Https.httpUrls.workspaceenumValues,{params:{enumName:params}}).then((rv: any) => {
				if (rv) {
					let arr:any = []
					rv.forEach((item:any) => {
						let obj = {
							value:item.name,
							label:item.name,
						}
						arr.push(obj)						
					});
					this.sketchCatecoryList = arr
				}
			})
		},
		getgenerateCheckbox(value:any){
			this.generateCheckbox = value
		},
        fileUploadChange(data: any) {
            let file = data.file;
            if (file.status === "done") {
				let res = JSON.parse(file.xhr.response);
                file.imgUrl = res.data.url;
                file.resData = res.data;
                file.pin = false;
                file.category = this.sketchCatecoryList?.[0]?.value;
                file.categoryShow = false;
				file.id_ = GO.id++
				file.type_ = {
					type1:'upload',
					type2:'Sketchboard'
				};
                let fileList = this.fileList.filter(
                    (v: any) => v.status === "done"
                );
                this.store.commit("setSketchboardFile", fileList);
            } else if (file.status === "error") {
                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('SketchboardUpload.jsContent1'));

            }
        },

        beforeUpload(file: 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('SketchboardUpload.jsContent2'));
            }
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isLt2M) {
                message.warning(this.t('SketchboardUpload.jsContent3'));
            }
            return (isJpgOrPng && isLt2M) || Upload.LIST_IGNORE;
        },

        showFileCategory(file: any) {
            file.categoryShow = true;
            document.addEventListener("click", this.hiddenFileCategory);
        },

        selectFileCategory(file: any, cate: any) {
			
			if(this.openClick == 3){
				for (let item of this.generateList) {
					item.categoryShow = false;
				}
				file.category = cate.value;
				// this.store.commit("sketchGenerateFiles", this.fileList);
			}else{
				for (let item of this.fileList) {
					item.categoryShow = false;
				}
				file.category = cate.value;
				this.store.commit("setSketchboardFile", this.fileList);
			}
        },
        hiddenFileCategory() {
			if(this.openClick == 3){
				for (let item of this.generateList) {
					item.categoryShow = false;
				}
			}else{
				for (let item of this.fileList) {
					item.categoryShow = false;
				}
			}
           
            document.removeEventListener("click", this.hiddenFileCategory);
        },

		ifMaximumLength(){
			clearTimeout(this.inputTime)
			let inputBox = document.getElementsByClassName('sketchboard_upload_modal')[0].getElementsByClassName('input_box')[0]
			let input = inputBox.getElementsByClassName('search_input')[0]
			this.inputTime = setTimeout(()=>{
				// let num1 = ((input as HTMLInputElement).value.match(/ /g) || []).length
				// let num2 = (input as HTMLInputElement).value.split(' ').length
				if(this.captionGeneration.split(/\s+/).length > 75){
					this.inputShow = true
				}else{
					this.inputShow = false
				}
			},500)
		},

        deleteFile(item: any) {
			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.sketchboardFiles
				let moodboard 
				this.store.state.UploadFilesModule.sketchboardFiles.forEach((items:any,index:Number)=>{
					if(items.id_ == item.id_){
						moodboard = index
						
					}
				})
				this.fileList.splice(moodboard,1)
				this.store.commit("setSketchboardFile", this.fileList);
			}
        },
		likeFile(item:any,str:string){
			if(str == 'like'){
				let data = {
					generateDetailId:item.id,
					level1Type:"Sketchboard",
					level2Type: item.category,
					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.axiosPost(Https.httpUrls.generateLike, data).then(
					(rv) => {
						item.like = false
					}
				).catch(res=>{
				});
			}
		},
        recollection() {
            let arr = JSON.parse(
                JSON.stringify(
                    this.store.state.UploadFilesModule.allBoardData
                        .sketchboardFiles
                )
            );
			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("setSketchboardGenerateFiles", setboard.generate);
			this.store.commit("setSketchboardMaterialFiles", setboard.material);
			this.store.commit("setSketchboardFile", setboard.moodboard);
			this.fileList = setboard.moodboard
        },
        confirmSelect(event: any) {
            for (let item of event) {
                let data = {
                    imgUrl: item.url,
                    resData: item,
                    pin: false,
                    status: "done",
                    category: item.level2Type || "Outwear",
                    categoryShow: false,
                };
                if (this.fileList.length == 15) {
                    message.warning(
                        this.t('SketchboardUpload.jsContent4')
                    );
                    break;
                }
                this.fileList.push(data);
            }
            this.store.commit("setSketchboardFile", this.fileList);
        },
		//发送请求生成图片
		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:generage.level2Type,
				text:this.captionGeneration,
				timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,
				version:1,//为1就是Print
				gender:this.workspace.sex,
			}
			if(generateType == 'image'||generateType == 'text-image'){
				if(generage?.collectionElementid){
				}else{
					message.warning(
						this.t('SketchboardUpload.jsContent5')
					);
					return
				}
			}else if(generateType == 'text'){
				// this.beforeUpload(false)
				data.collectionElementId = ''
				data.level2Type = ''
				if(this.captionGeneration){
					let arr = this.captionGeneration.split(/\s+/).length
					if(arr > 75){
						message.warning(
						this.t('SketchboardUpload.jsContent6')
						);
						return
					}
				}else{
					message.warning(
						this.t('SketchboardUpload.jsContent7')
						
					);
					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,
								category:generage.level2Type,
								id_:GO.id++
							}
						this.generateList.push(arr)
						this.loadingShow = false
						})
					}
                }
            ).catch(res=>{
				this.loadingShow = false
            });
		},
		generageAdd(item:any){
			item.type_ = {
                type1: "generate",
                type2: 'Sketchboard',
            },
			item.resData = JSON.parse(JSON.stringify(item))
			item.jsContent1 = this.t('uploadFile.jsContent1')
            this.store.commit("addGenerateMaterialFils", item);
		}
    },
});
</script>
<style lang="less" scoped>
.sketchboard_upload_modal {
	height: 100%;
    display: flex;
	.modal_left {
        padding-top: 4rem;
        width: 47%;
		display: flex;
		flex-direction: column;
		.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;
                }
            }
        }
		.sketchboard_body {
        // height: calc(100% - 5rem);
		flex: 1;
        padding-top: 2.5rem;
        height: 30rem;
        overflow-x: hidden;
        border-right: 1px solid #e5e5e5;
        &.moodboard_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 4rem 0;
			// margin: 0 2rem 2rem 0;
			display: inline-block;
			width: 10rem;
			height: 10rem;
			border: 1px solid #f5f5f5;
			vertical-align: top;
			position: relative;
			img{
				width: 100%;
				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%;
                    max-width: 100%;
                }
				&: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;
					text-align: center;
					cursor: pointer;
					img{
						// width: 100%;
						width: auto;
						height: 100%;
						object-fit: contain;
					}
					.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{
				z-index: 1;
				input{
					&.forbidden{
						cursor:not-allowed;
					}
				}
			}
			.modal_img{
				flex: 1;
				display: flex;
				flex-wrap: wrap;
				justify-content: flex-start;
				align-content: flex-start;
				position: relative;
				.mark_loading{
					position: absolute;
					width: 100%;
					height: 100%;
					z-index: 99;
				}
				.modal_imgItem{
					margin: 0 2rem 4rem 0;
					display: inline-block;
					width: 10rem;
					height: 10rem;
					border: 1px solid #f5f5f5;
					position: relative;
					cursor: pointer;
					&:hover .delete_like_file_block{
						display: block;
					}
					img{
						object-fit: cover;
						width: 100%;
						height: 100%;
					}
					&.active{
						opacity: 0.5;
					// border: 2px solid;
						border-radius: 1rem;
						transform: scale(0.9);
						// img {
						// }
						.operate_file_block{
							pointer-events:none
						}
						.pin_block{
							pointer-events:none
						}
						.delete_like_file_block{
							pointer-events:none
						}
					}
					
				}
			}
		}
	}
}
</style>
