<template>
    <div class="" v-bind="$attrs">
        <q-field v-model="color" :label="displayName" labelColor="primary"  :clearable="isSelected" stack-label :bottom-slots="!isSelected" :rules="rulesExp">
            <template v-slot:control>
                <q-chip text-color="black" color="white" v-if="isSelected">
                    <div class="row">
                        <div class="col-4">
                            <q-avatar class="shadow-1" :style="{ background: color }" size="xs"></q-avatar>
                        </div>
                        <div class="col">
                            {{ color }}
                        </div>
                    </div>
                </q-chip>
            </template>
            <template v-slot:append>
                <q-icon name="colorize" class="cursor-pointer" color="primary" >
                    <q-popup-proxy cover transition-show="scale" transition-hide="scale">
                        <q-color no-header default-view="palette" v-model="color" />
                    </q-popup-proxy>
                </q-icon>
            </template>
            <template v-slot:hint>
                {{ placeholder }}
            </template>
        </q-field>


    </div>
</template>

<script lang="ts">
import { computed, defineComponent, ref,watchEffect } from 'vue';
export default defineComponent({
    inheritAttrs:false,
    name: 'ColorPicker',
    components: {
    },
    props: {
        displayName: {
            type: String,
            default: '',
        },
        name: {
            type: String,
            default: '',
        },
        placeholder: {
            type: String,
            default: '',
        },
        hint: {
            type: String,
            default: '',
        },
        modelValue: {
            type: String,
            default: null
        },
        //例：[val=>!!val ||'入力してください']
        rules: {
          type: String,
          default: undefined
        },
        required:{
          type:Boolean,
          default:false
        },
        requiredMessage: {
          type: String,
          default: ''
        }
    },
    setup(props, { emit }) {
        const color = ref(props.modelValue??'');
        const isSelected = computed(()=>props.modelValue && props.modelValue!=='');
        const customExp = props.rules === undefined ? [] : eval(props.rules);
        const errmsg = props.requiredMessage?props.requiredMessage:`${props.displayName}が必須です。`;
        const requiredExp = props.required?[((val:any)=>!!val || errmsg ),'anyColor']:[];
        const rulesExp=[...requiredExp,...customExp];
        watchEffect(()=>{
          emit('update:modelValue', color.value);
        });
        return {
            color,
            isSelected,
            rulesExp
        };
    }
});
</script>
