<template>
    <view
        :class="'custom-class ' + utils.bem('switch', { on: value === activeValue, disabled })"
        :style="'font-size: ' + size + '; ' + ((checked ? activeColor : inactiveColor) ? 'background-color: ' + (checked ? activeColor : inactiveColor) : '')"
        @tap="onClick"
    >
        <view class="van-switch__node node-class">
            <van-loading v-if="loading" :color="loadingColor" custom-class="van-switch__loading" />
        </view>
    </view>
</template>
<script module="utils" lang="wxs" src="@/node_modules/@vant/weapp/dist/wxs/utils.wxs"></script>
<script>
import { VantComponent } from '../common/component';
import { BLUE, GRAY_DARK } from '../common/color';
export default {
    data() {
        return {
            value: '',
            loadingColor: ''
        };
    },
    field: true,
    classes: ['node-class'],
    props: {
        checked: {
            type: null
        },
        loading: Boolean,
        disabled: Boolean,
        activeColor: String,
        inactiveColor: String,
        size: {
            type: String,
            default: '30px'
        },
        activeValue: {
            type: null,
            default: true
        },
        inactiveValue: {
            type: null,
            default: false
        }
    },
    created() {
        const { checked: value } = this;
        const loadingColor = this.getLoadingColor(value);
        this.setData({
            value,
            loadingColor
        });
    },
    methods: {
        getLoadingColor(checked) {
            const { activeColor, inactiveColor } = this;
            return checked ? activeColor || BLUE : inactiveColor || GRAY_DARK;
        },
        onClick() {
            const { activeValue, inactiveValue } = this;
            if (!this.disabled && !this.loading) {
                const checked = this.checked === activeValue;
                const value = checked ? inactiveValue : activeValue;
                this.$emit('input', value);
                this.$emit('change', value);
            }
        }
    },
    watch: {
        checked: {
            handler: function (value) {
                const loadingColor = this.getLoadingColor(value);
                this.setData({
                    value,
                    loadingColor
                });
            },

            immediate: true
        }
    }
};
</script>
<style>
@import './index.css';
</style>
