<template>
  <div class="l-flex--col c-runtime">
    <div class="l-flex--row l-flex__none has-bottom-padding">
      <i class="l-flex__none c-runtime__icon download" />
      <span class="l-flex__fill c-runtime__title u-ellipsis">文件下载</span>
      <i
        v-if="count"
        class="l-flex__none c-runtime__list 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="large">{{ 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>
