<template>
    <div class="generate">
        <div v-if="type_.type2 == 'Sketchboard'|| type_.type2 == 'Printboard'"  class="generate_checkbox">
            <div>
                <label>
                    <input
                        type="checkbox"
                        v-model="checkbox[0].type"
                        @click="setKeyword(0)"
                    />
                    <span>{{ $t('Generate.ImageOnly') }}</span>
                </label>
            </div>
            <div>
                <label>
                    <input
                        type="checkbox"
                        v-model="checkbox[1].type"
                        @click="setKeyword(1)"
                    />
                    <span>{{ $t('Generate.TextOnly') }}</span>
                </label>
            </div>
            <div>
                <label>
                    <input
                        type="checkbox"
                        v-model="checkbox[2].type"
                        @click="setKeyword(2)"
                    />
                    <span>{{ $t('Generate.TextImage') }}</span>
                </label>
            </div>
			<div v-if="type_.type2 == 'Printboard'" class="printModel">
				<div @click.stop="PrintModel">{{ printModel.name }}</div>
				<ul v-show="printModel.optype">
					<li class="printModel_item" @click="setprintModel(1)">{{ $t('Generate.Model1') }}</li>
					<li class="printModel_item" @click="setprintModel(2)">{{ $t('Generate.Model2') }}</li>
				</ul>
			</div>
        </div>
        <div v-else class="input_box" :class="{active:inputShow}">
            <input
                class="search_input"
				@input="ifMaximumLength"
                :placeholder="$t('Generate.inputContent1')"
				:maxlength='inputShow?0:9999'
                v-model="searchPictureName"
                @keydown.enter="getgenerate()"
            />
            <div class="generage_btn started_btn" @click.stop="getgenerate">{{ $t('Generate.Generate') }}</div>
			<span>{{ $t('Generate.maximumLength') }}</span>

        </div>
        <div v-if="type_.type2 == 'Sketchboard' || type_.type2 == 'Printboard'" class="generage_img">
            <div class="upload_item">
                <div
                    class="upload_file_item"
                    v-for="(file, index) in sketchboardList"
                    :key="file"
					@click.stop="setSketchboardItem(file)"
					:class="[file?.checked?'active':'',checkboxImage? 'forbidden':'']"
                >
                    <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 v-if="type_.type2 == 'Sketchboard'" 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.stop="selectFileCategory(file, cate)"
                                    >
                                        {{ cate.label }}
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div
                            class="delete_file_block"
                            @click="deleteFile(index)"
                        >
                            <span class="icon iconfont icon-shanchu"></span>
                        </div>
                    </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,
                        }"
						:disabled="checkbox[1].type"
                        :headers="{ Authorization: token }"
                        v-model:file-list="sketchboardList"
                        :before-upload="beforeUpload"
                        multiple
                        :maxCount="8 - sketchboardList.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 v-else class="generage_img">
            <div
                class="generage_img_item"
                v-for="(item, index) in fileList"
                :key="item.imgUrl"
                @click="generageAdd(item)"
                :class="{ active: item?.checked }"
            >
                <img v-lazy="item.imgUrl" alt="" />
				<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>
			<div class="mark_loading" v-show="loadingShow">
				<a-spin size="large" />
			</div>
        </div>
		
    </div>
</template>
<script lang="ts">
import { LoadingOutlined } from "@ant-design/icons-vue";
import { message, Upload } from "ant-design-vue";
import { defineComponent, computed, h, ref, nextTick } from "vue";
import { Https } from "@/tool/https";
import { useStore } from "vuex";
import GO from "@/tool/GO";
import { getCookie } from "@/tool/cookie";
import { getUploadUrl } from "@/tool/util";
import { forEach } from "jszip";
import { useI18n } from "vue-i18n";
export default defineComponent({
    props: ["msg",'sketchCatecoryList'],
    setup() {
        // console.log(prop.msg);
        let checkbox = ref([
            {
                name: "image",
                type: false,
            },
            {
                name: "text",
                type: true,
            },
            {
                name: "text-image",
                type: false,
            },
        ]);
		let checkboxImage = ref()
        let imgList = ref([]);
        let selectImgList: any = ref([]);
        let selectImgListIds: any = ref([]);
        let isShowLoading: any = ref(false);
        let selectCode: any = ref("");
        let currentPage: any = ref(1);
        let searchPictureName = ref("");
        let pageSize = ref(20);
        let total = ref(0);
        let searcMaterialhName: any = ref(""); //搜索名字
        let designType: any = ref(null);
        let store = useStore();
        let fileList: any = ref([
          
        ]);
		let sketchboardList:any = ref([])
		let collectionElementid = ref()
		let level2Type = ref('')
		let printModel = ref({
			num:1,
			optype:false,
			name:'model1'
		})
		// let sketchCatecoryList:any = ref([])
		let workspace:any = ref({})

		let loadingShow = ref(false)
		let inputShow = ref(false)
		let inputTime = ref()

		let {t} = useI18n()
        return {
            imgList,
            selectImgList,
            selectImgListIds,
            isShowLoading,
            selectCode,
            currentPage,
            searchPictureName,
            pageSize,
            total,
            searcMaterialhName,
            designType,
            checkbox,
            store,
            fileList,
			sketchboardList,
			collectionElementid,
			level2Type,
			checkboxImage,
			printModel,
			loadingShow,
			// sketchCatecoryList,
			workspace,
			inputShow,
			inputTime,
			t,
        };
    },
    data(prop) {
        return {
            indicator: h(LoadingOutlined, {
                style: {
                    fontSize: "2.4rem",
                },
                spin: true,
            }),
            upload: {
                isPin: 0,
                level1Type: prop.msg,
                timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
            },
            token: "",
            uploadUrl: "",
            moodboarList: computed(() => {
                return useStore().state.UploadFilesModule.moodboard;
            }),
            type_: {
                type1: "generate",
                type2: prop.msg,
            },
        };
    },
    mounted() {
        // this.fileList.forEach((item,index)=>{
        // 	item.checked = true
        // 	item.type_ = 'generate'
        // 	item.id_ = GO.id++
        // })
        // this.store.commit("addGenerateFils", this.fileList);
        this.token = getCookie("token") || "";
        this.uploadUrl = getUploadUrl();
		this.workspace = this.store.state.Workspace.workspace
    },
    computed: {
        getSketchLabel(value: any) {
            return (value: any) => {
                let lable = "";
                for (let item of this.sketchCatecoryList) {
                    if (item.value === value) {
                        lable = item.label;
                        break;
                    }
                }
                return lable;
            };
        },
    },
    methods: {
        generageAdd(data: any) {
            data.type_ = this.type_;
			data.resData = JSON.parse(JSON.stringify(data))
			data.jsContent1 = this.t('uploadFile.jsContent1')
            this.store.commit("addGenerateMaterialFils", data);
        },
		
        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('Generate.jsContent1'));
            }
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isLt2M) {
                message.warning(this.t('Generate.jsContent2'));
            }
            return (isJpgOrPng && isLt2M) || Upload.LIST_IGNORE;
        },
        setKeyword(num: any) {
            this.checkbox.forEach((v: any) => {
                v.type = false;
            });
			
			nextTick().then(()=>{
				this.checkbox[num].type = true
				this.$emit('generateCheckbox',this.checkbox[0].type)
				this.checkboxImage = this.checkbox[1].type
				if(this.checkboxImage){
					this.sketchboardList.forEach((v:any)=>{
						v.checked = false
					})
				}
			})
        },
		PrintModel(){
			if(!this.printModel.optype){
				document.addEventListener('click',this.removePrintModel)
			}
			this.printModel.optype = !this.printModel.optype
		},
		removePrintModel(){
			this.printModel.optype = false
			document.removeEventListener('click',this.removePrintModel)
		},
		setprintModel(num:any){
			this.printModel = {
				num : num,
				optype:false,
				name:'model'+num
			}
		},
		getgenerate(){
			if(!this.searchPictureName){
				message.warning(
					this.t('Generate.jsContent3')
					);
				return
			}
			if(this.searchPictureName){
				let arr = this.searchPictureName.split(/\s+/).length
				if(arr > 75){
					message.warning(
					this.t('Generate.jsContent4')
					);
					return
				}
			}else{
				message.warning(
					this.t('Generate.jsContent5')
				);
				return
			}
			let data = {
				generateType:'text',
				designType:'',
				collectionElementId:'',
				level1Type:this.upload.level1Type,
				level2Type:'',
				text:this.searchPictureName,
				timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,
				version:1,//为1就是Print
				gender:'',
			}
			this.loadingShow = true
			Https.axiosPost(Https.httpUrls.sketchAndPrintGenerate, data).then(
                (rv) => {
					if(rv){
						this.fileList = []
						let arr
						rv.generatedCollectionItems.forEach((v:any,index:number)=>{
							arr = {
								id:rv.generatedCollectionItems[index].generateItemId,
								imgUrl:rv.generatedCollectionItems[index].generateItemUrl
							}
						this.fileList.push(arr)
						this.loadingShow = false
									
						})
					}
                }
            ).catch(res=>{
				this.loadingShow = false
            });
		},
		ifMaximumLength(){
			clearTimeout(this.inputTime)
			let inputBox = document.getElementsByClassName('generate')[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.searchPictureName.split(/\s+/).length > 75){
					this.inputShow = true
				}else{
					this.inputShow = false
				}
			},500)
		},
		
        fileUploadChange(data: any) {
            let file = data.file;
            if (file.status === "done") {
                let res = JSON.parse(file.xhr.response);
                file.id = res.data.id;
                file.imgUrl = res.data.url;
                file.resData = res.data;
                file.type_ = "upload";
                file.id_ = GO.id++;
                file.category = this.sketchCatecoryList?.[0]?.value;
                let fileList = this.sketchboardList.filter(
                    (v: any) => v.status === "done"
                );
                let arr = this.store.state.UploadFilesModule.sketchboard;
                if (arr.length >= 8) {
                    message.warning(this.t('Generate.jsContent6'));
                } else {
					this.sketchboardList = fileList
                }
            } else if (file.status === "error") {
                let index = -1;
                this.sketchboardList.forEach((ele: any, index1: any) => {
                    if (file.uid === ele.uid) {
                        index = index1;
                    }
                });
                if (index > -1) {
                    this.sketchboardList.splice(index, 1);
                }
                message.error(file.name + this.t('Generate.jsContent5'));
            }
        },
        showFileCategory(file: any) {
            file.categoryShow = true;
            document.addEventListener("click", this.hiddenFileCategory);
        },
        selectFileCategory(file: any, cate: any) {
            file.category = cate.value;
			file.categoryShow = false
            // this.store.commit("setSketchboardFile", this.sketchboardList);
        },
        hiddenFileCategory() {
            for (let item of this.sketchboardList) {
                item.categoryShow = false;
            }
            document.removeEventListener("click", this.hiddenFileCategory);
        },

		setSketchboardItem(item:any){
			if(this.checkboxImage){
				return
			}
			if(item.checked){
				item.checked = false
			}else{
				this.sketchboardList.forEach((v:any)=>{
					if(v.checked){
						v.checked = false
					}
				})
				item.checked = true
			}
			this.collectionElementid = item.id
			this.level2Type = item.category
		},
        deleteFile(item: any) {
            if (item.type_ == "generate" || item.type_ == "material") {
				item.jsContent1 = this.t('uploadFile.jsContent1')
                this.store.commit("addGenerateMaterialFils", item);
            } else {
                this.sketchboardList =
                    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.sketchboardList.splice(moodboard, 1);
                this.store.commit("setSketchboardFile", this.sketchboardList);
            }
        },
		likeFile(item:any,str:string){
			if(str == 'like'){
				let data = {
					generateDetailId:item.id,
					level1Type:"Moodboard",
					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=>{
				});
			}
			
		},
        closeModal() {
            // this.myMaterialModalShow = false
            this.searchPictureName = "";
            this.designType = null;
            this.selectImgList = [];
            this.selectImgListIds = [];
            this.imgList = [];
            this.currentPage = 1;
            // this.pageSize = 10;
            this.total = 0;
        },
    },
});
</script>
<style lang="less">
.generate {
	flex: 1;
    // height: 30rem;
    // overflow-x: hidden;
	display: flex;
    flex-direction: column;
    border-right: 1px solid #e5e5e5;
    &.generate::-webkit-scrollbar {
        display: none;
    }
	
    .generate_checkbox,
    .generage_input {
        display: flex;
        align-items: center;
        position: sticky;
        top: 0;
        background: #fff;
        padding-top: 2.5rem;
        padding-bottom: 2rem;
        z-index: 2;
    }
    .generate_checkbox {
        div {
            margin-right: 4rem;
            label {
                display: flex;
                cursor: pointer;
                input {
                    margin-right: 0.5rem;
                    padding-left: 1.5rem;
                }
                span {
                    font-size: 1.2rem;
                    font-weight: 500;
                }
            }
        }
    }
	.printModel{
		>div{
			width: 7rem;
			display: flex;
			justify-content: center;
			border-radius: 1rem;
			margin: 0;
			border: 2px solid;
            cursor: pointer;
		}
		ul{
			position: absolute;
			width: 7rem;
			text-align: center;
			margin-top: .3rem;
			border-radius: 1rem;
			overflow: hidden;
			li{
				background: rgba(0,0,0,.2);
				line-height: 2;
				cursor: pointer;
				&.printModel_item:hover{
					background: rgba(0,0,0,.4);
				}
			}
		}
	}
    .generage_input {
    }
    .generage_img {
        display: flex;
		position: relative;
        flex-wrap: wrap;
		align-content: flex-start;
		flex: 1;
		.mark_loading{
			position: absolute;
			width: 100%;
			height: 100%;
			z-index: 99;
		}
        .generage_img_item {
            cursor: pointer;
            margin: 0 2rem 2rem 0;
			position: relative;
            &.active {
					opacity: 0.5;
					// border: 2px solid;
					border-radius: 1rem;
					img {
						transform: scale(0.9);
					}
					.delete_like_file_block{
						pointer-events:none;
					}
				}
            img {
                width: 10rem;
                height: 10rem;
            }
			.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;
				i{
					font-size: 1.6rem;
					color: #fff;
					&.fi-rr-heart{

					}
					&.fi-sr-heart{
						color: red;
					}
				}
			}
			&:hover .delete_like_file_block{
				display: block;
			}
        }
        .upload_item {
            .upload_file_item {
				// &.active {
				// 	opacity: 0.5;
				// 	// border: 2px solid;
				// 	border-radius: 1rem;
				// 	transform: scale(0.9);
				// 	.delete_file_block{
				// 		pointer-events:none;
				// 	}
				// 	.operate_file_block{
				// 		pointer-events:none;
				// 	}
				// 	img {
				// 	}
				// }
				&.forbidden{
					cursor:not-allowed;
					img{
						cursor:not-allowed;
					}
				}
                .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%;
                    }

                    .delete_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;
                        }
                    }

                    &:hover .delete_file_block {
                        display: block;
                    }
                }
            }
        }
    }
}
.my_material_modal {
    border-radius: 2rem;
    .ant-modal-close {
        width: 3.6rem;
        height: 3.6rem;
        position: absolute;
        top: -1.8rem;
        right: -1.8rem;
    }

    .ant-modal-header {
        display: none;
    }

    .ant-modal-body {
        background: #f2f3fb;
        height: 80vh;
        min-height: 72rem;
        overflow-y: hidden;
        padding: 0;
    }

    .my_material_header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;
        height: 6.6rem;
        background: #f7f7f7;
        padding: 0 3.4rem 0 3.1rem;

        .my_material_title {
            font-size: 1.8rem;
            color: #030303;
            font-weight: 500;
        }

        .my_material_header_right {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .content_search_block {
                margin-right: 5rem;
                display: flex;

                .search_input {
                    width: 30rem;
                    padding-left: 1.5rem;
                    height: 4rem;
                    line-height: 3.8rem;
                    background: #ffffff;
                    border: 0.1rem solid #f1f1f1;
                    font-size: 1.6rem;
                    font-weight: 400;

                    &::placeholder {
                        color: #c2c2c2;
                    }
                }

                .search_icon_block {
                    width: 6rem;
                    height: 4rem;
                    line-height: 4rem;
                    text-align: center;
                    background: #343579;
                    cursor: pointer;

                    .icon-sousuo {
                        font-size: 2rem;
                        color: #ffffff;
                    }
                }
            }

            .icon_close {
                color: rgba(174, 178, 183, 1);
                font-size: 2.4rem;
                cursor: pointer;
            }
        }
    }

    .my_material_content {
        padding: 0 3rem 3.5rem 3rem;
        height: calc(100% - 6.6rem);
        position: relative;

        .material_content_top {
            padding: 1.3rem 0 2.1rem;
            height: 7rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-sizing: border-box;

            .material_content_top_title {
                font-size: 2rem;
                color: #030303;
            }

            .material_content_top_right {
                display: flex;
                align-items: center;

                .select_block {
                    background: #ffffff;
                    color: #1a1a1a !important;
                    margin-right: 2.3rem;

                    .icon-xiala {
                        color: #1a1a1a !important;
                    }
                }

                .check_all_block {
                    display: flex;
                    align-items: center;
                    font-size: 1.6rem;
                    color: #64686d;
                    cursor: pointer;

                    &.check_all {
                        color: #1a1a1a;
                    }

                    .check_block {
                        width: 2.4rem;
                        height: 2.4rem;
                        background: #ebecf4;
                        border: 0.1rem solid #64686d;
                        padding: 0.3rem;
                        margin-right: 0.7rem;

                        .check_block_body {
                            width: 100%;
                            height: 100%;
                            background: #343579;
                        }
                    }
                }
            }
        }

        .material_content_body {
            width: 100%;
            height: calc(100% - 19rem);
            overflow-y: auto;
            position: relative;

            .content_img_item {
                display: inline-block;
                vertical-align: top;
                padding: 0 1.4rem;
                margin-bottom: 2.8rem;

                .content_img_item_block {
                    border: 0.1rem solid transparent;
                    width: 16.5rem;
                    height: 16.5rem;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    position: relative;
                    cursor: pointer;

                    &.select_item_img {
                        border-color: #343579;
                    }

                    .print_content_img {
                        width: 100%;
                        height: 100%;
                    }

                    .content_img {
                        max-width: 100%;
                        max-height: 100%;
                    }
                }
                .content_img_name {
                    width: 16.5rem;
                    height: 3.5rem;
                    line-height: 3.5rem;
                    white-space: nowrap;
                    text-align: center;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    font-size: 1.4rem;
                    color: #030303;
                }
            }
        }

        .no_data_block {
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            position: absolute;
            left: 0;
            top: 0;
            z-index: 99;

            &.loading_block {
                background: rgba(0, 0, 0, 0.2);
            }
        }

        .material_confirm {
            width: 9.8rem;
            height: 3.6rem;
            line-height: 3.6rem;
            font-size: 1.4rem;
            text-align: center;
            margin: 0 auto;
            color: #ffffff;
            background: #343579;
            cursor: pointer;
            margin-top: 2rem;
        }

        .table_pagination {
            position: absolute;
            bottom: 3.5rem;
            left: 0;
            width: 100%;
            text-align: center;
            margin-top: 5rem;
        }
    }
}
</style>
