<template>
  <span>
    <a-checkbox
      :indeterminate="indeterminate"
      @change="onCheckAllChange"
      :checked="checkAll"
    >
      全选
    </a-checkbox>
    <a-checkbox-group
      v-model="checkedList"
      @change="onChange"
    >
      <a-checkbox
        :value="item.value"
        v-for="(item,index) in selfOptions"
        :key="index"
      >
        {{ item.name }}
      </a-checkbox>
    </a-checkbox-group>
  </span>
</template>

<script>
export default {
  props: {
    value: {
      type: Array,
      default: () => []
    },
    options: {
      type: [Array, Object],
      default: () => null
    }
  },
  data () {
    return {
      indeterminate: false,
      checkAll: false,
      checkedList: [],
      selfOptions: []
    }
  },
  methods: {
    onChange (checkedList) {
      this.indeterminate = !!checkedList.length && (checkedList.length < this.selfOptions.length)
      this.checkAll = checkedList.length === this.selfOptions.length
      this.$emit('input', this.checkedList)
    },
    onCheckAllChange (e) {
      Object.assign(this, {
        checkedList: e.target.checked ? this.selfOptions.map(i => i.value) : [],
        indeterminate: false,
        checkAll: e.target.checked
      })
      this.$emit('input', this.checkedList)
    }
  },
  watch: {
    value (val) {
      this.checkedList = val
    },
    options: {
      handler (val) {
        if (Array.isArray(val)) {
          this.selfOptions = val
        } else {
          this.selfOptions = []
          for (const key in val) {
            this.selfOptions.push({ value: key, name: val[key] })
          }
        }
      },
      immediate: true
    }
  }
}
</script>

<style scoped>

</style>
