<template>
    <div v-if="hasAuth" class="father">
        <el-switch :model-value="modelValue" :loading="loading" :active-value="activeValue" :inactive-value="inactiveValue"></el-switch>
        <div @click="_onClick" class="abs"></div>
    </div>
    <div v-else :class="{'green' : isOn}">
        {{isOn ? onText : offText }}
    </div>
</template>

<script>
export default {
    name: "st-switch",
    emits:["update:modelValue","change"],
    props:{
        auth:String, //若赋值为--则表示渲染为纯文本
        modelValue : [Boolean,String,Number] ,
        activeValue : {
            type : [Boolean,String,Number],
            default : true
        },
        inactiveValue  : {
            type : [Boolean,String,Number],
            default : false
        },
        beforeChange:{
            type : Function ,
            required : true ,
            default(){
                return ()=>{};
            }
        },
        params:{
            type : Object,
            default(){
                return {} ;
            }
        },
        onText:{
            type : String ,
            default : "已开启"
        },
        offText:{
            type : String ,
            default : "已关闭"
        }
    },
    computed:{
        isOn(){
            return this.modelValue === this.activeValue ;
        },
        hasAuth(){
            if(this.auth == "--") return false ;
            return !this.auth || this.$s.hasAuth([this.auth]);
        }
    },
    data(){
        return {
            loading : false
        }
    },
    methods:{
        async _onClick(){
            this.loading = true ;
            await this.beforeChange(this.params).finally(()=> this.loading = false);
            let value = this.modelValue === this.activeValue ? this.inactiveValue : this.activeValue ;
            this.$emit("update:modelValue" , value);
            this.$emit("change" , value);
        }
    }
}
</script>