<template>
    <!-- 范围校验 -->
    <div>
        <el-checkbox
            v-model="verify[attr]"
            @change="autoFocus"
        >
            限定{{ checkbox ? '选择数量' : attr === 'range' ? '数值' : '字数'}}范围
            <el-popover trigger="manual" v-model="formItem[minError]">
                <p class="error">不能超过最大值</p>
                <el-input
                    :value="verify[min]"
                    @input="verify[min] = posInt($event), autoCheck(verify[min])"
                    @blur="validate"
                    :ref="min"
                    slot="reference"
                ></el-input>
            </el-popover>
            ~
            <el-popover trigger="manual" placement="top" v-model="formItem[maxError]">
                <p class="error">不能低于最小值</p>
                <el-input
                    :value="verify[max]"
                    @input="verify[max] = posInt($event), autoCheck(verify[max])"
                    @blur="validate"
                    slot="reference"
                ></el-input>
            </el-popover>
        </el-checkbox>
    </div>
</template>

<script>
import { posInt } from '@/assets/utils/formatString.js'
export default {
    props: {
        attr: { type: String, default: 'length' }, // 校验属性
        length: { type: Boolean, default: false }, // 是否限定选择数量范围
        checkbox: { type: Boolean, default: false } // 是否是多选限定范围
    },
    data () {
        return {
            posInt,
            min: this.attr + 'Min',
            max: this.attr + 'Max',
            minError: this.attr + 'MinError',
            maxError: this.attr + 'MaxError',
            formItem: this.$store.state.form.formItem,
            verify: this.$store.state.form.formItem.verify
        }
    },
    methods: {
        // 勾选后自动聚焦后面的空输入框并校验
        autoFocus (value) {
            if (value) {
                this.validate()
                if (!this.verify[this.min] && !this.verify[this.max]) this.$refs[this.min].focus()
            } else {
                this.setError(false)
            }
        },
        // 未勾选就填写值则自动选中
        autoCheck (value) {
            this.setError(false)
            if (value && !this.verify[this.attr]) this.verify[this.attr] = true
        },
        // 校验左边是否大于右边
        validate () {
            const min = this.verify[this.min]
            const max = this.verify[this.max]
            if (min && max && min - 0 > max - 0) this.setError(true)
        },
        // 设置校验最大最小值错误
        setError (value) {
            this.formItem[this.minError] = value
            this.formItem[this.maxError] = value
        }
    }
}
</script>

<style lang="less" scoped>
.el-checkbox {
    display: block;
    margin-top: 10px;
    .el-input {
        width: 70px;
        margin: 0 5px;
        /deep/ input {
            padding: 0 5px;
            text-align: center;
        }
    }
}
.error {
    text-align: center;
    color: #F56C6C;
}
</style>
