<template>
  <label>
    <input
      type="checkbox"
      :name="name"
      :value="value"
      :checked="isChecked"
      @change="onChange"
    />
    <span class="bar" :style="style">
      <span class="handle" :style="style" />
    </span>
  </label>
</template>

<script>
export default {
  name: 'Toggle',
  props: {
    name: {
      type: String,
    },
    value: {
      type: String,
    },
    isChecked: {
      type: Boolean,
    },
    change: {
      type: Function,
      default: function() {},
    },
  },
  data() {
    return {
      checked: this.isChecked ? this.isChecked : false
    }
  },
  computed: {
    style() {
      return {
        '--bgColor': this.checked ? '#1890FF' : '#aaaaaa',
        '--left': this.checked ? '20px' : '0px',
      }
    },
  },
  methods: {
    onChange: function() {
      this.checked = !this.checked
      this.change && this.change()
    },
  },
}
</script>

<style lang="scss" scoped>
@import '../const/variable.scss';

label {
  display: inline-block;
  position: relative;
  height: 32px;
  width: 52px;

  input {
    opacity: 0;
    width: 0;
    height: 0;
  }

  .bar {
    --bgColor: '#1890FF';
    background-color: var(--bgColor);

    cursor: pointer;
    -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
    position: absolute;
    border-radius: 16px;
    top: 0;
    left: 0;
    width: 52px;
    height: 32px;
    transition: all 0.2s;

    .handle {
      --left: 20px;
      left: var(--left) !important;

      position: absolute;
      background-color: palette(white, base);
      border-radius: 28px;
      width: 28px;
      height: 28px;
      margin: 2px;
      transition: all 0.2s;
      box-shadow: 0 6px 8px rgba(102, 119, 136, 0.03),
        0 1px 2px rgba(102, 119, 136, 0.3);
    }
  }
}
</style>
