<template>
  <div>
    <el-drawer class="custom-drawer-form" title="数据包导入记录" size="800px" :visible.sync="drawer" direction="rtl" :before-close="close" destroy-on-close>
      <el-container class="project-import">
        <el-header>
          <el-form :inline="true" class="project-import-header-form">
            <el-form-item label="创建人">
              <el-input v-model="queryParams.createName" size="small" placeholder="请输入创建人名称"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="" size="small" @click="getList">查询</el-button>
              <el-button type="primary" size="small" @click="handleAdd()">导入</el-button>
            </el-form-item>
          </el-form>
        </el-header>
        <el-main class="project-file-main">
          <el-table v-loading="loading" :data="tableData" border header-row-class-name="custom-table-header">
            <el-table-column type="index" label="#" width="55" align="center"></el-table-column>
            <el-table-column prop="name" label="文件大小" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                <span v-if="scope.row.fileSize">{{ renderSize(scope.row.fileSize) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="createName" label="创建人" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="createTime" label="创建时间" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column label="操作" align="center" width="150">
              <template slot-scope="scope">
                <el-dropdown split-button type="primary" size="small" @click="handleEdit(scope.row)">
                 <p>记录</p> 
                  <el-dropdown-menu slot="dropdown" class="text-align_center">
                    <el-dropdown-item @click.native="handleDownload(scope.row)">下载</el-dropdown-item>
                    <el-dropdown-item divided class="color-red" @click.native="handleDelete(scope.row)">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination">
            <el-pagination :current-page.sync="queryParams.current" :page-size="queryParams.size" :total="total" @current-change="handleCurrentChange" layout="total, prev, pager, next, jumper" background></el-pagination>
          </div>
        </el-main>
        <el-footer class="footer-common">
          <el-button @click="close">关 闭</el-button>
        </el-footer>
      </el-container>
    </el-drawer>

    <el-dialog class="project-import-status" title="导入专题库数据" :visible.sync="visible" width="500px" :close-on-click-modal="false" append-to-body destroy-on-close :before-close="close2" 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>
        <el-form :model="form">
          <el-form-item label="选择专题库">
            <el-select v-model="form.projectId" filterable placeholder="请选择专题库" class="width_100">
              <el-option v-for="item in projectList" :value="item.id" :label="item.name"></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="!form.file ? 'el-icon-upload' : 'el-icon-refresh'"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip"></div>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="close2">取 消</el-button>
          <el-button type="primary" @click="submit" :loading="btnLoading">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

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

export default {
  data() {
    return {
      drawer: false,
      tableData: [],
      visible: false,
      upload: false,
      btnLoading: false,
      projectList: [],
      queryParams: {
        current: 1,
        size: 10,
        createName: ''
      },
      form: {
        projectId: null,
        file: null
      },
      total: 0,
      loading: false,
      importId: null,
      importList: [],
      activityList: [],
      statusObj: {
        0: '',
        1: '',
        2: '正在解压数据包',
        3: '开始执行更新专题库基础信息功能',
        4: '开始执行更新专题库附件(含报告)功能',
        5: '开始执行更新自定义栏位功能',
        6: '开始执行更新专利附图功能',
        7: '开始执行更新专利说明书功能',
        8: '开始执行更新专利基础信息功能',
        9: '开始执行更新专题库关联专利功能',
        100: '导入失败：数据包未包含专题库基础信息',
        101: '导入失败：系统异常',
        200: '导入数据包完成',
      }
    }
  },
  computed: {
    ...mapGetters(['webSocket', 'userinfo'])
  },
  mounted() {

  },
  methods: {
    renderSize,
    getProjectList() {
      let params = {
        current: 1,
        size: 9999,
        myself: true,
        name: '',
        sort: {
          order: 'desc',
          prop: 'create_time'
        },
      }
      this.$api.getProjectListV2(params).then(response => {
        this.projectList = response.data.records
      })
    },
    open() {
      this.drawer = true
      this.getList()
      this.getProjectList()
      this.webSocket.onmessage = (e) => {
        const { code, data, message } = JSON.parse(e.data)
        if (code === 901 && this.importId === data.importId) {
          this.getRecord(data)
        }
      }
    },
    getRecord(data) {
      this.record(this.statusObj[data.status], data.createTime, [100, 101].indexOf(data.status) === -1 ? 1 : 0)
    },
    handleAdd() {
      this.$api.getProjectImportOngoing().then(response => {
        if (!response.data) {
          this.visible = true
          this.upload = false
        } else {
          this.$message.error('有任务在进行中')
        }
      })
    },
    getList() {
      this.loading = true
      this.$api.getProjectImportPageList(this.queryParams).then(response => {
        this.tableData = response.data.records
        this.total = response.data.total
        this.loading = false
      })
    },
    onChange(file, fileList) {
      this.form.file = file.raw
    },
    record(status, createTime, code = 1) {
      this.activityList.push({
        status: status,
        code: code,
        createTime: 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.form.file) {
        this.$message.error('请选择文件')
        return false
      }
      this.activityList = []
      this.handleImport()
    },
    handleImport() {
      this.upload = true
      this.record('等待读取文件MD5')
      getFileMD5(this.form.file, async (md5) => {
        this.record('文件MD5：' + md5)
        let fileChunks = createFileChunk(this.form.file)
        await this.uploadChunks(fileChunks, md5, 0)
        this.record('等待服务器合并分片')
        const response = await this.$api.mergeChunks({ md5: md5, fileName: this.form.file.name })
        let params = {
          url: response.data,
          projectId: this.form.projectId
        }
        const response2 = await this.$api.importProjectData(params)
        this.importId = response2.data
      })
    },
    close() {
      this.drawer = false
        this.form.projectId = null
        this.form.file = null
        this.$emit('close')
      // this.$api.getPermissions().then(response => {
      //   this.$store.commit('SET_PERMISSIONS', response.data)
      //   this.drawer = false
      //   this.form.projectId = null
      //   this.form.file = null
      //   this.$emit('close')
      // })
    },
    close2() {
      this.visible = false
      this.form.projectId = null
        this.form.file = null
      this.getList()
    },
    handleCurrentChange(val) {
      this.queryParams.current = val;
      this.getList();
    },
    handleEdit(row) {
      this.$api.getProjectImportStatusList({ importId: row.id }).then(response => {
        this.visible = true
        this.upload = true
        this.importId = row.id
        this.activityList = []
        response.data.map(data => {
          this.getRecord(data)
        })
      })
    },
    handleDownload(row) {
      downLoad2(row.url)
    },
    handleDelete(row) {
      this.$confirm('确认删除本条数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        this.$api.deleteProjectImport({ id: row.id }).then(response => {
          this.$message.success('删除成功')
          this.loading = false
          this.getList()
        }).catch(error => {
          this.loading = false
        })
      })
    }
  }
}
</script>

<style lang="scss">
.project-import {
  .project-import-header-form {
    margin-left: 20px;
  }
}
.project-import-status {
  .el-timeline {
    padding: 10px !important;
  }
  .record {
    height: 600px;
    overflow-y: auto;
    margin-top: 10px;
  }
}
</style>