<template>
  <div :class="['ipub-radio-group','ipub-radio-group'+ (col?'--col':'')]">
    <slot>
      <template v-if="options && options.length">
        <ipub-radio @change="handleChange"
                    class="ipub-radio-group__item"
                    v-for="(item ,index) in options"
                    :value="item[_value]"
                    :label="item[_label]"
                    :checkBox="checkBox"
                    :checked="currentValue === item.value"
                    :key="'ipub-radio-group'+(item.id||item.label||index)" />
      </template>
    </slot>
  </div>
</template>

<script>
import IpubRadio from './main'
export default {
  name: 'IpubRadioGroup',
  components: {
    IpubRadio
  },
  // 传递属性给子组件
  provide () {
    return {
      theme: this// 方法一：提供祖先组件的实例
    };
  },
  props: {
    value: {
      type: [String, Number, Object, Boolean, Array],
      default: ''
    },
    options: {
      type: Array,
      default () {
        return []
      }
    },
    _label: {
      type: String,
      default: 'label'
    },
    _value: {
      type: String,
      default: 'value'
    },
    checkBox: Boolean,
    col: Boolean
  },
  watch: {
    value: {
      handler (val) {
        this.currentValue = val
      },
      immediate: true
    }
  },
  data () {
    return {
      currentValue: ''
    }
  },
  methods: {
    handleChange (val) {
      if (this.checkBox) {
        const index = this.currentValue.indexOf(val)
        if (index >= 0) {
          this.currentValue.splice(index, 1)
        } else {
          this.currentValue = this.currentValue || []
          this.currentValue.push(val)
        }
        this.$emit('input', this.currentValue)
        this.$emit('change', this.currentValue)
      } else {
        this.currentValue = (val || val === false || val === 0) ? val : ''
        this.$emit('input', this.currentValue)
        this.$emit('change', this.currentValue)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.ipub-radio-group {
  &--col {
    .ipub-radio-group__item {
      margin-left: 0;
      display: flex;
      margin-bottom: 6px;
    }
  }
}
</style>
