<template>
    <view class="number-box">
        <view class="sub" @click="onSub" :class="{ disabled: subDisabled }"></view>
        <input type="number" class="control-input" v-model="inputValue" @blur="onBlur" />
        <view class="add" @click="onAdd" :class="{ disabled: addDisabled }"></view>
    </view>
</template>

<script>
export default {
    model: {
        prop: 'value',
        event: 'input'
    },
    props: {
        min: {
            type: Number,
            default: 1
        },
        max: {
            type: Number,
            default: 99999
        },
        value: {
            type: Number,
            default: 0
        }
    },
    data() {
        return {
            inputValue: ''
        }
    },
    computed: {
        addDisabled() {
            return this.inputValue === this.max
        },
        subDisabled() {
            return this.inputValue === this.min
        }
    },
    watch: {
        inputValue(nVal) {
            this.$emit('input', parseInt(this.inputValue))
        }
    },
    created() {
        this.inputValue = this.value
    },
    methods: {
        onBlur() {
            if (this.inputValue < this.min) this.inputValue = this.min
            if (this.inputValue > this.max) this.inputValue = this.max
            this.$emit('change', this.inputValue)
        },
        // 减法
        onSub() {
            if (this.inputValue <= this.min) {
                return
            }
            this.inputValue--
            this.$emit('change', this.inputValue)
        },
        // 加法
        onAdd() {
            if (this.inputValue >= this.max) {
                return
            }
            this.inputValue++
            this.$emit('change', this.inputValue)
        }
    }
}
</script>

<style lang="scss" scoped>
.number-box {
    width: 148rpx;
    height: 50rpx;
    border: 1rpx solid #e1e1e1;
    border-radius: 25rpx;
    @extend .cm-flex-between;

    .add,
    .sub {
        @extend .cm-flex-center;
        flex: 1;
        font-size: 24rpx;
        color: #666666;

        &.disabled {
            color: #cccccc;
        }
    }

    .add {
        &::before {
            margin-bottom: 2rpx;
            content: '+';
        }
    }

    .sub {
        &::before {
            margin-bottom: 2rpx;
            content: '-';
        }
    }

    .control-input {
        width: 56rpx;
        height: 48rpx;
        border-right: 1rpx solid #e1e1e1;
        border-left: 1rpx solid #e1e1e1;
        background-color: #f7f7f7;
        box-sizing: border-box;
        text-align: center;
        font-size: 26rpx;
        color: #333;
    }
}
</style>
