<template>
  <div class="index">
    <CheckboxGroup style="flex-shrink: 0">
      <Checkbox
        class="checkbox_style"
        :indeterminate="indeterminate"
        :value="checkAll"
        :label="module.dgroupid"
        @click.prevent.native="handleCheckAll(module.devices)"
        ><span style="font-size: 14px; color: #333; font-weight: 700">{{
          module.dgname
        }}</span>
      </Checkbox>
    </CheckboxGroup>
    <CheckboxGroup
      v-model="checkAllSingleGroup"
      @on-change="checkAllSingleGroupChange"
    >
      <Checkbox
        v-for="mc in module.devices"
        :key="mc.deviceid"
        :label="mc.deviceid"
      >
        <span>{{ mc.deviceModel }}</span>
      </Checkbox>
    </CheckboxGroup>
  </div>
</template>
<script>
export default {
  name: "CheckboxDevice",
  props: ["module", "lsbid", "initdata"],
  data() {
    return {
      checkAll: false,
      indeterminate: false, //全选
      checkAllSingleGroup: [] //当前选中
    };
  },
  watch: {
    checkAllSingleGroup: function (val) {
      this.$emit("CheckboxDevice", this.module.dgroupid, val);
    },
    //清空回显
    initdata: function () {
      if (this.initdata) {
        this.checkAllSingleGroup = [];
        this.checkAll = false;
        this.indeterminate = false;
      }
    }
  },
  methods: {
    //全选或者全不选
    handleCheckAll(arr) {
      if (this.indeterminate) {
        this.checkAll = false;
      } else {
        this.checkAll = !this.checkAll;
      }
      this.indeterminate = false;
      let singleCheckedGroup = [];
      let singleObj = {};
      if (!Array.isArray(arr)) {
        return;
      }

      for (let i = 0; i < arr.length; i++) {
        singleObj = arr[i];
        singleCheckedGroup.push(singleObj.deviceid);
      }

      if (this.checkAll) {
        this.checkAllSingleGroup = singleCheckedGroup;
      } else {
        this.checkAllSingleGroup = [];
      }
    },
    //老师单独选择
    checkAllSingleGroupChange(data) {
      if (data.length === this.module.devices.length && data.length != 0) {
        this.indeterminate = false;
        this.checkAll = true;
      } else if (data.length > 0) {
        this.indeterminate = true;
        this.checkAll = false;
      } else {
        this.indeterminate = false;
        this.checkAll = false;
      }
    },
    //设置默认选中
    getCheckedDevices(val) {
      this.checkAllSingleGroup = [];
      this.module.devices.forEach((item) => {
        val.map((value) => {
          if (value.deviceid === item.deviceid) {
            this.checkAllSingleGroup.push(value.deviceid);
          }
        });
      });
      this.checkAllSingleGroupChange(this.checkAllSingleGroup);
    }
  }
};
</script>
<style lang="less" scoped>
.index {
  .checkbox_style {
    line-height: 36px;
  }
}
</style>
