<template>
	<view class="switch-container" :class="{ 'is-disabled': disabled }" @click="toggleSwitch">
		<view class="switch-background" :style="backgroundStyle">
			<view class="switch-text" v-if="activeText!=''">{{textInfo}}</view>
		</view>
		<view class="switch-thumb" :style="thumbPosition"></view>
	</view>
</template>

<script setup lang="ts">
	import { computed, withDefaults } from 'vue'

	const props = withDefaults(defineProps<{
		modelValue : boolean //
		disabled ?: boolean  //是否禁用
		activeColor ?: string  //开启颜色
		inactiveColor ?: string  //关闭颜色
		activeText ?: string  //开启文字
		inactiveText ?: string  //关闭文字(待完善)
	}>(), {
		disabled: false,
		activeColor: '#67c23a',
		inactiveColor: '#dcdfe6',
		activeText: '',
		inactiveText: ''
	})

	const emit = defineEmits<{
		(e : 'update:modelValue', value : boolean) : void
		(e : 'change', value : boolean) : void
	}>()

	const isActive = computed({
		get: () => props.modelValue,
		set: (value) => {
			if (props.disabled) return
			emit('update:modelValue', value)
			emit('change', value)
		}
	})

	const toggleSwitch = () => {
		isActive.value = !isActive.value
	}

	// 样式计算属性
	const backgroundStyle = computed(() => ({
		backgroundColor: isActive.value ? props.activeColor : props.inactiveColor
	}))

	// 样式切换思路：通过isActive控制css属性transform的translateX值向X轴移动的位置
	const thumbPosition = computed(() => ({
		transform: `translateX(${isActive.value ? '28px' : '2px'})`
	}))
	
	const textInfo=computed(()=>{
		return isActive.value?props.activeText:props.inactiveText
	})
</script>

<style lang="less" scoped>
	.switch-container {
		position: relative;
		width: 50px;
		height: 26px;

		&.is-disabled {
			opacity: 0.2;
			cursor: not-allowed;
		}
	}

	.switch-background {
		position: absolute;
		width: 100%;
		height: 100%;
		border-radius: 16px;
		transition: background-color 0.3s ease;

		.switch-text {
			margin-top: 5px;
			margin-left: 5px;
			font-size: 20rpx;
			color: #fff;
		}
	}

	.switch-thumb {
		position: absolute;
		top: 3px;
		left: 0px;
		width: 20px;
		height: 20px;
		border-radius: 50%;
		background-color: white;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
		transition: transform 0.3s ease;
	}
</style>