<template>
  <div class="goods-brand">
    <div class="check-title">
      <el-checkbox
        :indeterminate="isIndeterminate"
        v-model="checkAll"
        @change="handleCheckAllChange"
      >全部选择</el-checkbox>
    </div>

    <el-checkbox-group
      v-model="checkedBrandes"
      @change="handleCheckedBrandChange"
      class="brand-group"
    >
      <el-checkbox
        v-for="brand in brandes"
        :label="brand.brandName"
        :key="brand.id"
        class="brand-list"
      >{{ brand.brandName }}</el-checkbox>
    </el-checkbox-group>
    <slot></slot>
  </div>
</template>

<script>
import ElCollapseTransition from "./collapse-transition";
import Emitter from "@/mixins/emitter";
// 品牌
export default {
  name: "goods-brand",

  mixins: [Emitter],

  components: {
    ElCollapseTransition
  },

  props: {
    goodsBrands: Array,
    goodsIndex: Array
  },

  data() {
    return {
      isIndeterminate: false,
      checkAll: false,
      checkedBrandes: [],
      brandes: []
    };
  },

  methods: {
    // 全选
    handleCheckAllChange(val) {
      this.checkedBrandes = val ? this.brandes : [];
      this.isIndeterminate = false;
    },

    // 复选框多选
    handleCheckedBrandChange(val) {
      let checkCount = val.length;
      this.checkAll = checkCount === this.brandes.length;
      this.isIndeterminate = checkCount > 0 && checkCount < this.brandes.length;
      // 传值出去
      this.dispatch("goods-selector", "pass-checkbox", {
        index: this.goodsIndex,
        val: val
      });
    },
    getBrandList() {
      const param = {
        currentPage: 1,
        pageSize: 20
      };
      this.axios
        .get(`${this.baseUrl}/api-goods/brandlist?requestProject=goods`, {
          params: param
        }).then(res => {
          let data;
          if (res.data.errorCode === 0) {
            data = res.data.result;
            this.brandes = data.result;
            // 如果超过了20条 totalCount 是总数 根据总数来判断是否还要继续展示第二页的 并不适合全选
          } else {
            this.$message.error(res.data.message);
          }
        }).catch(err => {
          this.$message.error(error);
        });
    }
  },

  beforeMount() {
    // 获取品牌列表
    this.baseUrl = window.location.origin.includes("localhost")
      ? "http://gicdev.demogic.com"
      : window.location.origin;
    this.getBrandList();
  },

  watch: {
    goodsBrands: {
      immediate: true,
      handler(newval) {
        this.checkedBrandes = newval;
      }
    }
  }
};
</script>


<style src="./style/brand.less" lang="less" scoped></style>