<template>
    <div class="generate">
        <div v-if="(type_.type2 == 'Printboard' && scene.value == 'Pattern')"  class="generate_checkbox" >
			<generalMenu :dataList="printModelList" @setprintModel="setprintModel" :item="printModel" :driver__="driver__.driver" :driverClass="{class1: 'Guide_1_2_4'}"></generalMenu>
			<!-- <generalMenu :dataList="sceneList" @setprintModel="setSceneList" :item="scene"></generalMenu> -->
			<!-- <div v-if="type_.type2 == 'Printboard'" class="printModel">
				<div @click.stop="PrintModel" class="Guide_1_2_4" :class="[driver__.driver?'showEvents':'']">{{ printModel.name }}</div>
				<ul v-show="printModel.optype" class="Guide_1_2_5" :class="[driver__.driver?'showEvents':'']">
					<li class="printModel_item" @click="setprintModel(1)">{{ $t('Generate.Model1') }}</li>
					<li class="printModel_item" @click="setprintModel(2)">{{ $t('Generate.Model2') }}</li>
					<li class="printModel_item" @click="setprintModel(3)">{{ $t('Generate.Model3') }}</li>
				</ul>
			</div> -->
        </div>
        <div class="input_border" >
			<div class="input_box  Guide_1_5" :class="[inputShow?'active':'',type_.type2 =='Sketchboard'?'Guide_1_9_2':'',driver__.driver?'showEvents':'']">
				<div class="input_box_btnBox" v-if="scene?.value != 'extract'">
					<div class="upload_item" v-show="sketchboardList?.length != 0">
						<div
							class="upload_file_item Guide_1_2_7"
							v-for="(file, index) in sketchboardList"
							:key="file"
							:class="[driver__.driver?'showEvents':'']"
						>
							<div
								class="upload_file_item_content"
								v-show="file?.status === 'uploading'"
							>
								<a-spin size="small" :indicator="indicator" tip="Uploading..." />
							</div>
							<div
								class="upload_file_item_content"
								v-show="file?.status === 'done' || file?.base64"
							>
								<img :src="file?.imgUrl" class="upload_img" />
								<div class="delete_like_file_block"  :class="[driver__.driver?'hideEvents':'']">
									<span class="icon iconfont icon-shanchu operate_icon" @click.stop="deleteFile(index)"></span>
								</div>
							</div>
						</div>
					</div>
					<input
						class="search_input"
						@input="ifMaximumLength"
						:placeholder="(scene?.value == 'Slogan' && type_.type2 == 'Printboard')?isSloganHint:$t('Generate.inputContent1')"
						:maxlength='inputShow?0:9999'
						v-model="searchPictureName"
						@keydown.enter="getgenerate()"
						@click="inputFocus()"
						@paste="onPaste"
					/>
					<i class="fi fi-br-upload" :class="{ Guide_1_2_6:type_.type2 == 'Printboard'}" :title="$t('Generate.uploadTitle')" v-show="!isTextarea && upload.level1Type !== 'Moodboard' && scene?.value != 'Slogan' && scene?.value != 'Logo'">
						<a-upload
							class="search_upImg"
							:capture="null"
							:action="uploadUrl + '/api/element/upload'"
							list-type="picture-card"
							:data="{
								...upload,
							}"
							:maxCount='1'
							:headers="{ Authorization: token }"
							v-model:file-list="sketchboardList"
							:before-upload="beforeUpload"
							accept=".jpg,.png,.jpeg,.bmp"
							@change="(file) => fileUploadChange(file)"
						>
						</a-upload>
					</i>
					<i v-show="scene?.value == 'Slogan'" :title="$t('Generate.sloganTitle')" @click.stop="setSlogan" class="fi fi-rr-poll-h"></i>
					<i v-show="!isTextarea" class="fi fi-br-expand" @click.stop="setTextareaShow"></i>
					<i v-show="isTextarea" class="fi fi-bs-compress" @click.stop="setTextareaShow"></i>
				</div>
				<div class="input_box_btnBox sketch" v-else>
					<div class="upload_item"  v-show="sketchboardList.length > 0">
						<div
							class="upload_file_item"
							v-for="(file, index) in sketchboardList"
							:key="file"
							:class="[driver__.driver?'showEvents':'']"
						>
							<div
								class="upload_file_item_content"
								v-show="file?.status === 'uploading'"
							>
								<a-spin size="small" :indicator="indicator" tip="Uploading..." />
							</div>
							<div
								class="upload_file_item_content"
								v-show="file?.status === 'done' || file?.base64"
							>
								<img :src="file?.imgUrl" class="upload_img" />
								<div class="delete_like_file_block"  :class="[driver__.driver?'hideEvents':'']">
									<span class="icon iconfont icon-shanchu operate_icon" @click.stop="deleteFile(index)"></span>
								</div>
							</div>
						</div>
					</div>
					<i class="fi fi-br-upload" style="margin-left: 2rem;"  v-show="sketchboardList.length == 0" :title="$t('Generate.uploadproduct')">
						<a-upload
							class="search_upImg"
							:capture="null"
							:action="uploadUrl + '/api/element/upload'"
							list-type="picture-card"
							:data="{
								...upload,
							}"
							:maxCount='1'
							:headers="{ Authorization: token }"
							v-model:file-list="sketchboardList"
							:before-upload="beforeUpload"
							accept=".jpg,.png,.jpeg,.bmp"
							@change="(file) => fileUploadChange(file)"
						>
						</a-upload>
					</i>
					<div :title="$t('Generate.style')">
						<generalMenu :dataList="printModelList" :isCanvas="type_.type2 == 'Sketchboard'" @setprintModel="setprintModel" :item="printModel"></generalMenu>
					</div>
				</div>
				<textarea 
					v-show="isTextarea"
					class="search_textarea "  
					@input="ifMaximumLength" 
					:maxlength='inputShow?0:9999' 
					@keydown.enter="getgenerate()"
					@click.stop=""
					v-model="searchPictureName"
				></textarea>
				<div class="generage_btn_box" v-show="!isGenerate">
					<div class="generage_btn started_btn">
						<div :class="{Guide_1_2_8:type_.type2 == 'Printboard'}" @click.stop="getgenerate">
							<span 
								v-if="
								type_.type2 == 'Moodboard' || 
								(type_.type2 == 'Printboard' && scene?.value == 'Pattern') || 
								(type_.type2 == 'Sketchboard' && scene?.value == 'generate')"
								>
								{{ speedData.label }}
							</span>
							<span v-else>{{ $t('Generate.Generate') }}</span>
						</div>
						<div class="icon iconfont icon-xiala" v-show="
							type_.type2 == 'Moodboard' || 
							(type_.type2 == 'Printboard' && scene?.value == 'Pattern') || 
							(type_.type2 == 'Sketchboard' && scene?.value == 'generate')" :class="{active:speedState}" @click.stop="openSpeed"></div>
					</div>
					<div class="content" v-show="speedState">
						<div v-for="item in speedList" :key="item.value" @click="setSpeed(item)" :title="item.title">{{ item.label }}</div>
					</div>
				</div>
				<div v-show="isGenerate && !remGenerate" class="generage_btn started_btn" :class="{Guide_1_2_8:type_.type2 == 'Printboard'}" @click="getgenerate">
					<i class="fi fi-br-loading"></i>
				</div>
				<div v-show="remGenerate" @click="removeGenerate" class="generage_btn started_btn" :class="{Guide_1_2_8:type_.type2 == 'Printboard'}">
					{{$t('Generate.Close')}}
				</div>
				<span class="inputShowText" ref="inputShowText"></span>
			</div>
            <div class="search_keyword" v-if="workspace?.allKeywordsByStyle" v-show="isInputFocus" @click.stop="">
				<div class="search_keyword_center" >
					<div class="search_keyword_center_left">
						<div v-if="type_.type2 == 'Printboard'" v-for="item in styleRecommend" @click.stop="cliSetKeyword(item)" class="search_keyword_center_item"> {{item}} </div>
						<div v-for="item in workspace?.allKeywordsByStyle?.[type_.type2]" @click.stop="cliSetKeyword(item)" class="search_keyword_center_item"> {{item}} </div>
					</div>
				</div>
			</div>
        </div>
        <div class="generage_img Guide_1_6" :class="{Guide_1_13_2:type_.type2 == 'Sketchboard',Guide_1_2_9:type_.type2 == 'Printboard',showEvents : driver__.driver}" :style="[isGenerate?'overflow:hidden':'']">
            <div
                class="generage_img_item"
                v-for="(item, index) in fileList"
                :key="item.imgUrl"
                @click="generageAdd(item)"
                :class="[item.status != 'Success'?'hideEvents':'',item?.checked?'active':'']"
            >
				<img v-lazy="item.imgUrl" @click.stop="generageAdd(item)">
				<sketchCategory v-if="type_.type2 == 'Sketchboard' || type_.type2 == 'Printboard'" :isSpread="type_.type2 == 'Printboard'" :disignTypeList="sketchCatecoryList" :generateList="fileList" :item="item" :driver__="driver__.driver" :driverClass="{'class1': type_.type2 == 'Sketchboard'?'Guide_1_13':'','class2':type_.type2 == 'Sketchboard'?'Guide_1_13_1':''}"></sketchCategory>
				<div
					class="delete_like_file_block left1"
					:class="[driver__.driver?'hideEvents':'',]"
				>
					<i v-if="!item.like" class="fi fi-rr-heart" @click.stop="likeFile(item,'like')"></i>
					<i v-else class="fi fi-sr-heart" :adminLike="!!item.like" @click.stop="likeFile(item,'noLike')"></i>
				</div>
				<div class="delete_like_file_block left"  :class="[driver__.driver?'hideEvents':'']">
					<i class="fi fi-bs-expand-arrows-alt" @click.stop="scaleImage(index)"></i>
				</div>
				<div class="delete_like_file_block" :title="t('LibraryPage.Delete')" @click.stop="deleteGenerate(index)">
					<span class="icon iconfont icon-shanchu operate_icon"></span>
				</div>
            </div>
			<div class="mark_loading" v-show="loadingShow">
				<a-spin size="large" />
			</div>
        </div>
		<scaleImage ref="scaleImage" :isCanvas="type_.type2 == 'Sketchboard'" :workspace="workspace"></scaleImage>
		<createSlogan ref="createSlogan" @setSloganData="setSloganData"></createSlogan>
		<UpgradePlan ref="UpgradePlan"></UpgradePlan>
    </div>
</template>
<script lang="ts">
import { LoadingOutlined } from "@ant-design/icons-vue";
import { message, Upload, Modal } from "ant-design-vue";
import { defineComponent, computed, reactive, createVNode, h, ref,watch, nextTick, inject, toRefs } 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 scaleImage from "@/component/HomePage/scaleImage.vue";
import generalMenu from "@/component/HomePage/generalMenu.vue";
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { openGuide,driverObj__,driverIndex__ } from "@/tool/guide";
import createSlogan from "@/component/HomePage/createSlogan.vue";
import { useI18n } from "vue-i18n";
import sketchCategory from "@/component/HomePage/sketchCategory.vue";
import UpgradePlan from "@/component/HomePage/UpgradePlan.vue";

export default defineComponent({
	components: {
		scaleImage,	
		generalMenu,
		createSlogan,
		sketchCategory,
		UpgradePlan,
	},
    props: ["msg",'sketchCatecoryList','scene'],
    setup(props) {
        // console.log(prop.msg);
        let userDetail:any= computed(()=>{
			return store.state.UserHabit.userDetail
		})
		let printModelList:any = ref([])
		let sketchStyleList:any = ref([])
		let printModel:any = ref({
			num:'',
			id:'',
			optype:false,
			value:'Painting Style',
			label:useI18n().t('Generate.Model1')
		})
        let searchPictureName = ref("");
        let searchPictureSeed:any = ref(0);
        let store = useStore();
        let fileList: any = ref([
          
        ]);
		let sketchboardList:any = ref([])
		let level2Type = ref('')
		// let printBoards:any = computed(()=>{return store.state.UploadFilesModule.printboard})
		// let moodboarList:any = computed(()=>{return store.state.UploadFilesModule.moodboard})
		// let sketchCatecoryList:any = ref([])
		let workspace:any = ref({})
		let isGenerate = ref(false)//判断是否正在进行generate
		let inputShow = ref(false)//表示是否出现红框
		let inputTime = ref()
		let driver__:any = inject('driver__')
		let {t} = useI18n()
		let isTest = ref()
		let generateTime:any = ref()
		let generateProceedList:any = ref([])
		let remGenerate:any = ref(false)
		let remGenerateTime:any = ref()
		let styleRecommend:any = inject('styleRecommend')
		let generateLevel2Type = ''
		let isSloganHint:any = ref(' ')
		let loadingShow =ref(false)
		let speed = reactive({
			speedList:[
				{
					title:'Picture quality is average, speed is fast',
					label:'Low Quality',
					value:'fast',

				},{
					title:'Picture quality is high, speed is slow',
					label:'High Quality',
					value:'high',
				},
			],
			speedState:false,
			speedData:{
				title:'Picture quality is average, speed is fast',
				label:'Low Quality',
				value:'fast',
			},
		})
		const openSpeed = ()=>{
			speed.speedState = !speed.speedState
			if(speed.speedState){
				document.addEventListener('click',openSpeed)
			}else{
				document.removeEventListener('click',openSpeed)
			}
		}
		const setSpeed = (item:any)=>{
			speed.speedData = item
		}
        return {
			userDetail,
            searchPictureName,
			searchPictureSeed,
            store,
            fileList,
			sketchboardList,
			level2Type,
			printModel,
			printModelList,
			sketchStyleList,
			isGenerate,

			// printBoards,
			// moodboarList,
			// sketchCatecoryList,
			workspace,
			inputShow,
			inputTime,
			driver__,
			t,
			isTest,
			generateTime,
			generateProceedList,
			remGenerate,
			remGenerateTime,
			styleRecommend,
			generateLevel2Type,
			isSloganHint,
			loadingShow,
			...toRefs(speed),
			openSpeed,
			setSpeed,
        };
    },
    data(prop) {
        return {
            indicator: h(LoadingOutlined, {
                style: {
                    fontSize: "2.4rem",
                },
                spin: true,
            }),
            upload: {
                isPin: 0,
				gender:'',
                level1Type: prop.msg,
                timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
            },
            token: "",
            uploadUrl: "",
           
            type_: {
                type1: "generate",
                type2: prop.msg,
            },
			workspaceCom:{},
			isTextarea:false,
			isInputFocus:false,
        };
    },
	
    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") || "";
		let isTest:any = getCookie('isTest')
        this.isTest =JSON.parse(isTest)
        this.uploadUrl = getUploadUrl();
		this.workspaceCom = computed(()=>{
			return  this.store?.state?.Workspace?.workspace
		})
		// if()
		if(this.type_.type2 == 'Printboard'){
			this.printModelList = [
				{
					num:1,
					optype:false,
					value:'Painting Style',
					label:useI18n().t('Generate.Model1')
				},{
					num:2,
					optype:false,
					value:'Illustration Style',
					label:useI18n().t('Generate.Model2')
				},{
					num:3,
					optype:false,
					value:'Real Style',
					label:useI18n().t('Generate.Model3')
				},
			]
		}else if(this.type_.type2 == 'Sketchboard'){
			this.printModelList = JSON.parse(JSON.stringify(this.store.state.UserHabit.SketchStyle))
			let imgList = ['/image/sketch/sketch-thick.jpg','/image/sketch/sketch-medium.jpg','/image/sketch/sketch-fine.jpg']
			this.printModelList.forEach((item:any,index:number)=>{
				item.img = imgList[index]
			})
			if(this.printModelList[3])this.printModelList[3].img = -1

		}
		this.printModel = this.printModelList[0]
		
		
    },
	watch:{
		driver__:{
			handler(newVal,oldVal){
				if(this.type_.type2 == 'Printboard'){
					if(newVal.index >= 14 && newVal.index < 15){
					}else{
					}
				}else if(this.type_.type2 == 'Sketchboard'){
					
				}
				
			}
		},
		workspaceCom(newVal,oldVal){
			this.workspace = newVal
			this.upload.gender = newVal?.sexEnum?.value
		},
		scene:{
			handler(newVal,oldVal){
				if(this.type_.type2 == 'Printboard' && newVal.value == 'Slogan'){
					let sloganType = ['Blue and Yellow Starry Night','Green Cthulhu','Red and yellow fire style','Cyberpunk style','City skyline buildings','Red maple leaves','Golden Sunflower','Emerald Jungle Canopy','Pink Sakura Blossom']
					var randomNumber = Math.floor(Math.random() * sloganType.length);
					this.isSloganHint = sloganType[randomNumber]
				}else{
					this.isSloganHint = ''
				}
			}
		}
		// moodboarList(newVal,oldVal){
		// 	if(newVal.length>=1 || this.sketchboardList.length >= 2){
		// 	}else{
		// 		this.printModel = {
		// 			num:'',
		// 			optype:false,
		// 			value:'Painting Style',
		// 			name:this.t('Generate.Model'+1)
		// 		}
		// 	}
		// },
	},
    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.type_.type1 = data.designType?data.designType:this.type_.type1
			data.resData = JSON.parse(JSON.stringify(data))
			let maxImg = 8
			if(this.type_.type2 == 'Sketchboard'){
				maxImg = 20
			}
			data.jsContent1 = this.t('uploadFile.jsContent1',{maxImg:maxImg})
            this.store.commit("addGenerateMaterialFils", data);
			// console.log(this.fileList);
			let moodboard = this.store.state.UploadFilesModule.moodboardGenerateFiles
			let sketch = this.store.state.UploadFilesModule.sketchGenerateFiles
			let print = this.store.state.UploadFilesModule.printGenerateFiles
			if((moodboard.length >= 2 || print.length >= 2 || sketch.length >= 2) && this.driver__.driver){
				driverObj__.moveNext()
			}
        },
        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('Generate.jsContent1'));
            }
            const isLt2M = file.size / 1024 / 1024 < 5;
            if (!isLt2M) {
                message.info(this.t('Generate.jsContent2'));
            }
            return (isJpgOrPng && isLt2M) || Upload.LIST_IGNORE;
        },
		setprintModel(value:any){
			this.printModel = value
		},
		imageToSketch(){
			if((!this.printModel?.id && !this.printModel?.value) || !this.sketchboardList?.[0]?.id)return message.info(this.t('Generate.jsContent4'));
			this.loadingShow = true
			let data = {
				"elementId": this.sketchboardList[0].id,
				gender:this.workspace.sexEnum.value,
				"style": this.printModel.value,
				"styleImageId": this.printModel?.id?this.printModel?.id:''
			}
			Https.axiosPost(Https.httpUrls.imageToSketch, data).then((rv)=>{
				if(rv){
					this.sketchCatecoryList.forEach((itemCategory:any) => {
						if(itemCategory.value == rv.category){
							rv.categoryValue = itemCategory?.value
							rv.category = itemCategory?.name
						}
					});
					this.fileList.push({
						imgUrl:rv.url,
						categoryValue:rv.categoryValue,
						category:rv.category,
						id:rv.id,
						status:'Success',
					})
					this.loadingShow = false
				}
			}).catch(()=>{
				this.loadingShow = false
			})
		},
		getgenerate(){
			if(this.scene?.value == 'extract'){
				this.imageToSketch()
				return
			}
			this.isTextarea = false
			this.isInputFocus = false
			if(this.isGenerate)return
			clearInterval(this.remGenerateTime)
			if(this.searchPictureName){
				let arr = this.searchPictureName.split(/\s+/).length
				if(arr > 250){
					message.info(
					this.t('Generate.jsContent4')
					);
					return
				}
			}else{
				if(this.sketchboardList?.[0]?.imgUrl){

				}else{
					message.info(
						this.t('Generate.jsContent5')
					);
					return
				}
				
			}
			let level2Type = ''
			let collectionElementId = ''
			let base64 = ''
			if(this.sketchboardList?.[0]){
				collectionElementId = this.sketchboardList[0].id
				if(this.sketchboardList[0].base64){
					base64 = this.sketchboardList[0].imgUrl
				}
			}
			let sloganText = ''
			sloganText = this.searchPictureName
			if(this.upload.level1Type == "Sketchboard"){
				level2Type = this.sketchboardList?.[0]?.categoryValue?this.sketchboardList[0].categoryValue:''
				if(this.workspace.styleName){
					sloganText = `${this.workspace.styleName},${sloganText}`
				}
			}else if(this.upload.level1Type == "Printboard"){
				level2Type = this.scene?.value
				if(level2Type == 'Slogan' && this.searchPictureName == ''){
					sloganText = this.isSloganHint
				}else if(level2Type == 'Pattern'){
					sloganText = `${this.printModel.value},${sloganText}`
				}
				if(!base64 && level2Type == 'Slogan'){
					message.info(this.t('Generate.jsContent10'));
					return
				}
			}
			let data = {
				generateType:'text',
				designType:'collection',
				collectionElementId:collectionElementId,
				level1Type:this.upload.level1Type,
				level2Type:level2Type,
				text:sloganText,
				seed:this.searchPictureSeed,
				userId:this?.userDetail?.userId,
				timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,
				version:this.speedData.value,//为1就是Print
				isTestUser:this.driver__.driver?false:this.isTest,
				gender:this.workspace.sexEnum.value,
				sloganBase64:base64,
			}
			this.generateLevel2Type = data.level2Type
			this.isGenerate = true
			this.remGenerateTime = setTimeout(()=>{
				this.remGenerate = true
			},10000)
			Https.axiosPost(Https.httpUrls.generatePrepare, data).then(
                (rv) => {
					// if(data.isTestUser){
					// 	if(rv.leftUsageCount >= 1){
					// 		message.warning(this.t('Generate.jsContent8',{num:rv.leftUsageCount,str:this.t('collectionModal.Moodboard')}));
					// 	}else if(rv.leftUsageCount == 0){
					// 		message.warning(this.t('Generate.jsContent9',{str:this.t('collectionModal.Moodboard')}));
					// 		this.isGenerate = false
					// 		return
					// 	}
					// }
					this.setGenerate(rv.uniqueId)
					
                }
            ).catch(res=>{
				this.generateLevel2Type = ''
				this.isGenerate = false
				clearInterval(this.remGenerateTime)
				this.remGenerate = false

				if(res.errCode === 2){
					let this_ = this
					Modal.confirm({
						title: res.errMsg,
						icon: createVNode(ExclamationCircleOutlined),
						okText: 'Yes',
						cancelText: 'No',
						mask:false,
						zIndex:99999,
						centered:true,
						onOk() {
							let UpgradePlan:any = this_.$refs.UpgradePlan
							UpgradePlan.init()
						},
						onCancel(){
							
						}
					});
				}
            });
		},
		setGenerate(dataList:any){
			
			let data = dataList
			let dataNum = dataList.length
			let state = true
			this.generateTime = setInterval(()=>{
				if(!state)return
				state = false
				Https.axiosPost(Https.httpUrls.generateResult, data).then(
					(rv) => {
						state = true
						if(this.isGenerate){//防止取消后有正在执行的获取状态
							this.generateProceedList = rv.filter((item:any)=>item.status != 'Success' && item.status != 'Fail' && item.status != 'Invalid')
							rv.forEach((element:any) => {
								if(element.status == 'Success'){
									element.imgUrl = element.url
									element.id_ = GO.id++
									this.fileList.unshift(element)
									data = data.filter((item:any) => item !== element.taskId);
									if(this.type_.type2 == 'Sketchboard'){
										this.sketchCatecoryList.forEach((itemCategory:any) => {
											if(itemCategory.value == element.category){
												element.categoryValue = itemCategory?.value
												element.category = itemCategory?.name
											}
										});
									}else{
										element.categoryValue = this.scene?.value
										element.category = this.scene?.name
									}
								}
							});
							if((data.length == 0)|| (rv.filter((item:any)=>item.status == 'Invalid').length ==data.length)){
								if(rv.filter((item:any)=>item.status == 'Invalid').length ==dataNum){
									message.info(this.t('Generate.effectPoor'));
								}else{
									nextTick().then(()=>{
										if(this.driver__.driver){
											driverObj__.moveNext()
										}
									})
								}
								
								this.store.dispatch('getCredits')
								clearInterval(this.generateTime)
								clearInterval(this.remGenerateTime)
								this.remGenerate = false
								this.isGenerate = false
								this.generateLevel2Type = ''
							}
						}
					}
				).catch(res=>{
					clearInterval(this.generateTime)
					clearInterval(this.remGenerateTime)
					this.isGenerate = false
					this.remGenerate = false
					this.generateLevel2Type = ''
				});
			},1000)
		},
		removeGenerate(){
			//取消操作
			this.isGenerate = false
			this.remGenerate = false
			clearInterval(this.generateTime)
			if(this.generateProceedList){
				let str = this.generateProceedList.map((obj:any) => obj.taskId).join(',');
				let type = 'Generate'
				if(this.generateLevel2Type == 'Logo'){
					type = 'Logo'
				}
				let data = {
					uniqueId:str,
					userId:this?.userDetail?.userId,
					timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,
					type: type
				}
				Https.axiosGet(Https.httpUrls.generateStopWaiting, {params:data}).then(
					(rv) => {
						this.generateProceedList = []
					}
				).catch(res=>{
				});
			}
		},
		setTextareaShow(){
			this.isTextarea = !this.isTextarea
			if(this.isTextarea){
				document.addEventListener('click',this.setTextareaShow)
			}else{
				document.removeEventListener('click',this.setTextareaShow)
			}
		},
		cliSetKeyword(value:any){
			let str = ''
			if(this.searchPictureName[this.searchPictureName.length-1] != ',' && this.searchPictureName.length != 0){
				str = ','
			}
			if(this.upload.level1Type == "Moodboard"){
				if(this.workspace?.allKeywordsByStyle['Printboard'].indexOf(value) == -1){
					this.styleRecommend.push(value)
					this.styleRecommend = [...new Set(this.styleRecommend)]
				}
			}
			this.searchPictureName += str + value
		},
		ifSeedValue(e:any){
			if(this.searchPictureSeed == ''){
				this.searchPictureSeed = 0
			}
		},
		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 > 250){
					(this.$refs.inputShowText as any).innerHTML = this.t('Generate.maximumLength')
					this.inputShow = true
				}else{
					this.inputShow = false
				}
			},500)
		},
		inputFocus(){
			if(this.isInputFocus) return
		    this.isInputFocus = true
			let setDomCli = ()=>{
				this.isInputFocus = false
				document.removeEventListener('click',setDomCli)
			}
			setTimeout(()=>{
				document.addEventListener('click',setDomCli)
			},200)
		},
        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){
					let category:any={
						value:'',
						name:'',
					}
					if(this.sketchCatecoryList && this.type_.type2 == 'Sketchboard'){
						this.sketchCatecoryList.forEach((item:any) => {
							if(item.name == res.data.level2Type){
								category.value = item?.value
								category.name = item?.name
							}
						});
					}
					file.id = res.data.id;
					file.imgUrl = res.data.url;
					file.resData = res.data;
					file.type_ = "upload";
					file.id_ = GO.id++;
					file.categoryValue = category?.value;
					file.category = category?.name;
					//判断是否粘贴来的图片
					let paste = this.sketchboardList.filter((v: any) => v.id === file.id);
					if(paste.length == 0)this.sketchboardList.push(file);
					this.sketchboardList = this.sketchboardList.filter((v: any) => v.status === "done");
					nextTick().then(()=>{
						if(this.driver__.driver && this.type_.type2 == 'Printboard'){
							driverObj__.moveNext()
						}
					})
				}else{
					bor = false
				}
                
            } else if (file.status === "error") {
					bor = false
            }
			if(!bor){
				let index = -1;
                let res:any = JSON.parse(file.xhr.response);
                this.sketchboardList.forEach((ele: any, index1: any) => {
                    if (file.uid === ele.uid) {
                        index = index1;
                    }
                });
                if (index > -1) {
                    this.sketchboardList.splice(index, 1);
                }
                // message.warning(file.name + this.t('SketchboardUpload.jsContent1'));
                message.warning(res.errMsg);
			}
        },
		setSlogan(){
			let createSlogan:any = this.$refs.createSlogan
			createSlogan.init()
		},
		setSloganData(data:any){
			this.sketchboardList = data
		},
        deleteFile(item: any) {
			if(this.scene?.value == 'Slogan' && this.type_.type2 == 'Printboard'){
				let createSlogan:any = this.$refs.createSlogan
				createSlogan.isDeleteSlogan = true
			}
			this.sketchboardList.splice(item, 1);
			// if((this.sketchboardList.length<2 && this.moodboarList.length == 0) || this.sketchboardList.length == 0){
			// 	this.printModel = {
			// 		num:'',
			// 		optype:false,
			// 		value:'Painting Style',
			// 		label:this.t('Generate.Model'+1)
			// 	}
			// }
        },
		likeFile(item:any,str:string){
			if(str == 'like'){
				let level2Type = ''
				if(this.upload.level1Type == "Sketchboard"){
					level2Type = item.categoryValue
				}else if(this.upload.level1Type == "Printboard"){
					level2Type = this.scene?.value
				}
				let data = {
					generateDetailId:item.id,
					level1Type:this.type_.type2,
					level2Type: level2Type,
					gender:this.workspace.sexEnum.value,
					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=>{
				});
			}
		},
		deleteGenerate(index:any){
			// if(this.isGenerate)return
			let num = this.fileList.length
			let _this = this
            Modal.confirm({
                title: this.t('LibraryPage.jsContent1'),
                icon: createVNode(ExclamationCircleOutlined),
                okText: 'Yes',
                cancelText: 'No',
				mask:false,
                centered:true,
                onOk() {
					let a = _this.fileList.length - num
					_this.fileList.splice(index-a,1)
                }
            });
		},
		scaleImage(index:any){
			let scaleImage:any = this.$refs.scaleImage
			scaleImage.init(this.fileList,index)
		},
        closeModal() {
            // this.myMaterialModalShow = false
            this.searchPictureName = "";
        },
		onPaste(e:any){
			if(e.clipboardData.items[0] && !this.isTextarea && this.upload.level1Type !== 'Moodboard' && this.scene?.value != 'Slogan' && this.scene?.value != 'Logo'){
				let param = new FormData(); 
				param.append('inPin','0')
				param.append('gender',this.upload.gender)
				param.append('level1Type',this.upload.level1Type)
				param.append('timeZone',Intl.DateTimeFormat().resolvedOptions().timeZone)
				param.append('file',e.clipboardData.files[0]);
				let config:any = {headers:{'Content-Type':'multipart/form-data','Accept':'*/*'  }}
				Https.axiosPost(Https.httpUrls.elementUpload, param, config).then((v)=>{
					let value = {data:v,errCode : 0}
					v.status = 'done'
					let data = {
						file:{
							status: 'done',
							xhr:{
								response:JSON.stringify(value)
							}
						}
					}
					this.fileUploadChange(data)
					
				})
			}
			
		}
    },
});
</script>
<style lang="less" scoped>
.generate {
	flex: 1;
    // height: 30rem;
    // overflow-x: hidden;
	overflow-x: hidden;
	display: flex;
    flex-direction: column;
    border-right: 1px solid #e5e5e5;
	position: relative;
	// padding-top: calc(2.5rem*1.2);
	.input_border{
		padding-top: 1rem;
	}
    
	.mark_loading{
		position: absolute;
		width: 100%;
		height: 100%;
		z-index: 99;
	}
    .generate_checkbox,
    .generage_input {
        display: flex;
        align-items: center;
        position: sticky;
        top: 0;
        background: #fff;
        padding-top: calc(2rem*1.2);
        z-index: 3;
    }
    .generate_checkbox {
    }
    .generage_input {
    }
    .generage_img {
        display: flex;
		position: relative;
        flex-wrap: wrap;
		align-content: flex-start;
		flex: 1;
		overflow-y: auto;
		&.generage_img::-webkit-scrollbar {
        display: none;
    }
        .generage_img_item {
            cursor: pointer;
            margin: 0 calc(2rem*1.2) calc(2rem*1.2) 0;
			position: relative;
            &.active {
				opacity: 0.5;
				// border: 2px solid;
				border-radius: calc(1rem*1.2);
				img {
					transform: scale(0.9);
				}
				.delete_like_file_block{
					pointer-events:none;
				}
				.operate_file_block{
					pointer-events:none;
				}
			}
            img {
                width: calc(10rem*1.2);
                height: calc(10rem*1.2);
				object-fit: contain;
            }
			&:hover .delete_like_file_block{
				// display: block;
				opacity: 1;
			}
			
        }
        .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 {
				// 	}
				// }
                .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: calc(3.2rem*1.2);
                        height: calc(3.2rem*1.2);
                        background: rgba(0, 0, 0, 0.6);
                        border-radius: calc(0.4rem*1.2);
                        position: absolute;
                        top: calc(0.9rem*1.2);
                        right: calc(0.9rem*1.2);
                        text-align: center;
                        line-height: calc(3.2rem*1.2);
                        left: auto;
                        .icon-shanchu {
                            font-size: calc(1.6rem*1.2);
                            color: #fff;
                        }
                    }

                    &:hover .delete_file_block {
                        display: block;
                    }
                }
            }
        }
    }
}

</style>
