<template>
  <div class="main">
    <el-card
      v-for="(item, index) in data"
      :key="index"
      shadow="always"
      :body-style="{padding: 0}"
    >
      <app-item
        ref="appItem"
        :data="item"
        @command="handleCommand"
        @check-change="handleCheckChange"
        @card-click="cardClick"
      ></app-item>
    </el-card>
  </div>
</template>

<script>
const AppItem = () => import('./AppItem')
export default {
  name: 'AppCardView',
  components: {
    AppItem,
  },
  props: {
    data: Array,
  },
  watch: {
    data: {
      handler() {
        this.refreshItem()
        this.handleCheckChange()
      },
    },
  },
  methods: {
    cardClick(data) {
      this.$emit('card-click', data)
    },
    handleCommand(data) {
      this.$emit('command', data)
    },
    handleCheckChange() {
      let selection = !!this.$refs.appItem
        ? this.$refs.appItem
            .filter((item) => item.checked)
            .map((item) => item.data)
        : []
      this.$emit('selection-change', selection)
    },
    refreshItem() {
      this.$refs.appItem &&
        this.$refs.appItem.forEach((item) => {
          item.refresh()
        })
    },
    selectAll(checked) {
      this.$refs.appItem &&
        this.$refs.appItem.forEach((item) => {
          item.handleChecked(checked)
        })
    },
    selectedAll() {
      let appItems = this.$refs.appItem || []
      let checkedLength = appItems.filter((item) => item.checked).length
      return checkedLength === appItems.length
    },
    indeterminate() {
      let appItems = this.$refs.appItem || []
      let checkedLength = appItems.filter((item) => item.checked).length
      return checkedLength > 0 && checkedLength < appItems.length
    },
  },
}
</script>

<style lang="scss" scoped>
.main {
  &::after {
    content: '';
    display: block;
    clear: both;
  }

  .el-card {
    float: left;
    margin-right: 16px;
    margin-bottom: 16px;
  }
}
</style>
