<template>
  <div class="layout-no-cols right-list-toolbar">
    <el-toolbar>
      <el-button @click="backupClickHandler" priv="Platform.Backup.Backup">
        <i class="fa fa-copy" aria-hidden="true"></i>备份数据
      </el-button>
      <!-- <el-button :disabled="selectedRows.length === 0" @click="deleteClickHandler" priv="Platform.Backup.Delete">
        <i class="fa fa-remove" aria-hidden="true"></i>删除文件
      </el-button> -->
    </el-toolbar>

    <div v-loading="dataLoading">
      <el-table :data="backupFiles" tooltip-effect="dark" style="width: 100%" @selection-change="onSelectionChange">
        <el-table-column type="index" width="60" label="序号" align="center"></el-table-column>
        <el-table-column prop="file" label="文件名" min-width="40%"></el-table-column>
        <el-table-column prop="size" label="大小" min-width="25%"></el-table-column>
        <el-table-column prop="lastChangeDate" label="最后修改时间" min-width="25%">
          <template slot-scope="scope">
            {{scope.row.lastChangeDate | fixDateTime}}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="right" width="150">
          <template slot-scope="scope">
            <el-button @click.stop="downloadClickHandler(scope.row)" priv="Platform.Backup.Download" type="text" title="下载">
              <i class="fa fa-download f16"></i></el-button>
            <el-button @click.stop="recoveryClickHandler(scope.row)" priv="Platform.Backup.Restore" type="text" title="恢复数据">
              <i class="fa fa-reply f16"></i></el-button>
            <el-button @click.stop="seeClickHandler(scope.row)" priv="Platform.Backup.Info" type="text" title="查看文件">
              <i class="fa fa-eye f16"></i></el-button>
            <el-button @click.stop="deleteClickHandler(scope.row)" priv="Platform.Backup.Delete" type="text" title="删除文件">
              <i class="fa fa-remove f16"></i></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--查看文件框-->
    <el-dialog :title="tmpBackupFile.info.file" :visible.sync="tmpBackupFile.isShowModal">
      <el-tabs v-model="tmpBackupFile.activeName" @tab-click="tabClickHandler">
        <el-tab-pane label="Info" name="info">
          <el-form label-width="100px">
            <el-form-item label="File name：">
              <span>{{tmpBackupFile.info.file}}</span>
            </el-form-item>
            <el-form-item label="Data size：">
              <span>{{tmpBackupFile.info.size}}</span>
            </el-form-item>
            <el-form-item label="Total records：">
              <span>{{tmpBackupFile.info.total}}</span>
            </el-form-item>
            <el-form-item label="Start time：">
              <span>{{tmpBackupFile.info.startTime}}</span>
            </el-form-item>
            <el-form-item label="End time：">
              <span>{{tmpBackupFile.info.endTime}}</span>
            </el-form-item>
            <el-form-item label="Task log：">
              <el-input type="textarea" :rows="10" placeholder="task log" v-model="tmpBackupFile.info.tasklog"></el-input>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="Tables" name="tables">
          <div class="pane-wrap" v-loading="tableDataLoading">
            <el-table :data="tmpBackupFile.table" tooltip-effect="dark" style="width: 100%">
              <el-table-column type="index" width="60" align="center"></el-table-column>
              <el-table-column prop="name" label="Table name"></el-table-column>
              <el-table-column prop="size" label="Data size"></el-table-column>
              <el-table-column prop="total" label="Total records"></el-table-column>
              <el-table-column prop="batchcount" label="Batch count"></el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

  </div>
</template>

<script>
import util from '@src/common/util.js'
export default {
  filters: {
    fixDateTime: function(val) {
      if (!val) {
        return ''
      }
      return util.formatDate(val, 'yyyy-MM-dd HH:mm')
    }
  },
  data() {
    return {
      backupFiles: [],
      selectedRows: [],
      dataLoading: false,
      tmpBackupFile: {
        isShowModal: false,
        activeName: 'info',
        info: {},
        table: []
      },
      tableDataLoading: false
    }
  },
  methods: {
    onSelectionChange(selection) {
      this.selectedRows = selection
    },
    async backupClickHandler() {
      try {
        await this.$confirm('确认备份数据库吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch (e) {
        return
      }
      let res = await axios.post('/ui/backups')
      if (res.data.status === 1) {
        let resp = await axios.get(`/ui/framework/longtimetasks/${res.data.taskID}`)
        try {
          await util.showProgress(res.data.taskID, resp.data.data.currentInfo)
          this.initBackups()
        } catch (e) {
          util.showResponseMessage(e)
        }
      }
    },
    async recoveryClickHandler(row) {
      try {
        await this.$confirm('确认恢复数据库吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch (e) {
        return
      }
      let file = row && row.file ? row.file : this.selectedRows[0].file
      let res = await axios.put('/ui/backups/restored', { file })
      if (res.data.status === 1) {
        let resp = await axios.get(`/ui/framework/longtimetasks/${res.data.taskID}`)
        try {
          await util.showProgress(res.data.taskID, resp.data.data.currentInfo)
          this.initBackups()
        } catch (e) {
          util.showResponseMessage(e)
        }
      }
    },
    async deleteClickHandler(row) {
      try {
        await this.$confirm('确定删除吗，删除后无法恢复。是否继续删除？', '删除确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch (e) {
        return
      }
      let ids = []
      if (row && row.file) {
        ids.push(row.file)
      } else {
        this.selectedRows.forEach(function (obj) {
          ids.push(obj.file)
        })
      }
      try {
        /* 经过测试发现RESTful风格的接口不支持ids中带英文点（.），比如：/ui/backups/full_20180112173004.zbf，这中间有个英文点，
          导致接口无法找到（404错误）。故设置参数位为空，使用params传递ids */
        let res = await axios.delete(`/ui/backups/${ids.join()}/`)
        util.showMessage(res)
        if (res.data.status === 1) {
          this.backupFiles = this.backupFiles.filter(val => !ids.includes(val.file))
          this.selectedRows = []
        }
      } catch (e) {
        util.showErrorMessageBox(e)
      }
    },
    async seeClickHandler(row) {
      let file = row && row.file ? row.file : this.selectedRows[0].file
      try {
        let res = await axios.get('/ui/backups/infos', {params: {file}})
        this.tmpBackupFile.info = res.data
        this.tmpBackupFile.activeName = 'info'
        this.tmpBackupFile.table = []
        this.tmpBackupFile.isShowModal = true
      } catch (e) {
        util.showErrorMessageBox(e)
      }
    },
    async tabClickHandler(tab) {
      if (this.tmpBackupFile.activeName === 'tables' && !this.tmpBackupFile.table.length) {
        this.tableDataLoading = true
        try {
          let res = await axios.get('/ui/backups/tables', {params: {file: this.tmpBackupFile.info.file}})
          this.tableDataLoading = false
          this.tmpBackupFile.table = res.data.data
        } catch (e) {
          this.tableDataLoading = false
          util.showErrorMessageBox(e)
        }
      }
    },
    downloadClickHandler(row) {
      if (!row.hasFileDownloadPriv) {
        this.$alert('没有下载权限！')
        return
      }
      window.location.href = `ui/backups/download/file?fileName=${row.file}`
    },
    async initBackups() {
      this.dataLoading = true
      let res
      try {
        res = await axios.get('/ui/backups')
      } catch (e) {
        this.dataLoading = false
        return
      }
      this.dataLoading = false
      this.backupFiles = res.data.data
    }
  },
  created() {
    this.initBackups()
  }
}
</script>
