<template>
  <div ref="bgSwitch" class="bg-switch" :class="{ disabled: disabled }" :style="now_style" @click="switch_data">
    <span class="label" :style="now_label_style">
      {{ labels[now_index] }}
    </span>
    <span class="circle" :style="now_circle_style" ref="circle">
      <!-- circle -->
    </span>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
const props = defineProps({
  modelValue: {
    type: [Boolean, Number, String],
    default: 0,
  },
  labels: {
    type: Array,
    default: () => ["停用", "启用"],
  },
  values: {
    type: Array,
    default: () => [0, 1],
  },
  colors: {
    type: Array,
    default: () => ["#cbced7", "#2b4695"],
  },
  disabled: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(["update:modelValue"]);

const gap = ref(0);

const box_height = ref(0);

const circle_height = ref(0);

const now_index = computed(() => {
  if (props.values[0] == props.modelValue) {
    return 0;
  } else {
    return 1;
  }
});

const now_style = computed(() => {
  return {
    borderColor: props.colors[now_index.value],
    backgroundColor: props.colors[now_index.value],
  };
});

const now_label_style = computed(() => {
  return now_index.value == 0 ? { left: circle_height.value + gap.value + 5 + "px" } : { left: "6px" };
});

const now_circle_style = computed(() => {
  return now_index.value == 0
    ? {
        left: gap.value + "px",
      }
    : {
        left: "calc(100% - 16px)",
      };
});

const switch_data = () => {
  if (props.disabled) {
    return;
  }

  if (props.values[0] == props.modelValue) {
    emit("update:modelValue", props.values[1]);
  } else {
    emit("update:modelValue", props.values[0]);
  }
};

const bgSwitch = ref(null);
const circle = ref(null);

onMounted(() => {
  box_height.value = bgSwitch.value.offsetHeight;
  circle_height.value = circle.value.offsetHeight;
  gap.value = (box_height.value - circle_height.value - 4) / 2;
});
</script>
