<template>
	<div class="brandDetail">
		<div class="title">
			<div @click="back" class="back"><i class="fi fi-rr-arrow-small-left" style="font-size: 4rem; display:flex;"></i></div>
		</div>
		<div class="userDetail">
			<div class="logo">
				<img :src="logoUrl" alt="">
				<div class="upload_box">
					<i class="fi fi-rr-camera"></i>
					<a-upload
						class="upload"
						:capture="null"
						list-type="picture-card"
						:before-upload="beforeUpload"
						:customRequest="function(){}"
						:maxCount="1"
						accept=".jpg,.png,.jpeg,.bmp"
						>
						<div
							class="upload_tip_block"
						>
							<i class="fi fi-br-upload"></i>
							<!-- <img :src="uploadUrl?uploadUrl:userDetail.avatar" alt=""> -->
						</div>
					</a-upload>
				</div>
			</div>
			<div class="info">
				<div class="name">
					<span v-if="!isEditUserName" style="font-size:3rem;">{{ brandName }}</span>
					<input v-else type="text" v-model="brandName">
					<i v-if="!isEditUserName" class="fi fi-rr-edit" @click="openEdit('userName')"></i>
					<i v-else class="fi fi-br-check" @click="editChek('userName')"></i>
				</div>
				<div class="slogan">
					<div>Slogan:</div>
					<span v-if="!isEditDescribe" style="font-weight: 300;">{{ brandSlogan }}</span>
					<input v-else type="text" v-model="brandSlogan">
					<i v-if="!isEditDescribe" class="fi fi-rr-edit" @click="openEdit('brandSlogan')"></i>
					<i v-else class="fi fi-br-check" @click="editChek('brandSlogan')"></i>
				</div>
			</div>
			<div style="flex:1;text-align: right;" v-show="imgList.length > 0">
				<div class="gallery_btn" v-show="schedule.num == 1||(schedule.num == 0 && !schedule.state)" @click="compute">Compute</div>
				<div v-show="schedule.num != 1">
					<a-progress  style="width:20rem;" :percent="schedule.num * 100" size="small" :showInfo="false" />
				</div>
			</div>
		</div>
		<div class="content">
			<div style="display: flex;">
				<a-upload
					class="upload"
					:capture="null"
					:before-upload="beforeUpload"
					:customRequest="customRequest "
					:multiple="true"
					:maxCount="15"
					accept=".jpg,.png,.jpeg,.bmp"
				>
					<div class="gallery_btn">Upload</div>
				</a-upload>
				<div style="margin-left:2rem;" @click="deleteBatchPic" class="gallery_btn">Delete</div>
			</div>
			<div class="imgBox">
				<div class="imgItem" v-for="item,index in imgList" :key="item.id" :class="{active:selectImgList.indexOf(item.id) > -1}" @click="selectImg(item)">
					<img :src="item.url" alt="">
					<i class="fi fi-rr-trash icon_delete" @click="deleteSinglePic(item,index)"></i>
				</div>
			</div>
			<div class="total">
				<a-pagination
					v-model:current="currentPage"
					v-model:pageSize="pageSize"
					:total="total"
					:showQuickJumper="true"
					:showSizeChanger="false"
					@change="changePage"
				/>
			</div>
		</div>
		<div class="mark_loading" v-show="isShowMark">
			<a-spin size="large" />
		</div>
		<Cropper ref="Cropper" @handleCropperSuccess="handleCropperSuccess" :cropperFileData="cropperFileData" :isRound="true"></Cropper>
		<!-- <loadBrandDNA ref="loadBrandDNA"></loadBrandDNA> -->
	</div>
</template>
<script lang="ts">
import { defineComponent,computed,ref,provide,onBeforeUnmount,createVNode,toRefs, reactive} from 'vue'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { Https } from "@/tool/https";
import { Modal,message } from 'ant-design-vue';
import { useStore } from "vuex";
import { useI18n } from 'vue-i18n'
import Cropper from '@/component/HomePage/Cropper.vue'
// import loadBrandDNA from '@/component/LibraryPage/loadBrandDNA.vue'
import { getCookie } from "@/tool/cookie";

export default defineComponent({
	components:{
		Cropper
	},
	
	emits:['update:isShowMark','handleBack'],
	props: {
		isShowMark:{type:Boolean,default:false},
		selectCode:{type:String,default:''},
	},
	setup(props,{emit}) {
		const store = useStore();
		const {t} = useI18n();
		const data = reactive({
            cropperFileData:{name:'',uid:''}, //裁剪的原始文件数据
			uploadUrl:'',
			uploadFile:undefined,
			isEditUserName:false,
			isEditDescribe:false,
			brandName:'',
			brandSlogan:'',
			minioUrl:'',
			detail:{} as any,
			logoUrl:'',
			uploadList:[],
			upload:{},
			token:getCookie("token"),
			isShowMark:false,
			imgList:[],
			total:0,
			pageSize:10,
			currentPage:1,
			selectImgList:[] as any,//选择删除的图片
			getProgressTime:null as any,//获取进度的时间
			schedule:{
				num:0,
				state:false
			}
		})
		const dataDom = reactive({
			Cropper:null as any,
			loadBrandDNA:null as any,
		})
		const customRequest = (event:any)=>{
			console.log(data.detail)
            let new_data = {
                file:event.file,
				brandId:data.detail.id,
            }
            data.isShowMark = true
            Https.axiosPost(Https.httpUrls.brandDNAUpload, new_data,{headers:{'Content-Type': 'multipart/form-data'}}).then(
                (rv: any) => {
					getLibraryList()
					data.isShowMark = false
                }
            ).catch((res)=>{
                getLibraryList()
				data.isShowMark = false
            });
        }
		let  fileUploadChange = (data:any)=>{
            let file = data.file
			// file.id = res.data.id?res.data.id:""
			var reader = new FileReader();
			reader.onload = (e:any) => {
				let data_new;
				if (typeof e.target.result === 'object') {
				// 把Array Buffer转化为blob 如果是base64不需要
				data_new = window.URL.createObjectURL(new Blob([e.target.result]));
				} else {
				data_new = e.target.result;
				}
				dataDom.Cropper.getOptionImg(data_new)
			};
			reader.readAsArrayBuffer(file.originFileObj);
			dataDom.Cropper.changeShowModal(true)
        }
		let  getLibraryList = ()=>{
            let value = {
				// classificationIdList:labelArr,
                level1Type:'BrandDNA',
                level2Type:'',
                page:data.currentPage,
				// modelSex:sex.value?sex.value:'',
                // pictureName:searchPictureName.value,
                size:data.pageSize,
				brandId:data.detail.id,
				// intersection:intersection.value,
			}
			data.isShowMark = true
			Https.axiosPost(Https.httpUrls.queryLibraryPage,value).then(
				(rv: any) => {
					data.imgList = rv.content
					data.total = rv.total
					data.isShowMark = false
				}
			).catch((res)=>{
				data.isShowMark = false
			});
        }
		let beforeUpload=(file:any,fileList:any)=>{
            const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/bmp';
            if (!isJpgOrPng) {
                message.info(useI18n().t('PrintboardUpload.jsContent1'));
            }
            const isLt2M = file.size / 1024 / 1024 < 5;
            if (!isLt2M) {
                message.info(useI18n().t('PrintboardUpload.jsContent2'));
            }
        }
		let handleCropperSuccess = (event:any)=>{
            let {file, fileData,base64} =event
			data.uploadUrl = base64
			data.uploadFile = file
            dataDom.Cropper.closeCropper()
			if(!data.uploadFile)return
			let param = new FormData(); 
			param.append('file',data.uploadFile);
			let config:any = {headers:{'Content-Type':'multipart/form-data','Accept':'*/*'  }}
			Https.axiosPost(Https.httpUrls.brandLogoUpload,param,config)
			.then((rv)=>{
				data.logoUrl = rv.minioUrl
				data.minioUrl = rv.brandLogo
				uploadBrand()
			})
		}
		const openEdit = (str:string)=>{
			if(str == 'userName'){
				data.isEditUserName = true
			}
			if(str == 'brandSlogan'){
				data.isEditDescribe = true
			}
		}
		const editChek = (str:string)=>{
			if(str == 'userName')data.isEditUserName = false
			if(str == 'brandSlogan')data.isEditDescribe = false
			uploadBrand()
		}
		const getBranDetailData = (value:any)=>{
			data.detail = value
			data.brandName = value.brandName;
			data.brandSlogan = value.brandSlogan;
			data.logoUrl = value.minioUrl
			data.minioUrl = value.brandLogo
			clearInterval(data.getProgressTime)
			getProgress()
			getLibraryList()
			// emit("update:isShowMark",true)
			// setTimeout(()=>{
			// 	emit("update:isShowMark",false)
			// },2000)
		}
		const back = ()=>{
			clearInterval(data.getProgressTime)	
			emit("handleBack")
		}
		const uploadBrand = ()=>{
			let value = {
				"brandLogo": data.minioUrl,
				"brandName": data.brandName,
				"brandSlogan": data.brandSlogan,
				"id": data.detail.id,
			}
			Https.axiosPost(Https.httpUrls.brandDNASaveOrUpdate,value).then((res:any)=>{
			}).catch((err:any)=>{
				// console.log(err)
			})
		}
		const compute = ()=>{
			Https.axiosPost(Https.httpUrls.productImageInitialize,{brandId:data.detail.id}).then((res:any)=>{
				getProgress()
			}).catch((err:any)=>{
				// console.log(err)
			})
		}
		const getProgress = ()=>{
			setTimeout
			if(props.selectCode != 'MyBrand'){
				clearTimeout(data.getProgressTime)
				return
			}
			Https.axiosPost(Https.httpUrls.getInitializeProgress,{brandId:data.detail.id}).then((res:any)=>{
				data.schedule.num = res.percent
				data.schedule.state = res.analyzed
				if(res.percent == 1 || !res.analyzed){return clearTimeout(data.getProgressTime)}
				data.getProgressTime = setTimeout(()=>{
					getProgress()
				},5000)
				// analyzed

			}).catch((err:any)=>{
				// console.log(err)
			})
			
		}
        const changePage = (current:number, pageSize:number)=>{
			data.currentPage = current
            data.pageSize = pageSize
		}
		const deleteBatchPic = ()=>{
			if(!data.selectImgList.length){
                return
            }
            Modal.confirm({
                title: t('LibraryPage.jsContent2'),
                icon: createVNode(ExclamationCircleOutlined),
                okText: 'Yes',
                cancelText: 'No',
                centered:true,
                onOk() {
                    confirmDeletePic('',0,'')
                }
            });
		}
		const deleteSinglePic = (data:any,index:any)=>{
            Modal.confirm({
                title: t('LibraryPage.jsContent1'),
                icon: createVNode(ExclamationCircleOutlined),
                okText: 'Yes',
                cancelText: 'No',
				mask:false,
                centered:true,
                onOk() {
                    confirmDeletePic(data,index,'')
                }
            });
        }
		const confirmDeletePic = (value:any,index:any,nData:any)=>{
			let libraryIds = value ? [value.id] : data.selectImgList
			let newData = {
				libraryIds:libraryIds,
				deleteModelConfirm:'',
				timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,  
			}
			if(nData)newData = nData
			Https.axiosPost(Https.httpUrls.batchDeleteLibrary, newData).then(
				(rv: any) => {
					getLibraryList()
					data.selectImgList = []
				}
			).catch((res)=>{
			});
		}
		const selectImg = (item:any)=>{
			if(data.selectImgList.indexOf(item.id) > -1){
				data.selectImgList = data.selectImgList.filter((selectItem:any)=>selectItem != item.id)	
			}else{
				data.selectImgList.push(item.id)
			}
		}
		onBeforeUnmount(()=>{
			clearInterval(data.getProgressTime)	
		})
		return{
			...toRefs(dataDom),
			...toRefs(data),
			getBranDetailData,
			fileUploadChange,
			back,
			customRequest,
			beforeUpload,
			handleCropperSuccess,
			openEdit,
			editChek,
			compute,
			changePage,
			deleteBatchPic,
			deleteSinglePic,
			selectImg,
		}
	},
	provide() {
		return {
		}
	},
})
</script>
<style lang="less" scoped>
	.brandDetail{
		width: 100%;
		height: 100%;
		position: relative;
		font-weight: 600;
		font-size: 2.2rem;
		display: flex;
		flex-direction: column;
		> .title{
			display: flex;
			justify-content: space-between;
			align-items: center;
			> .back{
				font-weight: 400;
				font-size: 2rem;
				cursor: pointer;
				margin-left: -2rem;
			}
		}
		> .userDetail{
			display: flex;
			margin-top: 2rem;
			align-items: center;
			border-bottom: 1px solid #ccc;
			padding-bottom: 1rem;
			margin-bottom: 1rem;
			> .logo{
				position: relative;
				margin-right: 3rem;
				> img{
					width: 10rem;
					height: 10rem;
					object-fit: contain;
					border-radius: 50%;
				}
				> .upload_box{
					position: absolute;
					bottom: 0;
					right: 0;
					> i{
						width: 4rem;
						height: 4rem;
						display: flex;
						align-items: center;
						justify-content: center;
						border-radius: 50%;
						background: rgba(0,0,0,.5);
						color: #fff;
						font-size: 2rem;
					}
					> .upload{
						position: absolute;
						width: 100%;
						height: 100%;
						top: 0;
						left: 0;
						overflow: hidden;
						opacity: 0;
					}
				}
			}
			> .info{
				> .name, > .slogan{
					display: flex;
					align-items: center;
					> i{
						cursor: pointer;
						margin-left: 1rem;
						display: flex;
					}	
					> div{
						margin-right: 1rem;
					}
					> input{
						min-width: 20rem;
						height: 3.6rem;
						border-radius: 4rem;
						border: 1px solid;
						padding-left: 1.5rem;
					}
				}
				> .name{
					margin-bottom: 1rem;
				}
			}
		}
		> .content{
			flex: 1;
			display: flex;
			overflow: hidden;
			flex-direction: column;
			:deep(.upload){
				position: relative;
				overflow: hidden;
				margin-left: auto;
				> .ant-upload-list{
					display: none;
				}
			}
			> .imgBox{
				flex: 1;
				display: flex;
				align-content: flex-start;
				flex-wrap: wrap;
				> .imgItem{
					width: 100px;
					margin: 1rem;
					position: relative;
					cursor: pointer;
					aspect-ratio:  1 / 2.5;
					&.active{
						opacity: 0.5;
					}
					> img{
						width: 100%;
						height: 100%;
						object-fit: contain;
					}
					> i{
						position: absolute;
						top: 1rem;
						right: 1rem;
						cursor: pointer;
						display: none;
						cursor: pointer;
						padding: 0.5rem;
						font-size: 2rem;
					}
					&:hover{
						> i{
							display: flex;
						}	
					}
				}
			}
			> .total{
				text-align: center;
			}
			// > .upload_item{
			// 	width: 10rem;
			// 	height: 10rem;
			// 	align-items: center;
			// 	justify-content: center;
			// }
		}
	}
</style>