<script>

export default {
  name: 'MRadio',
}
</script>
<script setup>
import { inject, computed } from 'vue'

const radioGroup = inject('RadioGroup', '')

const props = defineProps({
  label: {
    type: [String, Number, Boolean],
    defualt: ''
  },
  modelValue: null,
  name: {
    type: String,
    defualt: ''
  }
})

const emit = defineEmits([
  'update:modelValue'
])

const model = computed({
  get: () => {
    return isGroup.value ? radioGroup.props.modelValue : props.modelValue
  },

  set: (value) => {
    if (isGroup.value) {
      radioGroup.emit('update:modelValue', value)
    } else {
      emit('update:modelValue', value)
    }
  }
})

// 用于判断 radio 是否被 radio-group 包裹
const isGroup = computed(() => !!radioGroup)
</script>

<template>
  <label class="m-radio" :class="{'is-checked': label === model}">
    <span class="m-radio__input">
      <span class="m-radio__inner"></span>
      <input
        v-model="model"
        :name="name"
        type="radio"
        class="m-radio__original"
        :value="label"
      />
    </span>
    <span class="m-radio__label">
      <slot></slot>
      <!-- 如果没有传值，就把label作为文本显示 -->
      <template v-if="!$slots.default">{{ label }}</template>
    </span>
  </label>
</template>

<style lang="scss" scoped>
.m-radio {
  color: #606266;
  font-weight: 500;
  line-height: 1;
  position: relative;
  cursor: pointer;
  display: inline-block;
  white-space: nowrap;
  outline: none;
  font-size: 14px;
  margin-right: 30px;
  user-select: none;

  .m-radio__input {
    white-space: nowrap;
    cursor: pointer;
    outline: none;
    display: inline-block;
    line-height: 1;
    position: relative;
    vertical-align: middle;

    .m-radio__inner {
      border: 1px solid #dcdfe6;
      border-radius: 100%;
      width: 14px;
      height: 14px;
      background-color: #fff;
      position: relative;
      cursor: pointer;
      display: inline-block;
      box-sizing: border-box;
      &:after{
        width: 4px;
        height: 4px;
        border-radius: 100%;
        background-color: #fff;
        content: "";
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%,-50%) scale(0);
        transition: transform .15s ease-in;
      }
    }

    .m-radio__original {
      opacity: 0;
      outline: none;
      position: absolute;
      z-index: -1;
      top: 0;
      left: 0px;
      right: 0;
      bottom: 0;
      margin: 0;
    }
  }

  .m-radio__label {
    font-size: 14px;
    padding-left: 10px;;
  }
}

// 选中的样式
.m-radio.is-checked{
  .m-radio__input{
    .m-radio__inner{
      border-color: #409eff;
      background-color: #409eff;
      &:after{
        transform: translate(-50%,-50%) scale(1);
      }
    }
  }

  .m-radio___label{
    color:#409eff;
  }
}
</style>
