<template>
  <el-radio-group :size="size" v-model="model" :disabled="disabled" @change="handleChange">
    <template v-for="item in option">
      <el-radio-button v-if="mode === 'button'" :key="item[valueProps.value]" :label="item[valueProps.value]">{{ item[valueProps.label] }}</el-radio-button>
      <el-radio v-else :key="item[valueProps.value]" :label="item[valueProps.value]" :border="mode === 'border'">{{ item[valueProps.label] }}</el-radio>
    </template>
  </el-radio-group>
</template>
<script>
  export default {
    name: 'RadioGroup',
    props: {
      // 大小
      size: String,
      // 组件值
      value: [Boolean, String, Number],
      // 选择框禁用状态
      disabled: {
        type: Boolean,
        default: false
      },
      // 数据源
      dataSource: {
        type: [Promise, Function, Array],
        required: true,
      },
      // 数据格式
      valueProps: {
        type: Object,
        default: () => {
          return { value: 'value', label: 'label' };
        }
      },
      // 模式 normal button border
      mode: {
        type: String,
        default: 'normal'
      }
    },
    data () {
      return {
        // 绑定值
        model: undefined,
        // 数据源
        option: [],
      };
    },
    watch: {
      value(val) {
        this.model = val;
      },
    },
    mounted() {
      this.model = this.value;
      this.queryData();
    },
    methods: {
      // 查询树数据
      async queryData() {
        if (this.dataSource instanceof Array) {
          this.option = this.dataSource;
        } else {
          this.option = await this.dataSource();
        }
      },
      // 选择
      handleChange(value) {
        this.$emit('input', value);
        this.$emit('change', value);
      },
    }
  };
</script>