<template>
  <view
    class="k-toggle"
    :class="{
      'is-checked': value,
      'is-disabled': disabled,
    }"
    @click="handleChange"
    :style="{
      width: `${size * 2 + 5}px`,
      height: `${size}px`,
      borderRadius: `${size}px`,
      borderColor: [value ? activeColor : ''],
      opacity: disabled ? 0.3 : 1,
    }"
  >
    <view
      class="k-toggle-ball"
      :style="{
        width: `${size - 4}px`,
        height: `${size - 4}px`,
        transform: value ? `translateX(${size + 5}px)` : `translateX(0px)`,
        backgroundColor: [value ? activeColor : ''],
      }"
    >
      <slot name="icon" />
    </view>
  </view>
</template>

<script lang="ts">
import Vue from 'vue';
export default Vue.extend({
  name: 'k-toggle',
  props: {
    disabled: {
      type: Boolean,
      default: false,
    },
    value: {
      type: Boolean,
      default: false,
    },
    size: {
      type: Number,
      default: 19,
    },
    activeColor: {
      type: String,
      default: '',
    },
  },
  methods: {
    handleChange() {
      if (!this.disabled) {
        this.$emit('input', !this.value);
        this.$emit('change', !this.value);
      }
    },
  },
});
</script>

<style scoped lang="scss">
.k-toggle {
  display: inline-block;
  background-color: var(--k-color-minor, #000);
  position: relative;
  transition-duration: 0.3s;
  transition-timing-function: ease-in-out;
  border: 1px solid var(--k-color-minor, #000);

  &.is-disabled {
    background-color: var(--k-color-minor, #000);
    border: 1px solid var(--k-color-minor, #000);
  }

  .k-toggle-ball {
    background-color: #fff;
    border-radius: var(--k-border-radius-circle);
    position: absolute;
    left: 5.5rpx;
    top: 4.5rpx;
    transition-duration: 0.3s;
    transition-timing-function: ease-in-out;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  &.is-checked {
    background-color: #fff;
    border: 1px solid var(--k-color-primary-01, #000);

    .k-toggle-ball {
      background-color: var(--k-color-primary-01, #000);
    }

    &.is-disabled {
      background-color: #fff;
      border: 1px solid var(--k-color-primary-01, #000);
      cursor: not-allowed;

      .k-toggle-ball {
        background-color: var(--k-color-primary-01, #000);
      }
    }
  }
}
</style>
