<template>
  <div>
    <el-checkbox 
      :indeterminate="isIndeterminate" 
      v-model="checkAll" 
      @change="handleCheckAllChange">全选</el-checkbox>
    <div style="margin: 15px 0;"></div>
    <el-checkbox-group v-model="checkedList" @change="handleChange">
      <div v-for="n in boxList" :key="n.itemId" class="mb10">
        <el-checkbox :label="n.itemId">{{n.label}}</el-checkbox>
      </div>
    </el-checkbox-group>
  </div>
</template>

<script>
export default {
  name: 'checkBox',
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    value: {
      type: Array,
      default: () => []
    },
    list: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      boxList: [],
      checkAll: false,
      checkedList: [],
      isIndeterminate: true,
      pid: '',
    }
  },
  created() {
    this.boxList = this.list.filter(item => item.itemType != 'inputRange')
    this.pid = this.list[0].itemGroupId
  },
  methods: {
    handleCheckAllChange(val) {

      this.checkedList = val ? this.boxList.map(item => item.itemId) : [];
      this.isIndeterminate = false;
      
      this.$emit('change', { list: this.filterArr(this.checkedList), pid: this.pid })
    },
    handleChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.list.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.boxList.length;
      this.$emit('change', { list: this.filterArr(this.checkedList), pid: this.pid })
    },
    filterArr(arr) {
      let list = []
      arr.forEach(item => {
        this.boxList.forEach(n => {
          if (item === n.itemId) list.push(n)
        })
      })
      return list
    }
  }
}
</script>

<style lang="scss" scoped>
.mb10 {
  margin-bottom: 10px;
}
</style>