<template>
  <el-dialog :visible.sync="exportDialogVisible" :close-on-click-modal="false" title="批量导出" class="export-dialog" append-to-body @close="close">
    <div class="top-area">
      <el-checkbox v-model="includeImage" :disabled="isExporting" class="checkBox">导出施工图片</el-checkbox>
      <div>
        <el-button :disabled="isExporting" type="primary" size="small" @click="startExport" >
          <i v-if="isExporting" class="el-icon-loading" />
          <span>{{ isExporting ? '正在导出' : '开始导出' }}</span>
        </el-button>
        <el-button v-if="list.length" type="primary" size="small" @click="hanldeDownloadZip()">下载最近一次文件压缩包</el-button>
        <el-button v-if="list.length" type="primary" size="small" @click="refresh">刷新列表</el-button>
      </div>
    </div>
    <el-table v-loading="listLoading" :data="list" class="table" border height="350">
      <el-table-column align="center" type="index" label="序号" width="55"/>
      <el-table-column v-for="column in columns" :key="column.value" :label="column.text" :width="column.width" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          <span :class="column.class">{{ scope.row[column.value] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="80">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="download(scope.row)">下载</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页-->
    <div class="pagination-container">
      <el-pagination
        :current-page="listQuery.offset"
        :page-sizes="[10,20,30]"
        :page-size="listQuery.limit"
        :total="total"
        align="center"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"/>
    </div>
  </el-dialog>
</template>
<script>
import { getLastExportList, downloadZip } from '@/api/factory'
import { downloadTemplate } from '@/api/common'
export default {
  name: 'ExportDialog',
  props: {
    exportDialogVisible: { // 对话框显隐
      type: Boolean,
      default: false
    },
    isExporting: { // 是否正在导出中
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      columns: [
        {
          text: '文件名',
          value: 'fileName'
        },
        {
          text: '完成时间',
          value: 'createTime'
        }
      ], // 显示列
      includeImage: false, // 0-fasle不导出图片、1-true导出图片
      list: [], // 表格数据
      total: 0, // 数据总数
      listQuery: {
        begTime: '',
        endTime: '',
        offset: 1,
        limit: 10
      },
      listLoading: false // 加载动画
    }
  },
  watch: {
    exportDialogVisible(val) {
      if (val) {
        this.fetchLastExportList()
        this.websocket()
      }
    }
  },
  methods: {
    websocket() {
      console.log(this.$store.state)
      if (!this.$store.state.websocket.wsStatus) {
        this.$store.dispatch('initWebSocket')
      }
    },
    fileHandle(data, fileName) {
      const blob = new Blob([data], { type: 'application/zip' })
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a') // 创建a标签
      link.href = url
      link.download = fileName // 重命名文件
      link.click()
      URL.revokeObjectURL(url) // 释放内存
    },
    // 点击下载压缩包
    hanldeDownloadZip() {
      if (this.list[0].fileDir !== '') {
        const fileDir = this.list[0].fileDir
        // 全屏加载动画
        const loading = this.$loading({
          lock: true,
          text: '数据处理中,请稍后...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        downloadZip(fileDir).then(res => {
          loading.close() // 关闭加载动画
          // const blob = new Blob([res.data])
          // const zip = new JSZip()
          // zip.file(this.list[0].fileName, blob)
          // zip.generateAsync({
          //   type: 'blob'
          // }).then(res => {
          //   saveAs(res, `${this.list[0].fileName}.zip`)
          // })
          const name = this.list[0].fileName.slice(0, this.list[0].fileName.indexOf('.'))
          console.log(name)
          this.fileHandle(res.data, `${name}.zip`)
        }).catch((res) => {
          loading.close()
          // this.$message.error(res.message)
        })
      }
    },
    // 点击下载
    download(row) {
      console.log(row)
      if (row.fileName !== '' && row.fileDir !== '') {
        const fileName = row.fileName
        const sendFileName = row.fileDir + row.fileName
        // 全屏加载动画
        const loading = this.$loading({
          lock: true,
          text: '数据处理中,请稍后...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        downloadTemplate(sendFileName).then(res => {
          loading.close() // 关闭加载动画
          const blob = new Blob([res.data])
          const downloadElement = document.createElement('a')
          const href = window.URL.createObjectURL(blob) // 创建下载的链接
          downloadElement.href = href
          downloadElement.download = fileName // 下载后文件名
          document.body.appendChild(downloadElement)
          downloadElement.click() // 点击下载
          document.body.removeChild(downloadElement) // 下载完成移除元素
          window.URL.revokeObjectURL(href) // 释放blob对象
        }).catch((res) => {
          loading.close()
          this.$message.error(res.message)
        })
      }
    },
    // 关闭弹窗
    close() {
      this.$emit('closeDialog')
    },
    // 点击开始导出
    startExport() {
      this.$emit('startExport', this.includeImage)
    },
    // 获取上次导出的列表
    fetchLastExportList() {
      this.listLoading = true
      getLastExportList({ offset: this.listQuery.offset, limit: this.listQuery.limit }).then(res => {
        console.log('上次导出列表返回', res)
        this.list = res.data.rows
        this.total = res.data.total
        this.listLoading = false
      })
    },
    // 改变页容量
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.fetchLastExportList()
    },
    // 改变当前页
    handleCurrentChange(val) {
      this.listQuery.offset = val
      this.fetchLastExportList()
    },
    // 点击刷新
    refresh() {
      this.fetchLastExportList()
    }
  }
}
</script>
<style lang="scss" scoped>
  .export-dialog {
    .top-area {
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 40px;
      .checkBox {
        margin-right: 40px;
      }
    }
    .pagination-container{
      margin-bottom: 20px;
      margin-top: 20px;
    }
  }
</style>
