<template>
    <el-checkbox-group v-model="selections" class="item">
      <el-checkbox :indeterminate="indeterminate" :label="data.id" @change="handleCheckAll">{{data.name}}</el-checkbox>
      <div class="item-children">
        <el-checkbox v-for="child in data.children" :label="child.id" :key="child.id" @change="val => handleCheckChild(val, child.id)">{{child.name}}</el-checkbox>
      </div>
    </el-checkbox-group>
</template>

<script>
import {union, intersection, includes} from 'lodash'
/**
 * 多选组件
 */
export default {
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    value: {
      type: Array,
      default: () => []
    },
    data: {
      type: Object,
      default: () => {}
    }
  },
  data(){
    return {
      selections: intersection(this.value || [], this.selectableIds)
    }
  },
  watch:{
    value(){
      this.selections = intersection(this.value || [], this.selectableIds)
    }
  },
  computed: {
    selectableIds(){
      return [this.data.id, ...this.data.children.map(({id}) => id)]
    },
    restIds(){
      return this.value.filter(id => !includes(this.selectableIds, id))
    },
    indeterminate(){
      return this.selections.length > 0 && this.selections.length < this.selectableIds.length
    }
  },
  methods:{
    handleCheckAll(val){
      this.selections = val ? this.selectableIds: []
      this.$emit('change', union(this.restIds, this.selections))
    },
    handleCheckChild(val, id){
      if (val) {
        this.selections = union(this.selections, [this.data.id])
      }
      // 子元素全部取消则去除父元素选中状态
      if (this.selectableIds.length > 1 && this.selections.length === 1) {
        this.selections = []
      }
      this.$emit('change', union(this.restIds, this.selections))
    }
  }
}
</script>

<style scoped>
.item{
  width: 100%;
  padding: 20px 40px;
  margin-bottom: 20px;
  background-color: rgb(242, 242, 242);
}
.item-children{
  padding: 20px 40px;
}
</style>
