<template>
  <view
    class="radio"
    :class="{
      'radio--disabled': isDisabled,
      'radio-active': isChecked,
    }"
    @click="handleClick"
  >
    <!-- <view class="radio__icon" :class="{ 'radio__icon--checked': isChecked }">
      <view v-if="isChecked" class="radio__icon-dot"></view>
    </view> -->
    <view class="radio__label">
      <slot>{{ label }}</slot>
    </view>
  </view>
</template>

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

const props = defineProps({
  name: {
    type: [String, Number],
    required: true,
  },
  label: {
    type: String,
    default: '',
  },
  disabled: {
    type: Boolean,
    default: false,
  },
})

interface RadioGroupContext {
  modelValue: ComputedRef<string | number>
  disabled: ComputedRef<boolean>
  toggleOption: (value: string | number) => void
}

// 注入radio group的上下文
const radioGroup = inject<RadioGroupContext>('radioGroup', {
  modelValue: computed(() => ''),
  disabled: computed(() => false),
  toggleOption: () => {},
})

// 是否选中
const isChecked = computed(() => {
  return radioGroup.modelValue.value === props.name
})

// 是否禁用
const isDisabled = computed(() => {
  return props.disabled || radioGroup.disabled.value
})

// 处理点击事件
const handleClick = () => {
  if (isDisabled.value) return
  radioGroup.toggleOption(props.name)
}
</script>

<style scoped lang="scss">
.radio {
  display: inline-flex;
  align-items: center;
  cursor: pointer;
  font-size: 28rpx;
  width: 100%;
  height: 100%;
  justify-content: center;

  &--disabled {
    cursor: not-allowed;
    opacity: 0.5;
  }

  // &__icon {
  //   width: 40rpx;
  //   height: 40rpx;
  //   border: 2rpx solid #dcdfe6;
  //   border-radius: 50%;
  //   display: flex;
  //   align-items: center;
  //   justify-content: center;
  //   margin-right: 8rpx;
  //   transition: all 0.2s;

  //   &--checked {
  //     border-color: #0083ff;
  //   }
  // }

  // &__icon-dot {
  //   width: 20rpx;
  //   height: 20rpx;
  //   background-color: #0083ff;
  //   border-radius: 50%;
  // }

  &__label {
    line-height: 1;
  }
}

.radio-active {
  color: #0083ff;
  border: 2rpx solid #0083ff;
  border-radius: 8rpx;
}
</style>
