<template>
  <v-radio-group v-bind="attrs" :modelValue="modelValue" @update:modelValue="onUpdate">
    <v-radio
      v-for="item in items"
      :key="item.id || item.code"
      :label="item.codeValue"
      :value="item.code"
    />
  </v-radio-group>
</template>

<script setup>
import { ref, onMounted, useAttrs } from 'vue';
import Request from '@/commons/request';

// 定义组件名称
defineOptions({
  name: "VtkRadio",
  inheritAttrs: false,
});
// 定义 props
const props = defineProps({
  /**
   * 字典来源：
   * - 静态数据，如："0:否/1:是"
   * - 字典键名，如："DISABLE_TYPE"
   */
  list: {
    type: String,
    required: true,
  },
  modelValue: {
    type: [String, Number],
    default: null,
  },
});

// 定义 emit 事件
const emit = defineEmits(['update:modelValue']);

// 获取透传属性（替代 $attrs）
const attrs = useAttrs();

// 响应式数据
const items = ref([]);

// 处理静态数据
const statc = () => {
  props.list.split('/').forEach(it => {
    const [code, codeValue] = it.split(':');
    items.value.push({ code, codeValue });
  });
};

// 请求远程字典
const miscs = async () => {
  try {
    const res = await Request.getForm(`dict/misc/list/${props.list}`);
    items.value = res.data || [];
  } catch (error) {
    console.error('[VtkRadio] Failed to load dictionary:', error);
    items.value = [];
  }
};

// 更新 v-model 值
const onUpdate = (val) => {
  emit('update:modelValue', val);
};

// 初始化数据
onMounted(() => {
  if (props.list.includes(':')) {
    statc();
  } else {
    miscs();
  }
});
</script>

<style scoped>
</style>