<template>
  <div>
    <el-dialog class="batch-instruction" title="批量上传说明书" :visible.sync="visible" width="500px" :close-on-click-modal="false" append-to-body destroy-on-close :before-close="close" top="10vh">
      <template v-if="upload">
        <el-alert title="注意" type="warning" show-icon>
          <b>1. 同时只允许一个导入任务进行</b><br>
          <b>2. 在"开始更新专利说明书"步骤前不要关闭此弹出框</b><br>
        </el-alert>
        <div class="record">
          <el-timeline>
            <el-timeline-item v-for="(activity, index) in activityList" :type="activity.code === 1 ? 'primary' : 'danger'" :timestamp="activity.createTime">
              {{ activity.status }}
            </el-timeline-item>
          </el-timeline>
        </div>
      </template>
      <template v-else>
        <div>
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm">
            <el-form-item label="文档类型" prop="type">
              <el-select v-model="ruleForm.type" class="width_100">
                <el-option label="公开文档" value="1"></el-option>
                <el-option label="授权文档" value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="导入文件" required>
              <el-upload class="upload-file" drag action="#" :auto-upload="false" :show-file-list="true" :on-change="onChange">
                <i :class="!ruleForm.file ? 'el-icon-upload' : 'el-icon-refresh'"></i>
                <div class="el-upload__text">将<span style="color: rgb(244, 87, 87);">压缩包</span>文件拖到此处，或<em>点击上传</em><span style="color:  rgb(244, 87, 87);">压缩包</span></div>
                <div class="el-upload__tip" slot="tip"></div>
              </el-upload>
            </el-form-item>
            <el-form-item label="备注内容" prop="remark">
              <el-input v-model="ruleForm.remark" placeholder="请输入备注" type="textarea"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="close">取 消</el-button>
          <el-button type="primary" @click="submit" :loading="btnLoading">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getFileMD5, createFileChunk } from "@/utils/file";
import { renderSize, formatDate } from "@/utils";
import { mapGetters } from "vuex";

export default {
  data() {
    return {
      visible: false,
      btnLoading: false,
      ruleForm: {
        type: '1',
        file: null
      },
      rules: {
        type: [{ required: true, message: '请选择文档类型', trigger: 'change' },],
      },
      upload: false,
      activityList: []
    }
  },
  computed: {
    ...mapGetters(['webSocket', 'userinfo'])
  },
  created() {

  },
  methods: {
    renderSize,
    open() {
      this.webSocket.onmessage = (e) => {
        const { code, data, message } = JSON.parse(e.data)
        if (code === 900) {
          const status = `开始更新专利说明书(${data.index + 1}/${data.total})`
          if (this.activityList.length < 5) {
            this.activityList = [{
              status: status,
              code: 1,
              createTime: formatDate(new Date(), 'YYYY-MM-DD HH:mm:ss')
            }]
            this.upload = true
          } else {
            let record = this.activityList[4]
            record.status = status
          }
          if (data.index + 1 === data.total) {
            this.record('专利说明书更新完成')
          }
        } else if (code === 800) {
          this.$message.error(message)
        }
      }
      this.activityList = []
      this.upload = false
      this.visible = true
    },
    close() {
      this.visible = false
      this.ruleForm = {
        type: '1',
        file: null
      }
      this.$emit('close')
    },
    onChange(file, fileList) {
      this.ruleForm.file = file.raw
    },
    record(status, code = 1) {
      this.activityList.push({
        status: status,
        code: code,
        createTime: formatDate(new Date(), 'YYYY-MM-DD HH:mm:ss')
      })
    },
    uploadChunks(fileChunks, md5, index) {
      return new Promise((resolve, reject) => {
        if (index >= fileChunks.length) {
          resolve(true)
        }
        let formData = new FormData()
        formData.append('file', fileChunks[index].file)
        formData.append('md5', md5)
        formData.append('index', index)
        this.$api.uploadChunks(formData).then(async (response) => {
          let record = this.activityList[2]
          const status = `将分片上传至服务器(${index + 1}/${fileChunks.length})`
          if (record) {
            record.status = status
          } else {
            this.record(status)
          }
          resolve(this.uploadChunks(fileChunks, md5, index + 1))
        })
      })
    },
    submit() {
      if (!this.ruleForm.file) {
        this.$message.error('请选择文件')
        return false
      }
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.upload = true
          this.record('等待读取文件MD5')
          getFileMD5(this.ruleForm.file, async (md5) => {
            this.record('文件MD5：' + md5)
            let fileChunks = createFileChunk(this.ruleForm.file)
            await this.uploadChunks(fileChunks, md5, 0)
            this.record('等待服务器合并分片')
            const response = await this.$api.mergeChunks({ md5: md5, fileName: this.ruleForm.file.name })
            let params = {
              url: response.data,
              type: this.ruleForm.type,
              remark: this.ruleForm.remark
            }
            await this.$api.batchUploadPatentInstruction(params)
            this.record('开始更新专利说明书')
          })
        }
      })
    }
  }
}
</script>

<style lang="scss">
.batch-instruction {
  .el-timeline {
    padding: 10px !important;
  }
  .record {
    height: 600px;
    overflow-y: auto;
    margin-top: 10px;
  }
}
</style>
