<script setup lang="ts">
import type { CheckboxValueType } from 'element-plus'

const props = withDefaults(
  defineProps<{
    modelValue: any
    options: any[]
    labelKey?: string
    valueKey?: string
  }>(),
  {
    labelKey: 'label',
    valueKey: 'value',
  },
)

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

defineOptions({ name: 'MjRadio' })

const value = computed({
  get: () => props.modelValue,
  set: val => emit('update:modelValue', val),
})

// 勾选的value
const checkedMap = ref({} as any)

// 用户操作数据 -> 外部数据
function _map2values(id: any) {
  value.value = id
}

// 数据流向
// 1.界面操作 -> checkedMap -> value -> checkedMap
// 2.外部数据传递 -> value -> checkedMap -> 界面显示
watch(
  [() => value.value, () => props.options],
  () => {
    if (!props.options.length) return

    // 控制界面显示
    checkedMap.value = {}
    checkedMap.value[value.value] = true
  },
  {
    immediate: true,
  },
)
</script>

<template>
  <div class="mj-radio">
    <mj-check
      v-for="op in options"
      :key="op[valueKey]"
      v-model="checkedMap[op[valueKey]]"
      :value="op[valueKey]"
      :label="op[labelKey]"
      @change="_map2values(op[valueKey])"
    />
  </div>
</template>

<style lang="scss" scoped>
.mj-radio {
  display: flex;
  flex-wrap: wrap;
  column-gap: 12px;
  row-gap: 1.33vh;
  padding: 0.67vh 0;
}
</style>
