<template>
    <div class="color">
		<div class="detailText">Current color</div>
		<div class="pallet">
			<pallet :selectColor="selectColor" @selectUplpadColor="selectUplpadColor"></pallet>
		</div>
		<div class="detailText">Color pelette</div>
		<div class="colorBox">
			<div v-for="item,index in colorList.list[selectDetail.id]" @click="setSelectColor(item,index)" class="colorBoxItem" :class="{active:colorList.index == index}">
				<div v-show="!item.gradient" class="background" :style="{'background-color':item.hex}"></div>
				<div v-show="!item.gradient" class="text">{{ item.hex }}</div>
				<div v-show="!item.gradient" class="text">{{ item.name }}</div>
				<div v-show="item.gradient" class="backgroundImg" :style="{'background-image':`linear-gradient(${item.gradient?.angle}deg,${setGradient(item.gradient)})`}"></div>
			</div>
		</div>
		<div class="detailText">Choose color from image</div>
		<div class="uploadImage">
			<upload @selectUplpadColor="selectUplpadColor"></upload>
		</div>
		<div class="detailText">Color Code</div>
		<div class="colorCode">
			<div class="generalModel_state">
				<div class="generalModel_state_item">
					<input class="search_input" placeholder="Tcx value（e.g:19-4052)" v-model="tcxToColor" style="width: 100%;" @keydown.enter="getTcxColor()">
				</div>
			</div>
			<div class="getTcxColorBtn" @click="getTcxColor">Extract Color</div>
		</div>
    </div>
    
</template>
<script lang="ts">
import { defineComponent,computed,ref,watch,nextTick,toRefs, reactive, onMounted} from 'vue'
// import setDesignItem from '@/component/Detail/setDesignItem2.vue'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { useStore } from "vuex";
import { Https } from "@/tool/https";
import { useI18n } from 'vue-i18n'
import { rgbaToHex,rgbToHsv } from "@/tool/util"
import { message,Upload} from 'ant-design-vue';

import upload from './upload.vue'
import pallet from './pallet.vue'
export default defineComponent({
    components:{
		upload,pallet
    },
    setup(props,{emit}) {
        const store = useStore();
        const {t} = useI18n();
		const colorData = reactive({
			selectTitle:'current',
			selectDetail:computed(()=>store.state.DesignDetailCopy.selectDetail),
			allBoardData:computed(()=>store.state.UploadFilesModule.allBoardData),
			currentDetailType:computed(()=>store.state.DesignDetailCopy.currentDetailType),
			colorList:{
				list:{},
				index:-1,
			} as any,
			selectColor:{} as any,
			setGradient:computed(()=>{
				return (gradient:any)=>{
					let gradientStr = ''
					if(!gradient?.gradientList)return
					gradient.gradientList.sort((a:any, b:any) => {
						let aArr = a.left.split('%')[0]
						let bArr = b.left.split('%')[0]
						return aArr - bArr;
					});
					gradient.gradientList.forEach((item:any,index:any)=>{
						let str = ','
						if(gradient.gradientList.length == index+1)str = ''
						gradientStr += `rgba(${item.rgba.r},${item.rgba.g},${item.rgba.b},${item.rgba.a}) ${item.left}${str}` 

					})
					return `${gradientStr}`
				}
			}),
			tcxToColor:'',
		})
		watch(()=>colorData.selectColor,async (newVal,oldVal)=>{
		    if(!newVal?.name && newVal.rgba){
				let data:any = await getColorName(newVal.rgba)
				newVal.name = data.name
				newVal.tcx = data.tcx
				colorData.colorList.list[colorData.selectDetail.id][colorData.colorList.index] = newVal
				let value = {
					data:newVal,
					str:'color'
				}
				store.commit('DesignDetailCopy/setNewDetail',value)
			}
		})
		watch(()=>colorData.selectDetail.id,(newVal,oldVal)=>{
			if(!newVal)return
			if(!colorData.colorList?.list?.[newVal]){
				colorData.colorList.list[newVal] = []
			}else{
				return
			}
			
			let isNoSelect = false
			let isOneChecked = false
			for (let index = 0; index < 9; index++) {
				colorData.allBoardData.colorBoards
				let item:any = {}
				item = colorData.allBoardData.colorBoards[index]
				if(
					colorData.allBoardData.colorBoards?.[index] &&
					colorData.selectDetail.color.rgba?.r == colorData.allBoardData.colorBoards?.[index]?.rgba?.[0] &&
					colorData.selectDetail.color.rgba?.g == colorData.allBoardData.colorBoards?.[index]?.rgba?.[1] &&
					colorData.selectDetail.color.rgba?.b == colorData.allBoardData.colorBoards?.[index]?.rgba?.[2] &&
					JSON.stringify(colorData.selectDetail.color.gradient) == JSON.stringify(colorData.allBoardData.colorBoards?.[index]?.gradient)
				){
					if(!isOneChecked){
						isOneChecked = true
						if(colorData.allBoardData.colorBoards?.[index].gradient){
							item.gradient = colorData.allBoardData.colorBoards?.[index].gradient
						} 
						colorData.selectColor = item
						colorData.colorList.index = index
					}
				}else{
					if(!isNoSelect){
						item = {
							hex:rgbaToHex([colorData.selectDetail.color.rgba.r,colorData.selectDetail.color.rgba.g,colorData.selectDetail.color.rgba.b]),
							id:colorData.selectDetail.color.id,
							rgba:{
								r:colorData.selectDetail.color.rgba.r,
								g:colorData.selectDetail.color.rgba.g,
								b:colorData.selectDetail.color.rgba.b,
							},
							tcx:colorData.selectDetail.color.tcx,
							name:colorData.selectDetail.color.name,
						}
						if(colorData.selectDetail.color.gradient){
							item.gradient = colorData.selectDetail.color.gradient
						} 
						colorData.colorList.index = index
						colorData.selectColor = item
						isNoSelect = true
					}else{
						item = {}
					}
				}
				colorData.colorList.list[newVal].push(item)
			}
		},{immediate: true})
		const selectImgItem = ()=>{

		}
		const getColorName = (color:any)=>{
			let rgb:any = [color.r, color.g, color.b];
			let hsv = rgbToHsv(rgb);
			let data = [{
				h: hsv[0],
				s: hsv[1],
				v: hsv[2],
			}]
			return new Promise((resolve, reject) => {
			    Https.axiosPost(Https.httpUrls.getRgbByHsvBatch, data)
					.then((rv) => {
						if (rv) {
							resolve(rv[0])
						}
					})
					.catch((res) => {
						resolve({name:'--',tcx:'--'})
					});
			})
		}
		const selectUplpadColor = (item:any)=>{
			colorData.selectColor = JSON.parse(JSON.stringify(item))
		}
		const setSelectColor = (item:any,index:number)=>{
			colorData.colorList.index = index
			if(item.rgba){
				colorData.selectColor = item
			}else{
				// colorData.colorList.list[colorData.selectDetail.id][index] = {}
				colorData.selectColor = {}
			}
		}
		const getTcxColor = ()=>{
			 if(!colorData.tcxToColor){
                return
            }
			let pattern = /^\d{2}-\d{4}$/;
			if(pattern.test(colorData.tcxToColor)){
				Https.axiosGet(Https.httpUrls.getRgbByTcx + '?tcx=' + colorData.tcxToColor).then((rv) =>{
					if(rv && rv.name){
						let hex = rgbaToHex([rv.r,rv.g,rv.b,rv.a? rv.a :1])
						let value = {
							hex:hex,
							rgba:{
								r:rv.r,
								g:rv.g,
								b:rv.b,
							},
							name:rv.name,
							tcx:rv.tcx,
							id:rv.id,
						}
						colorData.selectColor = value
					}else{
						message.info(t('DesignDetailAlter.jsContent6'))
					}
				})
			}else{
				message.info(t('ColorboardUpload.jsContent5'))
			}
		}
		onMounted(()=>{
			if(colorData.allBoardData.colorBoards){
				colorData.allBoardData.colorBoards.forEach((item:any)=>{
					item.rgba = item.rgbValue
					let rgba = [item.rgbValue.r,item.rgbValue.g,item.rgbValue.b]
					item.hex = rgbaToHex(rgba)
				})
			}
			
		})
        return{
			...toRefs(colorData),

			selectImgItem,
			selectUplpadColor,
			setSelectColor,
			getTcxColor,
        }
    },

	provide() {
		return {
		}
	},
		
})
</script>
<style lang="less" scoped>
    .color{
		// width: 34rem;
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		overflow-y: auto;
		> .detailText{
			margin-bottom: .5rem;
		}
		> .pallet{
			margin-bottom: 2rem;
		}
		> .colorBox{
			margin-bottom: 1rem;
			display: flex;
			flex-wrap: wrap;
			justify-content: space-between;
			> .colorBoxItem{
				// margin: 1rem 0;
				margin-bottom: 1rem;
				width: 32%;
				height: 11rem;
				border-radius: .5rem;
				border: 1px solid #999;
				cursor: pointer;
				display: flex;
				flex-direction: column;
				&.active{
					border: 2px solid #000;
				}
				> .background{
					flex: 1;
					height: 7rem;
					width: 100%;
				}
				> .text{
					font-weight: 600;
					line-height: 2rem;
					text-align: center;
				}
				> .backgroundImg{
					width: 100%;
					height: 100%;
				}
			}
		}
		> .uploadImage{
			flex-shrink: 0;
			margin-bottom: 3rem;
			border: 1px dashed transparent;
        	background: linear-gradient(#fff, #fff) padding-box,repeating-linear-gradient(-45deg,#fff 0,#fff 0.3em,	#000 0,#000 0.6em);
			height: 10rem;
			width: 100%;
			border-radius: .5rem;
		}
		> .colorCode{
			margin-bottom: 3rem;
			> .generalModel_state{
				> .generalModel_state_item{
					width: 100%;
					margin: 0;
					input{
						background: #f4f4f4;
					}
				}
			}
			> .getTcxColorBtn{
				background: #BDBDBD;
				border-radius: 5rem;
				line-height: 6rem;
				text-align: center;
				margin-top: 2rem;
				cursor: pointer;
				width: 100%;
				transition: all .3s;
				&:hover{
					background: #d4d4d4;
				}
			}
		}
		
	}
</style>