<template>
    <div class="sRGBHexWrap">
        <el-color-picker v-model="defaultValue" show-alpha  @change="updateColor"/>
        <el-tooltip content="取色器" placement="top">
            <img src="@/assets/icons/svg/straw.svg"  class="iconStyle" @click="handleOpen"/>
        </el-tooltip>
        
    </div>
</template>
 
<script setup>
 
import { useEyeDropper } from '@vueuse/core'
const { open, sRGBHex } = useEyeDropper();
// 引入 Vue 相关的 API
import { ref, watch, onMounted } from "vue";
 
// 定义组件的 props 和 emits
const props = defineProps(['modelValue'])
const emit = defineEmits(["update:modelValue", "update:isUpdate"]);
//默认颜色显示
let defaultValue = '#165DFF' //默认展示的颜色，使用ref无法触发初始化显示
let Value = ref(null) //派发的颜色
 
//获取颜色盘的颜色
const getColor = (newValue) => {
    defaultValue = newValue
    Value.value = newValue;
};
 
//监听接受的值然后进行复制
watch(() => props.modelValue, async (newValue) => {
    if (newValue) {
        getColor(newValue)
    }
}, { immediate: true })
 
//监听滴管颜色
watch(sRGBHex, async (newmodelValue) => {
    if (newmodelValue) {
        getColor(newmodelValue)
    }
})
 
//监听值的变化
watch(Value, async (newValue) => {
    if (newValue) {
        emit("update:modelValue", newValue);
    }
})
 
//获取颜色盘的颜色
const updateColor = (value) => {
    Value.value = value;
    emit("update:isUpdate");
};
 
//处理打开滴管时候按Esc按钮报错
const handleOpen = () => {
    try {
        open();
    } catch (error) {
        console.error('Error while opening EyeDropper:', error);
    }
};
 
 
</script>
 
<style lang="scss" scoped>
.color {
    background: var(--background-color2);
    outline: none;
    box-shadow: none;
    border: none;
}
 
.sRGBHexWrap {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    /* background-color: aliceblue; */
 
}
 
.iconStyle {
    width: 100%;
    height: 100%;
    cursor: pointer;
    width: 20px; 
    height: 20px;
    margin-left: 10px;
}
</style>