<template>
	<view class="switchbox" :style="{background: value ? activeColor:inactiveColor}" @tap="change">
		<view :class="value ? 'switchbar checked-shadow':'switchbar checked-noshadow'" 
		:style="{transform: value ?`translate(32rpx,-50%)`:`translate(4rpx,-50%)`}"></view>
	</view>
</template>

<script>
	export default {
		name: "mySwitch",
		props: {
			// 通过v-model双向绑定的值
			value: {
				type: [Boolean, String, Number],
				default: false
			},
			// switch打开时的值
			activeValue: {
				type: [String, Number, Boolean],
				default: true
			},
			// switch关闭时的值
			inactiveValue: {
				type: [String, Number, Boolean],
				default: false
			},
			// 打开时的背景色
			activeColor: {
				type: String,
				default: "#FF7700"
			},
			// 关闭时的背景色
			inactiveColor: {
				type: String,
				default: "#E9E9EA"
			}
		},
		data() {
			return {
				
			}
		},
		computed: {
			isActive(){
				return this.value === this.activeValue;
			}
		},
		watch: {
			value: {
				immediate: true,
				handler(n) {
					if(n !== this.inactiveValue && n !== this.activeValue) {
						console.error("('v-model绑定的值必须为inactiveValue、activeValue二者之一')")
					}
				}
			}
		},
		methods: {
			change() {
				const oldValue = this.isActive ? this.inactiveValue : this.activeValue
				// 放到下一个生命周期，因为双向绑定的value修改父组件状态需要时间，且是异步的
				this.$nextTick(() => {
					this.$emit('change', oldValue)
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.switchbox {
		flex-shrink: 0;
		width: 76rpx;
		height: 48rpx;
		border-radius: 40rpx;
		position: relative;
		.switchbar {
			width: 40rpx;
			height: 40rpx;
			background: #FFFFFF;
			border-radius: 50%;
			position: absolute;
			left: 4rpx;
			top: 50%;
			transition: transform 0.3s;
		}
		.checked-shadow {
			box-shadow: -2rpx 2rpx 8rpx 0rpx rgba(233,84,3,0.7);
		}
		.checked-noshadow {
			box-shadow: 2rpx 0rpx 8rpx 0rpx rgba(204,204,204,0.7);
		}
	}
</style>