<template>
    <div :class="ui" class="hc-counter-box">
        <div class="counter-box">
            <div class="counter-btn first" :disabled="modelVal <= 1" @click="moveBtnClick">-</div>
            <div class='counter-val w-20'>
                <span>{{modelVal}}</span>
                <span class="ml-2" v-if="text">{{text}}</span>
            </div>
            <div class="counter-btn end" @click="addBtnClick">+</div>
        </div>
    </div>
</template>

<script setup>
import {ref, watch} from "vue";
const props = defineProps({
    ui: {
        type: String,
        default: ''
    },
    modelValue: {
        type: [String,Number],
        default: 1
    },
    text: {
        type: String,
        default: ''
    },
})

//转换
const setModelVal = (value) => {
    return parseInt(value || 1 + '');
}

const modelVal = ref(setModelVal(props.modelValue))

//监听
watch(() => props.modelValue, (value) => {
    modelVal.value = setModelVal(value)
})

const emit = defineEmits(['update:modelValue','addClick','moveClick'])

//减少
const moveBtnClick = () => {
    let val = modelVal.value - 1;
    if (val <= 1) {
        modelVal.value =  1;
    } else {
        modelVal.value =  val;
        emit('update:modelValue', val)
        emit('moveClick', val)
    }
}

//增加
const addBtnClick = () => {
    let val = modelVal.value + 1;
    modelVal.value =  val;
    emit('update:modelValue', val)
    emit('addClick', val)
}
</script>

<style lang="scss" scoped>
.hc-counter-box {
    position: relative;
    display: inline-block;
    height: 32px;
    .counter-box {
        display: flex;
        align-items: center;
        height: inherit;
        color: #000000;
        .counter-btn {
            height: 32px;
            width: 32px;
            border: 1px solid #eeeeee;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 22px;
            font-weight: 100;
            cursor: pointer;
            user-select: none;
            background-color: white;
            transition: color 0.2s, background-color 0.2s;
            &.first {
                border-radius: 4px 0 0 4px;
            }
            &.end {
                border-radius: 0 4px 4px 0;
            }
            &:hover {
                color: var(--el-color-primary);
                background-color: var(--el-color-primary-light-8);
            }
            &[disabled=true] {
                cursor: not-allowed;
                color: #c5c5c5;
                background-color: #f3f3f3;
            }
        }
        .counter-val {
            height: inherit;
            border-top: 1px solid #eeeeee;
            border-bottom: 1px solid #eeeeee;
            display: flex;
            align-items: center;
            justify-content: center;
        }
    }
}
</style>
