<template>
	<view class="container" @click="toggleSwitch">
		<label :class="isOn ? 'switch-checked' : 'switch-nochecked'">
			<view class="open">{{ activeText }}</view>
			<view class="close">{{ inactiveText }}</view>
		</label>
	</view>
</template>

<script setup>
	import {
		ref,
		watch,
	} from 'vue';

	const props = defineProps({
		value: {
			type: Boolean,
			default: false
		},
		activeText: {
			type: String,
			default: '已上线'
		},
		inactiveText: {
			type: String,
			default: '已下线'
		},
		activeValue: {
			type: [Number, String, Boolean],
			default: true
		},
		inactiveValue: {
			type: [Number, String, Boolean],
			default: false
		},
	});

	const emit = defineEmits(['update:value', 'change']);

	const isOn = ref(props.value);
	watch(() => props.value, (newVal) => {
		isOn.value = newVal;
	});

	const toggleSwitch = () => {
		isOn.value = !isOn.value;
		emit('update:value', isOn.value ? props.activeValue : props.inactiveValue);
		emit('change', isOn.value ? props.activeValue : props.inactiveValue);
	};
</script>

<style lang="scss" scoped>
	.container {
		width: 156rpx;
		padding: 10rpx;

		label {
			position: relative;
			display: block;
			border-radius: 40rpx;
			width: 100%;

			&:before {
				content: " ";
				display: block;
				border-radius: 50rpx;
				height: 50rpx;
				background-color: #d5d5d5;
				transform: scale(1, 1);
				transition: all 0.3s ease;
			}

			&:after {
				content: "";
				position: absolute;
				top: 3rpx;
				left: 0;
				width: 44rpx;
				height: 44rpx;
				border-radius: 50%;
				background: #fff;
				border: 2rpx solid #e0e0e0;
				box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.12);
				transition: all 0.3s cubic-bezier(.4, 0, .2, 1);
				z-index: 2;
			}
		}

		%font-style {
			top: 0;
			color: #ffffff;
			font-size: 28rpx;
			height: 100%;
			line-height: 50rpx;
			position: absolute;
			transition: all 1s ease;
		}

		.switch-checked {
			&:after {
				left: unset;
				right: 5rpx;
				top: 1.5rpx;
				border: 2rpx solid #FFDA59;
			}

			&:before {
				background-color: #FFDA59;
			}

			.close {
				display: none;
			}
		}

		.switch-nochecked {
			&:before {
				background-color: #d5d5d5;
			}

			&:after {
				left: 5rpx;
				top: 1.5rpx;
				border: 2rpx solid #d5d5d5;
			}

			.open {
				display: none;
			}
		}

		.open {
			left: 20rpx;
			@extend %font-style;
			font-size: 26rpx;
			color: #56441B;
			display: flex;
			align-items: center;
			height: 56rpx;
			position: absolute;
			top: 0;
		}

		.close {
			right: 20rpx;
			@extend %font-style;
			font-size: 26rpx;
			color: #56441B;
			display: flex;
			align-items: center;
			height: 56rpx;
			position: absolute;
			top: 0;
		}
	}
</style>