<script setup name="RadioBlock">
import { ref, onMounted } from "vue";
const props = defineProps({
  col: Number,
  columns: {
    type: Array,
    default: () => [],
  },
  modelValue: {
    type: [String, Number],
    default: "",
  },
  name: {
    type: String,
    default: "",
  },
});

const selectIndex = ref(null);

const emit = defineEmits(["change", "update:modelValue"]);

onMounted(() => {
  if (props.modelValue) {
    selectIndex.value = props.modelValue;
  }
});

const onChange = (e) => {
  let value = +e.detail.value;
  if (Object.is(NaN, value)) {
    value = e.detail.value;
  }
  selectIndex.value = value;
  emit("update:modelValue", value);
  emit(
    "change",
    value,
    props.columns.find((item) => item.value === value)
  );
};
</script>

<template>
  <radio-group :name="name" @change="onChange">
    <view
      class="grid"
      :style="{
        gridTemplateColumns: `repeat(${col || columns.length}, 1fr)`,
      }"
    >
      <label
        class="radio"
        :class="{
          active: selectIndex === item.value,
        }"
        v-for="item in columns"
        :key="item.value"
      >
        <radio
          class="uni-radio"
          :value="item.value"
          :checked="selectIndex === item.value"
        />
        <view @click="selectIndex = item.value">
          {{ item.label }}
        </view>
      </label>
    </view>
  </radio-group>
</template>

<style scoped lang="scss">
@import "@/uni.scss";
.grid {
  display: grid;
  gap: 22rpx;

  .radio {
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1px solid #ccc;
    padding: 0 auto;
    font-weight: 500;
    font-size: 28rpx;
    color: #333333;
    border-radius: 8rpx;
    height: 60rpx;

    .uni-radio {
      width: 0;
      height: 0;
      opacity: 0;
    }
  }

  .radio.active {
    background-color: $primary;
    border-color: $primary;
    color: #fff;
  }
}
</style>
