<template>
  <div class="file-container">
    <el-card class="top-box">
      <div slot="header" class="clearfix card-header">
        <span>排行榜</span>
      </div>
      <el-scrollbar class="top-scrollbar">
        <div v-loading="topLoading" class="top-item-box">
          <div v-for="(item, index) in topData" :key="item.id" class="top-item">
            <div class="item-default">
              <div :class="['top-rank', index<=2 ? 'top-rank_'+index : '']">{{ index + 1 }}</div>
              <div>
                <!-- <div class="top-name">{{ item.fileName }}</div> -->
                <ellipsis-tooltip :content="item.fileName" placement="top" class="top-name" width="270px">
                  <a style="cursor: text">{{ item.fileName }}</a>
                </ellipsis-tooltip>
                <div>
                  <span class="top-size">{{ formatBytes(item.size) }}</span>
                  <span class="top-count">{{ formatCount(item.downloads) }}次下载</span>
                </div>
              </div>
              <el-button type="primary" size="small" style="width:56px">下载</el-button>
            </div>
          </div>
        </div>
      </el-scrollbar>
    </el-card>
    <el-card class="file-box">
      <div slot="header" class="clearfix card-header">
        <span>软件下载</span>
        <el-button type="primary" size="small" class="header-upload-btn" @click="showUpload">上传</el-button>
      </div>
      <div class="list-filter">
        <el-form ref="filterForm" :model="formData" inline>
          <el-form-item label="名称">
            <el-input v-model="formData.fileName" class="filter-item" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchTable">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-tabs v-model="curTab" class="list-tabs" @tab-click="getTablelist">
        <el-tab-pane v-for="typeItem in typeData" :key="dictType + '-' + typeItem.id" :label="typeItem.label" :name="typeItem.id + ''">
          <div v-loading="loading" class="list-box">
            <el-scrollbar class="list-scrollbar">
              <div class="list-item-box">
                <div v-for="item in tableData" :key="item.id" class="list-item">
                  <div class="item-content">
                    <!-- <el-avatar :size="56" :src="item.icon | formatImgUrl" class="item-icon" /> -->
                    <div class="item-title">
                      <div class="item-name">{{ item.fileName }}</div>
                      <div class="item-system">上传时间：{{ item.createTime }}</div>
                    </div>
                  </div>
                  <div class="item-tip">
                    <span>大小：{{ formatBytes(item.size) }}</span>
                    <span>下载量：{{ formatCount(item.downloads) }}次</span>
                  </div>
                  <div class="item-footer">
                    <el-button type="text" size="small" @click="downloadItem(item)">下载</el-button>
                    <el-button type="text" size="small" @click="deleteItem(item.id)">删除</el-button>
                  </div>
                </div>
              </div>
            </el-scrollbar>
            <div v-if="total > 0" class="page">
              <el-pagination
                layout="total, sizes, prev, pager, next, jumper"
                :current-page="current"
                :total="total"
                :page-sizes="pageSizeAll"
                :page-size="size"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-dialog
      v-loading="uploadLoading"
      :visible.sync="visible"
      :close-on-press-escape="true"
      :close-on-click-modal="false"
      :show-close="false"
      destroy-on-close
      custom-class="main-edit-dialog file-upload-dialog"
      title="软件上传"
    >
      <el-form :ref="formName" :model="formData" :rules="rules" label-width="100px">
        <el-form-item prop="type" label="软件类型">
          <el-select v-model="formData.type" placeholder="请选择">
            <el-option v-for="item in typeData" :key="item.id" :label="item.label" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item prop="fileName" label="上传软件" style="height: 100px;">
          <upload-file ref="uploadFile" :file-type="formData.type" :upload-change="uploadChange" :auto-upload="false" :on-success="uploadSuccess" :on-error="uploadError" />
          <div>{{ formData.fileName }}</div>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="saveFile">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchDictData } from '@/api/dict'
import { fetchFileList, fetchTopN, pushDeleteFile } from '@/api/file'

import { hasValidRecords, formatDictData, isNull } from '@/utils/convert'
import { formatBytes, formatCount } from '@/utils'

import EllipsisTooltip from '@/components/EllipsisTooltip'
import UploadFile from '@/components/Upload/UploadFile.vue'

export default {
  name: 'Application',
  components: {
    EllipsisTooltip,
    UploadFile
  },
  data() {
    return {
      // type
      dictType: 'software_type',
      typeData: [],
      // top N
      topN: 50,
      topData: [],
      // table
      current: 1,
      size: 16,
      total: 0,
      pageSizeAll: [10, 16, 20, 50, 100, 200, 500],
      tableData: [],
      // filter
      formData: {
        type: null,
        fileName: ''
      },
      rules: {
        type: [
          { required: true, message: '请选择软件类型', trigger: 'change' }
        ],
        fileName: [
          { required: true, message: '请选择软件', trigger: 'change' }
        ]
      },
      // dialog
      visible: false,
      formName: 'uploadForm',
      // others
      curTab: '',
      loading: false,
      topLoading: false,
      uploadLoading: false
    }
  },
  created() {
    this.getTypeData()
    this.searchTable()
  },
  methods: {
    // 改变每页显示条数
    handleSizeChange(val) {
      this.current = 1
      this.size = val
      this.getTablelist()
    },
    // 切换第几页
    handleCurrentChange(val) {
      this.current = val
      this.getTablelist()
    },
    // 重置搜索项
    resetTable(formName) {
      this.$refs[formName].resetFields()
      this.getTablelist()
    },
    // 点击搜索按钮
    searchTable() {
      this.current = 1
      this.getTablelist()
    },
    // 获取table数据
    getTablelist() {
      this.formData.type = parseInt(this.curTab)
      const params = {
        page: this.current,
        size: this.size,
        params: {
          delFlag: 0,
          type: this.curTab,
          fileName: this.formData.fileName
        }
      }
      this.loading = true
      fetchFileList(params).then(response => {
        if (hasValidRecords(response)) {
          this.tableData = response.data.records
          this.total = response.data.total
        } else {
          this.tableData = []
          this.total = 0
        }
        this.loading = false
      }).catch(error => {
        console.log(error)
        this.loading = false
        this.$message.error({
          type: 'error',
          duration: 0,
          showClose: true,
          message: ': ' + error.message
        })
      })
    },
    downloadItem(item) {
      window.open(item.url, '_blank')
      item.downloads++
    },
    deleteItem(id) {
      this.loading = true
      pushDeleteFile(id).then(res => {
        this.getTablelist()
      }).catch(error => {
        console.log(error)
        this.loading = false
        this.$message.error({
          type: 'error',
          duration: 0,
          showClose: true,
          message: '删除软件出错: ' + error.message
        })
      })
    },
    getTopNData() {
      const typeIds = this.typeData.map(item => item.id).join(',')
      fetchTopN(typeIds, this.topN).then(res => {
        if (!isNull(res.data)) {
          this.topData = res.data
        } else {
          this.topData = []
        }
        this.topLoading = false
      }).catch(error => {
        console.log(error)
        this.topLoading = false
        this.$message.error({
          type: 'error',
          duration: 0,
          showClose: true,
          message: ': ' + error.message
        })
      })
    },
    getTypeData() {
      this.topLoading = true
      fetchDictData(this.dictType).then(response => {
        if (!isNull(response.data)) {
          this.typeData = response.data

          this.curTab = this.typeData[0].id + ''
          this.formData.type = parseInt(this.curTab)

          this.getTopNData()
          this.searchTable()
        } else {
          this.typeData = []
        }
      }).catch(error => {
        console.log(error)
        this.topLoading = false
        this.$message.error({
          type: 'error',
          duration: 0,
          showClose: true,
          message: ': ' + error.message
        })
      })
    },
    // dialog
    showUpload() {
      this.visible = true
    },
    close() {
      this.visible = false
    },
    // Upload
    uploadSuccess() {
      this.uploadLoading = false
      this.formData.fileName = ''
      this.visible = false
      this.searchTable()
    },
    uploadError(error) {
      this.uploadLoading = false
      this.$message.error({
        type: 'error',
        duration: 0,
        showClose: true,
        message: '上传软件出错：' + error.message
      })
    },
    uploadChange(file) {
      if (file.status === 'ready') {
        this.formData.fileName = file.name
      }
    },
    saveFile() {
      this.$refs[this.formName].validate((valid) => {
        if (valid) {
          this.uploadLoading = true
          this.$refs['uploadFile'].submit()
        }
      })
    },
    formatDictData(type) {
      return formatDictData(this.typeData, type)
    },
    formatBytes(size) {
      return formatBytes(size)
    },
    formatCount(count) {
      return formatCount(count)
    }
  }
}
</script>

<style lang="scss" scoped>
.file-container {
  display: flex;

  ::v-deep {
    .el-card__header {
      height: 56px;
      padding: 12px 20px;
    }
    .el-card__body {
      height: calc(100% - 56px);
      padding: 10px 0px 10px 20px;
    }

    .el-scrollbar__wrap{
      overflow-x: hidden;
    }

    .el-scrollbar__bar.is-horizontal {
      display: none;
    }
  }

  .card-header {
    font-size: 18px;
    line-height: 32px;
    height: 32px;
    color: rgba(0,0,0,0.85);
    font-weight: bold;
  }

  .header-upload-btn {
    float: right;
    height: 32px;
    font-size: 14px;
  }

  .top-box {
    width: 400px;
    min-width: 400px;
    height: 100%;
    margin-right: 5px;
  }

  .top-scrollbar {
    height: 100%;
  }

  .top-item-box {
    margin-right: 10px;
  }

  .item-default {
    height: 50px;
    display: flex;
    // justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid rgba(0,0,0,0.1);
    color: rgba(0,0,0,0.85);

    &>div {
      display: inline-block;
      margin-right: 10px;
    }
    .top-rank {
      width: 20px;
      text-align: center;
    }
    .top-rank_0 {
      background-color: #F63842;
      border-radius: 1px;
      color: #f0f0f0;
    }
    .top-rank_1 {
      background-color: #FB982D;
      border-radius: 1px;
      color: #f0f0f0;
    }
    .top-rank_2 {
      background-color: #FADB14;
      border-radius: 1px;
      color: #8e8686;
    }

    .top-name {
      width: 270px;
      margin-bottom: 5px;
    }
    .top-size,.top-count{
      color: rgba(0,0,0,0.45);
      font-size: 14px;
    }
    .top-size {
      display: inline-block;
      padding-right: 5px;
      border-right: 1px solid rgba(0,0,0,0.1);
      margin-right: 5px;
    }
  }

  .file-box {
    background-color: #fff;
    width: 100%;
    height: 100%;
    min-width: 875px;

    .upload-btn {
      display: inline-block;
      margin-left: 10px;
    }

    .page {
      margin-right: 20px;
      text-align: right;
    }
  }

  .list-filter {
    height: 60px;
  }

  .list-tabs {
    height: calc(100% - 60px);

    ::v-deep {
      .el-tabs__content {
        height: calc(100% - 55px);
      }
      .el-tab-pane {
        height: 100%;
      }
    }
  }

  .list-box {
    height: 100%;
  }

  .list-scrollbar {
    height: calc(100% - 32px);
  }

  .list-item-box {
    display: flex;
    flex-wrap: wrap;
  }

  .list-item {
    width: 325px;
    height: 150px;
    border: 1px solid rgba(0,0,0,0.09);
    border-radius: 4px;
    margin-right: 16px;
    margin-bottom: 16px;
    padding: 10px 10px 0 10px;

    .item-content {
      display: flex;
      align-items: center;
      height: calc(100% - 72px);
    }

    .item-icon {
      margin-right: 10px;
    }

    .item-title {

      .item-name, .item-system {
        width: 240px;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
      }

      .item-name {
        font-size: 15px;
        font-weight: 550;
        color: rgba(0,0,0,0.85);
      }

      .item-system {
        font-size: 14px;
        color: rgba(0,0,0,0.65);
        margin-top: 5px;
      }
    }

    .item-tip {
      height: 32px;
      color: rgba(0,0,0,0.65);
      font-size: 14px;
      &>span{
        display: inline-block;
        line-height: 32px;
        width: 150px;
      }
    }

    .item-footer {
      height: 34px;
      width: 100%;
      color: rgba(0,0,0,0.85);
      border-top: 1px solid rgba(0,0,0,0.10);
      text-align: center;

      .el-button {
        width: calc(50% - 5px);
        color: rgba(0,0,0,0.85);
        font-size: 14px;
      }
      .el-button+.el-button {
        border-left: 1px solid rgba(0,0,0,0.10);
      }
    }
  }
}
</style>

