<template>
  <div class="l-flex--col o-device-grid-item has-border radius">
    <div class="l-flex--row l-flex__none has-bottom-padding">
      <i class="l-flex__none o-device-grid-item__icon o-icon medium has-bg" />
      <span class="l-flex__fill u-color--info u-ellipsis">文件下载</span>
      <i
        v-if="count"
        class="l-flex__none o-device-grid-item__large u-color--blue el-icon-s-operation u-pointer"
        @click="showDownload"
      />
    </div>
    <div class="l-flex__fill u-text-center">
      <div class="has-bottom-padding">当前已下载文件</div>
      <div class="u-color--black">
        <span class="o-device-grid-item__largest">{{ downloadCount }}</span> 个
      </div>
    </div>
    <div
      v-if="count !== downloadCount"
      class="l-flex__none u-color--error dark u-bold u-text-center"
    >
      正在下载文件...
    </div>
    <el-dialog
      title="文件下载详情"
      :visible.sync="showProgress"
      custom-class="c-dialog"
      append-to-body
    >
      <download-progress @update="onUpdate" />
    </el-dialog>
  </div>
</template>

<script>
import {
  addListener,
  removeListener
} from '../../monitor'
import DownloadProgress from './DownloadProgress'

export default {
  name: 'DeviceDownload',
  components: {
    DownloadProgress
  },
  data () {
    return {
      showProgress: false,
      count: 0,
      downloadCount: 0,
      loading: false
    }
  },
  created () {
    addListener('download', this.onUpdate)
  },
  beforeDestroy () {
    removeListener('download', this.onUpdate)
  },
  methods: {
    onUpdate (files) {
      this.count = files.length
      this.downloadCount = files.filter(({ complete, success }) => complete && success).length
      this.loading = files.some(({ complete }) => !complete)
    },
    showDownload () {
      this.showProgress = true
    }
  }
}
</script>

<style lang="scss" scoped>
.o-device-grid-item__icon {
  background-image: url("~@/assets/icon_download.png");
}
</style>
