<template>
  <el-container id="workspaceBackUp">
    <el-header style="height: 50px;">
      <div style="margin: 10px;">
        <awsui-button style="width: 130px;" class="button-general-color" type="primary" @click="createBackup()">新建备份</awsui-button>
      </div>
    </el-header>
    <el-main>
      <el-table
        id="workspaceBackupTable"
        ref="workspaceBackupTable"
        :data="tableData"
        style="width: 100%;"
        :height="tableHeight">
        <el-table-column
          prop="time"
          label="备份时间"
          width="250">
        </el-table-column>
        <el-table-column
          prop="user"
          label="操作用户"
          width="180">
        </el-table-column>
        <el-table-column
          prop="remark"
          label="备注"
          min-width="180">
        </el-table-column>
        <el-table-column
          prop="operation"
          label="操作"
          width="200"
          align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.state != 0 && scope.row.state != 2 && scope.row.state != 3">
              <el-tooltip class="item" content="修改" placement="bottom" :hide-after=2000>
                <i class="awsui-iconfont" style="cursor: pointer;" @click="update(scope.row.id, scope.row.remark)">&#58914;</i>
              </el-tooltip>
              <el-tooltip class="item" content="恢复" placement="bottom" :hide-after=2000>
                <i class="awsui-iconfont" style="cursor: pointer;" @click="recover(scope.row.id, scope.row.time)">&#59130;</i>
              </el-tooltip>
              <el-tooltip class="item" content="导出" placement="bottom" :hide-after=2000>
                <i class="awsui-iconfont" style="cursor: pointer;" @click="exportBackup(scope.row.id)">&#xe7a1;</i>
              </el-tooltip>
              <el-tooltip class="item" content="删除" placement="bottom" :hide-after=2000>
                <i class="awsui-iconfont" style="cursor: pointer;" @click="deleteBackup(scope.row.id, scope.row.time)">&#58918;</i>
              </el-tooltip>
            </div>
            <div v-if="scope.row.state == 0">
              <el-tooltip class="item" content="正在备份..." placement="bottom" :hide-after=2000>
                <i class="awsui-iconfont" style="cursor: default;">&#59648;</i>
              </el-tooltip>
            </div>
            <div v-if="scope.row.state == 2">
              <el-tooltip class="item" content="备份失败" placement="bottom" :hide-after=2000>
                <i class="awsui-iconfont" style="cursor: default;">&#58905;</i>
              </el-tooltip>
              <el-tooltip class="item" content="删除" placement="bottom" :hide-after=2000>
                <i class="awsui-iconfont" style="cursor: pointer;" @click="deleteBackup(scope.row.id, scope.row.time)">&#58918;</i>
              </el-tooltip>
            </div>
            <div v-if="scope.row.state == 3">
              <el-tooltip class="item" content="正在恢复..." placement="bottom" :hide-after=2000>
                <i class="awsui-iconfont" style="cursor: default;">&#59193;</i>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog
        title="资产库备份"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleClose"
        :modal-append-to-body=false
        :close-on-click-modal=false>
        <div style="margin-bottom: 10px;">
          <label>备注</label>
        </div>
        <el-input
          type="textarea"
          placeholder="请输入备注"
          v-model="updateRemark"
          maxlength="200"
          :rows=5
          show-word-limit>
        </el-input>
        <span slot="footer" class="dialog-footer">
          <awsui-button class="button-general-color" :disabled=false type="primary" @click="save">确定</awsui-button>
          <awsui-button @click="closeDlg">取消</awsui-button>
        </span>
      </el-dialog>
    </el-main>
  </el-container>
</template>

<script>
    import awsuiAxios from "../../awsuiAxios";

    export default {
      name: "WorkspaceBackup",
      data() {
        return {
          tableHeight: (parseInt(this.$store.getters.getTopMainHeightFn) - 22 - 50) + 'px',
          tableData: [],
          dialogVisible: false,
          updateType: 'create',// 新增、修改的类型
          updateId: '',// 修改时的id
          updateRemark: '',// 新增、修改的备注
          exportProgressTimeout: '', // 导出备份轮询状态，用于完成轮询后清除定时器
          stateInterval: ''// 定时刷新器
        }
      },
      props: ['wsId'],
      computed: {
        listenTopMainHeight() {
          return this.$store.getters.getTopMainHeightFn;
        }
      },
      created() {
        // alert('a')
      },
      mounted() {
        const that = this;
        that.initData();
        setTimeout(function(){
          that.stateInterval = setInterval(function(){
            that.refreshState();
          }, 1000);
        }, 2000);

      },
      methods: {
        initData(scrollTop) {// 初始化
          const that = this;
          const params = {
            url:'jd',
            data:{
              cmd: 'com.actionsoft.apps.coe.pal_ws_backup_data_query',
              wsId: that.wsId
            }
          };
          awsuiAxios.post(params).then(function (ro) {
            if (ro.result == 'ok') {
              let data = ro.data;
              that.tableData = data;
              if (scrollTop == undefined || scrollTop) {
                that.$refs.workspaceBackupTable.bodyWrapper.scrollTop = 0;
              }
            }
          }).catch(error=>{
            console.log(error);
          })
        },
        createBackup() {// 新建备份
          this.updateRemark = '';
          this.updateId = '';
          this.updateType = 'create';
          this.dialogVisible = true;
        },
        update(id, remark) {
          this.updateRemark = remark;
          this.updateId = id;
          this.updateType = 'update';
          this.dialogVisible = true;
        },
        save() {// 新增、修改的保存
          const that = this;
          if (that.updateRemark.trim() == '') {
            that.$message({message: '[备注]不允许为空', type: 'warning'});
            return false;
          }
          if (that.updateType == 'create') {// 创建新的备份
            const params = {
              url:'jd',
              data:{
                cmd: 'com.actionsoft.apps.coe.pal_backup_add',
                wsId: that.wsId,
                remark: that.updateRemark
              }
            };
            awsuiAxios.post(params).then(function (ro) {
              that.initData();
              that.closeDlg();
            }).catch(error=>{
              console.log(error);
            })
          } else {// 修改备注
            const params = {
              url:'jd',
              data:{
                cmd: 'com.actionsoft.apps.coe.pal_backup_update',
                id: that.updateId,
                remark: that.updateRemark
              }
            };
            awsuiAxios.post(params).then(function (ro) {
              that.$message({message: '修改成功',type: 'success'});
              that.initData();
              that.closeDlg();
            }).catch(error=>{
              console.log(error);
            })
          }
        },
        recover(id, time) {
          const that = this;
          that.$confirm('恢复后，当前数据无法找回，请先备份当前数据！要继续恢复[' + time + ']的备份吗？', '提示', {
            confirmButtonText: '是，已经备份',
            cancelButtonText: '否，去备份',
            confirmButtonClass: 'button-general-color',
            type: 'warning'
          }).then(() => {
            const params = {
              url:'jd',
              data:{
                cmd: 'com.actionsoft.apps.coe.pal_backup_recover',
                wsId: that.wsId,
                id: id
              }
            };
            awsuiAxios.post(params).then(function (ro) {
              that.initData(false);
            }).catch(error=>{
              console.log(error);
            })
          }).catch(() => {
            that.createBackup();
          });
        },
        exportBackup(id) {
          const that = this;
          // 生成bak文件
          const params = {
            url:'jd',
            data:{
              cmd: 'com.actionsoft.apps.coe.pal_backup_export',
              wsId: that.wsId,
              id: id
            }
          };
          awsuiAxios.post(params).then(function (ro) {
            that.exportProgressTimeout = setInterval(function(){that.exportBackupProgress(id)}, 2000);
          }).catch(error=>{
            console.log(error);
          })
        },
        exportBackupProgress(id) {// 查询是否备份完成
          const that = this;
          const params = {
            url:'jd',
            data:{
              cmd: 'com.actionsoft.apps.coe.pal_backup_export_progress',
              wsId: that.wsId,
              id: id
            }
          };
          awsuiAxios.post(params).then(function (r) {
            if(r.data.progress == "finish") {
              //已经生成bak,可系统下载
              clearTimeout(that.exportProgressTimeout);
              that.exportProgressTimeout = '';
              that.exportBackupDownload(id);
            } else if(r.data.progress == "byhand") {
              //已经生成bak,需手工下载
              clearTimeout(that.exportProgressTimeout);
              that.exportProgressTimeout = '';
              $.simpleAlert("close");
              var filename = that.wsId + ".bak";
              this.$message({
                showClose: true,
                message: '文件过大，请联系管理员在服务器/doccenter/com.actionsoft.apps.coe.pal/tmp/exp/repository目录下获取备份文件' + filename,
                duration: 0,
              });
            }
          }).catch(error=>{
            console.log(error);
          })
        },
        exportBackupDownload(id) {// 下载备份文件
          const that = this;
          const params = {
            url:'jd',
            data:{
              cmd: 'com.actionsoft.apps.coe.pal_backup_export_download',
              wsId: that.wsId,
              id: id
            }
          };
          awsuiAxios.post(params).then(function (ro) {
            window.open(ro.data.downloadUrl);
          }).catch(error=>{
            console.log(error);
          })
        },
        deleteBackup(id, time) {
          const that = this;
          that.$confirm('确定要删除吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            confirmButtonClass: 'button-general-color',
            type: 'warning'
          }).then(() => {
            const params = {
              url:'jd',
              data:{
                cmd: 'com.actionsoft.apps.coe.pal_backup_delete',
                wsId: that.wsId,
                id: id
              }
            };
            awsuiAxios.post(params).then(function (ro) {
              that.$message({type: 'success',message: '删除成功!'});
              for (let i = 0; i < that.tableData.length; i++) {
                if (that.tableData[i].id == id) {
                  that.tableData.splice(i, 1);
                  break;
                }
              }
            }).catch(error=>{
              console.log(error);
            })
          }).catch(() => {
          });
        },
        handleClose(done) {
          done();
        },
        closeDlg() {
          this.dialogVisible = false;
          this.updateRemark = '';
          this.updateType = 'create';
          this.updateId = '';
        },
        refreshState() {// 查询
          const that = this;
          for (let i = 0; i < that.tableData.length; i++) {
            const data = that.tableData[i];
            if (data.state == 0 || data.state == 3) {
              // 查询状态
              const params = {
                url:'jd',
                data:{
                  cmd: 'com.actionsoft.apps.coe.pal_backup_state',
                  wsId: that.wsId,
                  id: data.id
                }
              };
              awsuiAxios.post(params).then(function (r) {
                that.tableData[i].state = r.data.state;
                if (r.data.state == 4) {
                  that.$message({message: '恢复成功',type: 'success'});
                  setTimeout(function() {
                    // 刷新首页
                    location.reload();
                  }, 1000);
                }
              }).catch(error=>{
                console.log(error);
              })
            }
          }
        }
      },
      watch : {
        listenTopMainHeight: function (newd, old) {
          this.tableHeight = (parseInt(newd)) - 22 - 50 + 'px';
        }
      },
      beforeDestroy:function(){
        clearInterval(this.stateInterval);
        clearInterval(this.exportProgressTimeout);
      },
    }
</script>

<style scoped>
  #workspaceBackUp >>> .el-main {
    display: block;
    -webkit-box-flex: 1;
    -ms-flex: 1;
    flex: 1;
    -ms-flex-preferred-size: auto;
    flex-basis: auto;
    overflow: auto;
    padding: 0px 20px 0px;
  }
  #workspaceBackUp >>> .el-dialog__body {
    padding: 10px 20px;
    color: #606266;
    font-size: 14px;
    word-break: break-all;
  }
  #workspaceBackupTable >>> .item {
    margin-left: 5px;
    margin-right: 5px;
  }
</style>
