<template>
  <el-checkbox-group ref="elCheckboxGroupRef" multiple :value="value" :size="size" @input="updateVal($event)" v-bind="checkboxGroupProps">
    <el-checkbox
      ref="elCheckboxRef"
      v-for="(item, index) in checkboxData[checkboxKey]"
      v-bind="checkboxProps"
      :label="item[props['value']]" :key="index">
      {{ item[props['label']] }}
    </el-checkbox>
  </el-checkbox-group>
</template>

<script>
  import {componentConfig} from '@/comps/mixin/component-config'

  export default {
    inheritAttrs: false,
    name: 'CmsCheckboxGroup',
    mixins: [componentConfig],
    props: {
      checkboxData: {
        type: Object,
        required: true,
        default: () => {
          return {}
        }
      },
      checkboxKey: {
        type: String,
        required: true,
        default: () => {
          return undefined
        }
      },
      // //此处一定要用value
      value: {
        type: [String, Number, Boolean, Array],
        default: () => {
          return ''
        }
      },
      props: {
        type: Object,
        default: () => {
          return {label: 'label', value: 'value'}
        }
      }
    },
    data() {
      return {
        checkboxGroupProps: {},
        checkboxProps: {},
      }
    },
    created() {
    },
    mounted() {
      const elCheckboxGroupProps = this.$refs.elCheckboxGroupRef.$props;
      Object.keys(elCheckboxGroupProps).forEach(prop => this['group' + this.capitalizeFirstUpper(prop)] = elCheckboxGroupProps[prop])
      this.$refs.elCheckboxRef.forEach(elCheckbox => {
        const elCheckboxProps = elCheckbox.$props;
        Object.keys(elCheckboxProps).forEach(prop => this['checkbox' + this.capitalizeFirstUpper(prop)] = elCheckboxProps[prop])
      })
      console.log(this);
      Object.keys(this.$attrs).filter(prop => {
        if (prop.startsWith('group')) {
          const propName = this.lowercaseFirstLetter(prop.substring('group'.length));
          this.checkboxGroupProps[propName] = this.$attrs[prop];
        }
        if (prop.startsWith('checkbox')) {
          const propName = this.lowercaseFirstLetter(prop.substring('checkbox'.length));
          this.checkboxProps[propName] = this.$attrs[prop];
        }
      })
    },
    methods: {
      // 首字母大写
      capitalizeFirstUpper(string) {
        return string.toLowerCase().replace(/\b[a-z]/g, function(match) {
          return match.toUpperCase();
        });
      },
      lowercaseFirstLetter(string) {
        return string.charAt(0).toLowerCase() + string.slice(1);
      },
      updateVal(val) {
        this.$emit('input', val) // 通过事件实现组件属性到父组件的传递
      },
    }
  }
</script>

<style scoped>

</style>
