<template>
    <div class="upload">
		<div class="successfullyUpload" v-show="uploadList?.[selectDetail.id]?.length >= 1">
			<div class="img">
				<div class="upload_file_item" v-for="(file) in uploadList?.[selectDetail.id]" :key="file">
					<div class="upload_file_item_content" v-show="file.status !== 'done'">
						<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="delete_file_block" @click="colorDeleteFile(index)">{{ $t('DesignDetailAlter.Delete') }}</div>
					</div>
				</div>
			</div>
			<div class="color">
				<div v-for="item in colorList?.[selectDetail.id]" :key="item" @click="selectColor(item)" :style="{'background-color': item.hex}"></div>	
			</div>
		</div>
		<a-upload
			:capture="null"
			v-show="!uploadList?.[selectDetail.id] || uploadList?.[selectDetail.id]?.length < 1"
			list-type="picture-card"
			:customRequest="function(){}"
			@change="fileUploadChange"
			:before-upload="beforeUpload"
			:action="null"
			accept=".jpg,.png,.jpeg,.bmp"
			>
			<div  class="upload_tip_block">
				<i class="fi fi-br-upload"></i>
			</div>
		</a-upload>
    </div>
    
</template>
<script lang="ts">
import { defineComponent,computed,h,watch,nextTick,createVNode,toRefs, reactive} from 'vue'
import { message,Upload} from 'ant-design-vue';
import { useStore } from "vuex";
import GO from "@/tool/GO";
import { LoadingOutlined } from '@ant-design/icons-vue';
import { useI18n } from 'vue-i18n'
import { rgbaToHex } from "@/tool/util"
export default defineComponent({
    components:{
    },
	emits:['selectUplpadColor'],
    setup(props,{emit}) {
		const {t} = useI18n();
        const store = useStore();
		const colorUpload = reactive({
			selectDetail:computed(()=>store.state.DesignDetailCopy.selectDetail),
			
			uploadList:{} as any,
			indicator: h(LoadingOutlined, {
                style: {
                    fontSize: "2.4rem",
                },
                spin: true,
            }),
			colorList:{} as any,

		})
		
		const fileUploadChange = (data:any)=>{
            let file:any = data.file
            let fileData = file.originFileObj
            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;
                }
                file.imgUrl = data_new
                file.status = 'done'
				if(!colorUpload.uploadList[colorUpload.selectDetail.id])colorUpload.uploadList[colorUpload.selectDetail.id]=[]
				colorUpload.uploadList[colorUpload.selectDetail.id].push(file)

				setTimeout(async ()=>{
					const img = new Image();
					// let colorImage = this.$refs.colorImage
					img.src = file.imgUrl;

					img.onload = async () => {
						const colorThief = new ColorThief();
						// let domImg = colorImage[0];
						// let color = colorThief.getColor(img)
						// let colorHex = this.rgbaToHex(color)
						let selectColorList:any = [];
						let selectColor = colorThief.getPalette(img,8)
						//排序
						let obj = {
							max : 5,
							min: 5,
						}

						let colorSort:any
						await GO.setColor(selectColor,file.imgUrl,obj).then(
							(rv:any) => {
								if(rv){
									colorSort = rv.ratio
								}
							}
						)
						colorSort.sort((a:any, b:any) => {
							var a_num = a.ratio;
							var b_num = b.ratio;
							return b_num - a_num;
						});
						selectColor = []
						colorSort.forEach((v:any)=>{
							selectColor.push(v.rgb)
						})
						selectColor = selectColor.join('&')
						selectColor = selectColor.split("&")
						let color = selectColor[0].split(',')
						let colorHex = rgbaToHex(color)

						let colorLi:any = []
						new Set(selectColor).forEach((item:any)=>{
							colorLi.push(item.split(","))
						})
						colorLi.forEach((element:any) => {
							let colorLiHex = rgbaToHex(element)
							selectColorList.push(
								{rgba:{r:element[0],g:element[1],b:element[2],a:1},hex:colorLiHex}
							)
						});
						if(!colorUpload.colorList[colorUpload.selectDetail.id])colorUpload.colorList[colorUpload.selectDetail.id]=[]
						colorUpload.colorList[colorUpload.selectDetail.id] = selectColorList
						// this.getHsvColor(selectColorList)
						// this.selectColor = {rgba:{r:color[0],g:color[1],b:color[2],a:1},hex:colorHex}
						img.remove()
					};
                },100)
            };
            // 转化为base64S
            reader.readAsDataURL(fileData)
        }
		const 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(t('DesignDetailAlter.jsContent4'));
            }
            const isLt2M = file.size / 1024 / 1024 < 5;
            if (!isLt2M) {
                message.info(t('DesignDetailAlter.jsContent5'));
            }
            return (isJpgOrPng && isLt2M) || Upload.LIST_IGNORE;
        }
		const selectColor = (color:any)=>{
			emit('selectUplpadColor',color)
		}
		const colorDeleteFile = ()=>{
			colorUpload.uploadList[colorUpload.selectDetail.id] = []
			colorUpload.colorList[colorUpload.selectDetail.id] = []
		}
        return{
			...toRefs(colorUpload),

			fileUploadChange,
			beforeUpload,
			colorDeleteFile,
			selectColor,
        }
    },

	provide() {
		return {
		}
	},
		
})
</script>
<style lang="less" scoped>
    .upload{
		// width: 34rem;
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;
		:deep(.ant-upload-picture-card-wrapper){
			height: 100%;
			width: 100%;
			.ant-upload-list{
				height: 100%;
				width: 100%;
				.ant-upload-select-picture-card{
					height: 100%;
					width: 100%;
					border: none;
					margin: 0;
					background: #fff;
					&:hover{
						border: none;
					}
				}
			}
			.upload_tip_block{
				i{
					font-size: 4rem;
					display: flex;
				}
			}
		}
		> .successfullyUpload{
			width: 100%;
			display: flex;
			> .color{
				display: flex;
				margin-left: 1rem;
				flex-wrap: wrap;
				align-items: center;
				> div{
					margin: .5rem;
					width: 3rem;
					height: 3rem;
					cursor: pointer;
				}
			}
			> .img{
				> .upload_file_item{
					> .upload_file_item_content{
						width: 9rem;
						height: 9rem;
						position: relative;
						&:hover{
							> .delete_file_block{
								display: block;
							}
						}
						> .delete_file_block{
							display: none;
							cursor: pointer;
							position: absolute;
							bottom: 0;
							line-height: 3rem;
							background: rgba(0, 0, 0, 0.6);
							color: #fff;
							width: 100%;
							text-align: center;
						}
						> img{
							width: 100%;
							height: 100%;
							object-fit: contain;
						}
					}
					
				}
			}
		}
	
	}
</style>