<template>
  <div class="components_upload">
    <!-- 上传文件 -->
    <div class="">
      <el-button class="cont_upload_btn" round type="primary">上传</el-button>
      <input id="upFile" type="file" name="upFile" @change="changeFile($event)" />
      <!-- <img v-if="coverUrl" :src="coverUrl" alt="封面" /> -->
      <!-- <el-progress :percentage="filePercent" />
      {{ filePercent }} -->
    </div>

    <!-- 上传封面 -->
    <el-upload action="#" list-type="picture-card" :auto-upload="false">
      <!-- <i slot="default" class="el-icon-plus"></i> -->
      <img src="@/assets/images/t-sc.png" alt />
      <div slot="file" slot-scope="{file}">
        <img class="el-upload-list__item-thumbnail" :src="file.url" alt />
      </div>
    </el-upload>

    <!-- 上传列表layer -->
    <div class="upload_layer">
      <!-- width="736px" -->
      <el-dialog
        title="上传列表"
        :close-on-click-modal="false"
        :show-close="false"
        :visible.sync="uploadListVisible"
        height="384px"
      >
        <!-- :status="percentage === 100 ? undefined : 'success'" -->
        <el-table :data="fileData" :header-cell-style="{ color: '#333' }">
          <el-table-column align="center" prop="fileNames" label="文件名" />
          <el-table-column align="center" prop="formatType" label="类型" />
          <el-table-column align="center" prop="fileSize" label="大小" />
          <el-table-column align="center" prop="filePercentTxt" label="状态">
            <template>
              <div class="loadingModal" :style="{ 'height': '100%' }">
                <!-- :format="format" -->
                <!-- <el-progress
                  :stroke-width="6"
                  :percentage="filePercent"
                  :color="colors"
                /> -->
                {{ filePercentTxt }}
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="handle" label="操作">
            <template slot-scope="scope">
              <el-button
                type="primary"
                round
                class="on_off_btn"
                @click="end(scope.$index, scope.row)"
              >{{ loading_txt }}</el-button>
              <el-button
                type="info"
                round
                class="upload_delt"
                @click="handleRecord(scope.$index, scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="upload_list_right">
          <!-- <el-upload
            class="upload-demo"
            action="https://jsonplaceholder.typicode.com/posts/"
            multiple
            :limit="3"
          >
            <div class="right_upload">点击上传</div>
          </el-upload> -->
          <input type="button" name="开始上传" value="开始上传" @click="uploadFile()" />
          <div class="upload_return" @click="uploadListVisible=false">返回</div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import * as qiniu from 'qiniu-js'
import { getQiniuToken } from '@/api/material/material'
export default {
  name: 'Qiniu',
  data() {
    return {
      file: null,
      token: '',
      baseurl: 'qiniu.aiyxlib.com',
      fileData: [],
      uploadFileUrl: null,
      filePercent: 0,
      fileNames: '',
      formatType: '',
      postfix: '',
      fileSize: '',
      uploadListVisible: false,
      loading_txt: '暂停',
      colors: '#1e9f4c',
      uploadListData: [],
      filePercentTxt: '上传中'
    }
  },
  mounted() {
    this.getQiniuToken()
  },
  methods: {
    changeFile(e) {
      // 获取文件
      this.file = e.target.files[0]
      this.formatType = this.file.type.substring(0, this.file.type.indexOf('/'))
      console.log('formatType', this.formatType)
      this.fileNames = this.file.name
      console.log('fileNames', this.fileNames)
      this.postfix = this.fileNames.substring(
        this.fileNames.lastIndexOf('.') + 1,
        this.fileNames.length
      )
      console.log(this.postfix)
      this.fileSize = this.file.size
      console.log('fileSize', this.fileSize)

      if (this.formatType === 'image') {
        const isJPG = this.file.type === 'image/jpeg' || this.file.type === 'image/png' || this.file.type === 'image/bmp' || this.file.type === 'image/gif'
        const isLt2M = this.file.size / 1024 / 1024 < 4
        if (!isJPG) {
          this.$message.error('图片只支持bmp、jpg、png、gif格式的文件')
        }
        if (!isLt2M) {
          this.$message.error('图片大小不能超过 4MB !')
        }
      }

      // this.uploadListVisible = true
      // this.fileData.push({
      //   fileNames: this.fileNames,
      //   formatType: this.formatType,
      //   fileSize: this.fileSize,
      //   filePercentTxt: this.filePercentTxt
      // })
      // console.log(this.fileData[0].filePercent)
    },
    getQiniuToken() {
      getQiniuToken().then(res => {
        this.token = res.data
      })
    },
    // format(percentage) {
    //   return percentage === 100 ? '100%' : `${percentage}%`
    // },
    uploadFile() {
      // 当前VUE中的this 是指向实例，相当于父级，指向指不到子级中。所需需要一个变量 _this 存储this得指向。
      const _this = this

      // 获取身份的token
      const token = _this.token
      console.log(token)
      // 上传时的配置
      var config = {
        useCdnDomain: true
      }
      //  设置文件的配置
      var putExtra = {
        fname: '',
        params: {},
        mimeType: null
      }
      //   实例化七牛云的上传实例
      var observable = qiniu.upload(_this.file, _this.file.name, token, putExtra, { resumingByFileSize: 4 * 1024 * 1024 }, config)
      //   设置实例的监听对象
      var observer = {
        //   接收上传进度信息
        next(res) {
          // 上传进度
          console.log(res)
          console.log(res.total.size)
          _this.filePercent = parseInt(res.total.percent)
          console.log(_this.filePercent)
          this.filePercentTxt = '上传中'
          if (_this.filePercent == 100) {
            // _this.fileData.push(_this.filePercent)
            // _this.fileData.forEach((value, index) => {
            //   value['filePercent'] = parseInt(res.total.percent)
            // })
            this.filePercentTxt = '上传成功'
            console.log('success')
          }
          console.log(_this.fileData)
          // _this.fileData[0].filePercent = parseInt(res.total.percent)
          // console.log(_this.fileData[0].filePercent)
          // _this.fileData.forEach((value, index) => {
          //   value['filePercent'] = parseInt(res.total.percent)
          // })
        },
        // 接收上传错误信息
        error(err) {
          console.log(err)
        },

        // 接收上传完成后的信息
        complete(res) {
          this.filePercentTxt = '上传成功'
          console.log(res)
          console.log(res.key)
          _this.uploadFileUrl = 'http://' + _this.baseurl + '/' + res.key
          console.log(_this.uploadFileUrl)
          // console.log(_this.fileUrl.push({ name: _this.file.name, url: _this.fileUrl }))
          // console.log(_this.fileUrl)
        }
      }
      // 上传开始
      var subscription = observable.subscribe(observer)
      // subscription.unsubscribe()  停止当前文件上传
    }

  }
}
</script>

<style lang="scss" scoped>
.components_upload{
  position: relative;
  // width: 100%;
}
#upFile{
  display: block;
    width: 114px;
    height: 34px;
    padding: 0;
    font-size: 14px;
    border: none;
    opacity: 0;
}
.cont_upload_btn{
  position: absolute;
  left: 0;
  top: 0;
}
</style>

