<template>
    <div :class="switchClass"
         @click="toogle">
        <div :class="`${prefix}-switch__dot`">
            <i v-if="loading"
               :class="`${prefix}-icon-loading`"></i>
        </div>
        <div v-if="showFont"
             :class="`${prefix}-switch__font`">
            <div :class="`${prefix}-switch__font--open`"
                 :style="{visibility: this.trueFalse?'':'hidden'}">
                <slot name="open">开</slot>
            </div>
            <div :class="`${prefix}-switch__font--close`"
                 :style="{visibility: this.trueFalse?'hidden':''}">
                <slot name="close">关</slot>
            </div>
        </div>
    </div>
</template>

<script>
import { prefix, prefixMixins } from 'jdd-design/utils';
export default {
    name: `${prefix}-switch`,
    mixins: [prefixMixins],
    data() {
        return {
            model: null,
            trueFalse: false
        };
    },
    props: {
        value: [Boolean, Number, String],
        openedLabel: [Boolean, Number, String],
        closedLabel: [Boolean, Number, String],
        showFont: Boolean,
        loading: Boolean,
        disabled: Boolean
    },
    watch: {
        value() {
            this.model = this.value;
            if (this.openedLabel) {
                this.trueFalse = this.value === this.openedLabel;
            } else {
                this.trueFalse = this.value;
            }
        }
    },
    computed: {
        switchClass() {
            let clsNames = [`${prefix}-switch`];
            clsNames.push(
                `${prefix}-switch--${this.trueFalse ? 'opened' : 'closed'}`
            );
            this.disabled && clsNames.push('is-disabled');
            this.loading && clsNames.push('is-loading');
            return clsNames;
        }
    },
    methods: {
        toogle() {
            if (this.disabled || this.loading) return;
            this.trueFalse = !this.trueFalse;
            if (this.trueFalse) {
                this.model = this.openedLabel || this.trueFalse;
            } else {
                this.model = this.closedLabel || this.trueFalse;
            }
            this.$emit('input', this.model);
            this.$emit('change', this.model);
        }
    },
    mounted() {
        this.model = this.value;
        if (this.openedLabel) {
            this.trueFalse = this.value === this.openedLabel;
        } else {
            this.trueFalse = this.value;
        }
    }
};
</script>
