<script>
export default {
  name: 'MSwitch',
}
</script>
<script setup>
import { nextTick, ref, watchEffect } from 'vue'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  activeColor: {
    type: String,
    default: '#409eff'
  },
  inactiveColor: {
    type: String,
    default: ''
  },
  name: {
    type: String,
    default: ''
  }
})

const emit = defineEmits([
  'update:modelValue'
])

const mswitch = ref(null)
watchEffect(() => {
  nextTick(() => {
    mswitch.value.style.setProperty('--primary-color', props.activeColor)
  })
})

function handleClick () {
  emit('update:modelValue', !props.modelValue)
}
</script>

<template>
  <div ref="mswitch" class="m-switch" :class="{'is-checked': modelValue}" @click="handleClick">
    <span ref="core" class="m-switch__core">
      <span class="m-switch__button"></span>
    </span>
    <input ref="input" type="checkbox" class="m-switch__input" :name="name" />
  </div>
</template>

<style lang="scss" scoped>
.m-switch {
  display: inline-block;
  align-items: center;
  position: relative;
  font-size: 14px;
  line-height: 20px;
  vertical-align: middle;
}

.m-switch__core {
  margin: 0;
  display: inline-block;
  position: relative;
  width: 40px;
  height: 20px;
  border: 1px solid #dcdfe6;
  outline: none;
  border-radius: 10px;
  box-sizing: border-box;
  background: #dcdfe6;
  cursor: pointer;
  transition: border-color .3s, background-color .3s;
  vertical-align: middle;

  .m-switch__button {
    position:absolute;
    top: 1px;
    left: 1px;
    border-radius: 100%;
    transition: all .3s;
    width: 16px;
    height: 16px;
    background-color: #fff;
  }
}

// 选中样式
.is-checked {
  .m-switch__core {
    // border-color: $bgcolor;
    // background-color: $bgcolor;
    border-color: var(--primary-color);
    background-color: var(--primary-color);

    .m-switch__button {
      transform: translateX(20px);
    }
  }
}

// 隐藏input标签
.m-switch__input {
  position:absolute;
  width: 0;
  height: 0;
  opacity: 0;
  margin: 0;
}
</style>
