<template>
  <div id="app">
    <router-view />

    <div v-if="isOpenDownPanel" class="download-mask">
      <h3 class="title">{{ `下载任务【${downloadTitle}】`}}</h3>
      <div class="content">
        <div
          class="down-tip"
          style="min-height: 60px;"
          v-loading="showDownLoading"
          element-loading-text="资源文件正在生成中，请耐心等待。。。"
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(0, 0, 0, 0)"
        >

          <template v-if="downPercent > 0">
            <el-progress :text-inside="true" :stroke-width="26" :percentage="downPercent"></el-progress>
            <div style="text-align: right; color: #666; font-size: 14px; margin-top: 6px;">下载进度条</div>
          </template>

          <el-result v-if="showError" icon="error" title="文件下载失败">
            <template slot="extra">
              <el-button type="primary" size="medium" @click="handleAgainDown">重新下载</el-button>
              <el-button type="primary" size="medium" @click="handleClose">关闭窗口</el-button>
            </template>
          </el-result>

          <el-result v-if="showSucc" icon="success" title="下载成功">
            <template slot="extra">
              <el-button type="primary" size="medium" @click="handleClose">关闭窗口</el-button>
            </template>
          </el-result>

        </div>
        
      </div>
    </div>
  </div>
</template>

<script>
import {exportBlob} from "@/api/common";
import {getToken} from "@/util/auth";
import {downloadXls, downloadFileByUrl} from "@/util/util";
import { generateTaskId, downAllFile } from "@/api/achiveManage/archiveList"
import { mapGetters } from "vuex";
import {setStore, getStore, removeStore} from '@/util/store'

export default {
  name: "app",
  data() {
    return {
      taskStoreName: '', // 下载任务存储的store对象
      fileSize: 0, // 文件大小
      downPercent: 0,

      isOpenDownPanel: false,
      showDownLoading: false,
      showError: false,
      showSucc: false,
      fileTypeNameObj: {
        0: '全部档案资料',
        1: '高新备查资料',
        2: '加计扣除备查资料'
      }
    };
  },
  computed: {
    ...mapGetters(['userInfo', 'downloadTaskObj']),
    downloadTitle() {
      const { type, yearAndMonth } = this.downloadTaskObj;
      return `${yearAndMonth}年${this.fileTypeNameObj[type]}`;
    }
  },
  watch: {
    'downloadTaskObj.isOpenDown': {
      handler(newVal) {
        if (newVal) {
          const { type, yearAndMonth } = this.downloadTaskObj;
          this.taskStoreName = `taskType${type}_${yearAndMonth}_${this.userInfo.tenant_id}`;
          this.isOpenDownPanel = true;
          this.showDownLoading = true;
          this.showError = false;
          this.showSucc = false;
          this._checkTimeout = setTimeout(() => {
            this.checkTaskId(yearAndMonth, type);
          }, 3000)
          
        }
      },
      deep: true
    }
  },
  beforeDestroy() {
    this._timout && clearTimeout(this._timout);
    this._checkTimeout && clearTimeout(this._checkTimeout);
    this.$store.commit("SET_TASK_OPEND_STATUS", false);
  },
  methods: {
    handleAgainDown() {
      const { type, yearAndMonth } = this.downloadTaskObj;
      this.showError = false;
      this.showDownLoading = true;
      this.checkTaskId(yearAndMonth, type);
    },
    handleClose() {
      this.showError = false;
      this.showSucc = false;
      this.showDownLoading = false;
      this.isOpenDownPanel = false;
      this.$store.commit("SET_TASK_OPEND_STATUS", false);
    },
    /**
     * 检查下载任务进程
     * @param yearAndMonth 年份
     * @param fileType 文件类型
     */
    checkTaskId(yearAndMonth, fileType) {
      if (this._checkTimeout) {
        clearTimeout(this._checkTimeout);
      }
      let storeTaskId = getStore({ name: this.taskStoreName }) || undefined;
      generateTaskId({ yearAndMonth, type: fileType, id: storeTaskId }).then(taskRes => {
        if (taskRes.data.code == 200) {
          const { id: taskId, status, fileSize } = taskRes.data.data;

          if (!storeTaskId) {
            setStore({ name: this.taskStoreName, content: taskId });
          }

          if (status == 2) {
            this.showDownLoading = false;
            removeStore({ name: this.taskStoreName });
            this.downloadZip(yearAndMonth, taskId, fileType, fileSize);
          } else if (status == 4) {
            // 任务过期或者不存在
            removeStore({ name: this.taskStoreName });
            this._checkTimeout = setTimeout(() => {
              this.checkTaskId(yearAndMonth, fileType);
            }, 1500)
          } else {
            this._checkTimeout = setTimeout(() => {
              this.checkTaskId(yearAndMonth, fileType);
            }, 1500)
          }
        }
        
      }).catch(err => {
        this.$message.error("文件下载失败!");
        this.showDownLoading = false;
        this.showError = true;
      })
    },
    /**
     * 下载文件
     * @param yearAndMonth 年份
     * @param taskId 下载任务id
     * @param fileType 文件类型
     * @param fileSize 文件大小
     */
    downloadZip(yearAndMonth, taskId, fileType, fileSize) {
       this.showProgressDialog = true;
        exportBlob(`/api/kd-scientific/archive/center/download?${this.website.tokenHeader}=${getToken()}`, { taskId }, (progressEvent) => {
          const progress = Math.round((progressEvent.loaded * 100) / fileSize);
          this.downPercent = progress;
        }).then(res => {
          this._timout = setTimeout(() => {
            this.$message.success('文件下载成功!');
            downloadXls(res.data, `${this.downloadTitle}.zip`);
            this.downPercent = 0;
            this.showDownLoading = false;
            this.showSucc = true;
            this.$store.commit("SET_TASK_OPEND_STATUS", false);
          }, 800)
        }).catch(() => {
          this.$message.error("文件下载失败!");
          this.showError = true;
        });
    }
  },
};
</script>
<style lang="scss">
#app {
  width: 100%;
  height: 100%;
  overflow: hidden;
}
.avue--detail .el-col{
  margin-bottom: 0;
}

.download-mask {
  position: fixed;
  top: 105px;
  right: 0;
  padding: 14px 26px 14px 13px;
  width: 330px;
  min-height: 60px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
  border: 1px solid #ebeef5;
  z-index: 9999;
  .title {
    font-weight: 700;
    font-size: 16px;
    color: #303133;
    margin: 0 !important;
  }
  .content {
    margin-top: 16px;
  }
}
</style>
