<template>
  <div class="lyf-ui-switch" :class="{ checked: value }" :style="{
    width: customSize.switchW,
    height: customSize.switchH,
    backgroundColor: customColor,
    borderColor: customColor
  }" @click="switchClick">
    <div class="lyf-ui-switch-dot" :style="{ width: customSize.dotW, height: customSize.dotH }"></div>
  </div>
</template>

<script>
export default {
  name: 'LyfSwitch',
  props: {
    value: {
      type: Boolean,
      default: false
    },
    color: {
      type: String,
      default: ''
    },
    size: {
      type: [String, Number],
      default: ''
    }
  },
  computed: {
    customColor() {
      if (this.value && this.color) {
        return this.color
      }
      return undefined
    },
    customSize() {
      // 大小比例：2.215 = 34/16，分别对应设计稿默认大小中“容器宽”和“原点宽”
      let _o = {}
      let _size = 0
      if (this.size) {
        if (typeof this.size === 'number') {
          _size = this.size
        } else {
          if (this.size.indexOf('px') > -1) {
            _size = this.size.substring(0, this.size.length - 2)
          } else {
            _size = this.size
          }
        }
        _o.dotW = _o.dotH = _size - 2 + 'px'

        _o.switchW = _size * 2.215 + 'px'
        _o.switchH = _size + 'px'
      }
      return _o
    }
  },
  emits: ['input'],
  methods: {
    switchClick() {
      this.$emit('input', !this.value)
    }
  }
}
</script>

<style scoped>
.lyf-ui-switch {
  position: relative;
  width: 32px;
  height: 16px;
  border: solid var(--border-width_1) var(--border-color_2);
  border-radius: var(--radius_50);
  background-color: var(--background-color_2);
  transition: background-color .2s;
}

.lyf-ui-switch .lyf-ui-switch-dot {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 1%;
  width: 14px;
  height: 14px;
  margin: auto;
  background-color: var(--background-color_2);
  border-radius: 50%;
  box-shadow: 0px 0px 3px rgba(0, 0, 0, 0.2), 0px 3px 16px rgba(0, 0, 0, 0.08), -1px 3px 3px rgba(0, 0, 0, 0.1);
  transition: left .2s;
}

.lyf-ui-switch.checked {
  justify-content: flex-end;
  border-color: var(--primary-color);
  background-color: var(--primary-color);
}

.lyf-ui-switch.checked .lyf-ui-switch-dot {
  left: 56%;
}
</style>