<template>
  <div class="el-checkbox-group">
    <label class="el-checkbox" v-for="(item, index) in options" :key="index">
      <input
        type="checkbox"
        :name="_name"
        :checked="isChecked(item)"
        @change="
          (event) => {
            handeChange(event, item, index);
          }
        "
      />{{ labelKey ? item[labelKey] : item.name || item.label }}
    </label>
  </div>
</template>
<script>
export default {
  name: 'EoCheckbox',
  props: {
    field: {
      required: true,
      type: String
    },
    prop: String,
    index: Number,
    labelKey: String,
    valueKey: String,
    data: {
      type: Object,
      default() {
        return {};
      }
    },
    options: {
      type: Array,
      default() {
        return [];
      }
    },
    decollator: {
      type: String,
      default: ','
    },
    valueToString: Boolean,
    value: {}
  },
  data() {
    return {
      _value: this.value
    };
  },
  computed: {
    model: {
      get() {
        if (Array.isArray(this.value)) {
          return this.value;
        }
        if (typeof this.value === 'string') {
          return this.value.split(this.decollator);
        }
        return [this.value];
      }
      // set(val) {
      //   this.$emit(
      //     'input',
      //     this.valueToString ? val.join(this.decollator) : val
      //   );
      //   return val;
      // }
    },
    _name() {
      if (this.index !== undefined) {
        return `${this.field || this.prop}[${this.index}]`;
      }
      return this.field || this.prop;
    }
  },
  methods: {
    isChecked(res) {
      return this.valueKey
        ? this.model.indexOf(res[this.valueKey]) > -1
        : this.model.indexOf(res.value) > -1;
    },
    handeChange(event, res, index) {
      let val = this.model;
      if (event.target.checked) {
        if (val.length > index) {
          val.splice(index, 0, this.valueKey ? res[this.valueKey] : res.value);
        } else {
          val.push(this.valueKey ? res[this.valueKey] : res.value);
        }
      } else {
        let i = val.indexOf(this.valueKey ? res[this.valueKey] : res.value);
        val.splice(i, 1);
      }
      this.$emit('input', this.valueToString ? val.join(this.decollator) : val);
    }
  }
};
</script>
