<!--
	作者：GuoZhiBo
	时间：2020-05-13
	描述：文件下载进度条
	参数：id控件id
	方法：download下载方法，参数：文件路径和文件名称
-->
<template>
  <div v-show="show">
    <div
      :id="id"
      class="loadBar"
    >
      <div>
        <span class="percent">
          <i />
        </span>
      </div>
      <span class="percentNum">0%</span>
    </div>
  </div>
</template>

<script>
import { Notify, Uuid } from 'pc-component-v3';
export default {

  components: {
    
  },
  props: {
    id:{
      type: String,
      default: null,
    },
  },
  data: function () {
    return {
      max: 0,
      currentProgress: 0,
      percentEle: undefined,
      loadbar: undefined,//进度条对象
      percentNumEle: undefined,
      progressValue: 0,
      show: false,
    };
  },
  watch: {
    'progressValue': function (val, oldVal) {
      var _self = this;
      _self.setProgress(val);
      if (val == 100) {
        _self.show = false;
        _self.progressValue = 0;
      }
    },
  },
  mounted: function () {
    var _self = this;
    _self.loadingBar(_self.id);
  },
  created: function () {
  },

  methods: {
    loadingBar: function (id) {
      var _self = this;
      _self.loadbar = $('#' + id);
      _self.percentEle = $('.percent', _self.loadbar);
      _self.percentNumEle = $('.percentNum', _self.loadbar);
      _self.max = 100;
      _self.currentProgress = 0;
    },
    //设置进度
    setProgress: function (val) {
      var _self = this;
      if (val >= _self.max) {
        val = _self.max;
      }
      _self.currentProgress = parseInt((val / _self.max) * 100) + '%';
      _self.percentEle.width(_self.currentProgress);
      _self.percentNumEle.text(_self.currentProgress);
    },
    download: function (item) {
      var _self = this;
      var url = item.url;
      var fileName = item.fileName;
      var method = item.method;
      var data = item.data;
      var contentType = item.contentType;

      // 默认是GET方式的HTTP请求
      if(method == null){
        method = 'GET';
      }

      if (_self.progressValue != 100 && _self.show == false) {
        _self.show = true;
        var xhr = new XMLHttpRequest();
        xhr.open(method, url, true);//get请求，请求地址，是否异步

        if(contentType != null){
          xhr.setRequestHeader('Content-Type', contentType);
        }

        xhr.addEventListener('progress', function (evt) {
          if (evt.lengthComputable) {
            _self.progressValue = (evt.loaded / evt.total) * 100;
          }
        }, false);
        xhr.responseType = 'blob';    // 返回类型blob
        var token = null;
        if (item.token == null || item.token == undefined) {
          token = localStorage.getItem('#token');
        } else {
          token = item.token;
        }
        xhr.setRequestHeader('token', token);
        // 请求成功回调函数
        xhr.onload = function () {// 请求完成处理函数
          if (this.status === 200) {
            let type = xhr.getResponseHeader('Content-Type');
            let blob = new Blob([this.response], { type: type });
            _self.saveAs(blob, fileName);
          } else if (this.status === 500) {
            Notify.error('提示', '无权限下载数据。');
          } else if (this.status === 404) {
            Notify.error('提示', '文件找不到。');
          } else {
            Notify.error('提示', '服务器异常。');
          }
          if (item.taskId != undefined) {
            item.status = this.status;
            _self.$store.commit('updateCount', item);
          }
        };
        // 请求结束
        xhr.onloadend = function () {
          _self.show = false;
        };
        // 发送ajax请求
        xhr.send(data);
      } else {
        Notify.info('提示', '文件正在下载，请稍后再试。');
      }
    },


    /**
         * 保存
         * @param {Blob} blob
         * @param {String} filename 想要保存的文件名称
         */
    saveAs: function (blob, filename) {
      var link = document.createElement('a');
      var body = document.querySelector('body');

      link.href = window.URL.createObjectURL(blob);
      link.download = filename;

      // fix Firefox
      link.style.display = 'none';
      body.appendChild(link);

      link.click();
      body.removeChild(link);

      window.URL.revokeObjectURL(link.href);
    },

  },
};
</script>

<style scoped>
body {
    font-family: Thoma, Microsoft YaHei, "Lato", Calibri, Arial, sans-serif;
}

#content {
    margin: 120px auto;
    width: 80%;
}

.loadBar {
    width: 100%;
    height: 20px;
    border: 3px solid #212121;
    border-radius: 20px;
    position: relative;
}

.loadBar div {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
}

.loadBar div span,
.loadBar div i {
    box-shadow: inset 0 -2px 6px rgba(0, 0, 0, 0.4);
    width: 0%;
    display: block;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    border-radius: 20px;
}

.loadBar div i {
    width: 100%;
    -webkit-animation: move 0.8s linear infinite;
    background: -webkit-linear-gradient(
        left top,
        #7ed047 0%,
        #7ed047 25%,
        #4ea018 25%,
        #4ea018 50%,
        #7ed047 50%,
        #7ed047 75%,
        #4ea018 75%,
        #4ea018 100%
    );
    background-size: 40px 40px;
}

.loadBar .percentNum {
    position: absolute;
    top: 100%;
    right: 10%;
    padding: 1px 15px;
    border-bottom-left-radius: 16px;
    border-bottom-right-radius: 16px;
    border: 1px solid #222;
    background-color: #222;
    color: #fff;
}

@-webkit-keyframes move {
    0% {
        background-position: 0 0;
    }
    100% {
        background-position: 40px 0;
    }
}
</style>