<template>
  <div class="systemBackup">
    <div class="systemBackup-btn">
      <el-button
        type="primary"
        @click="
          confirmation(
            {
              msg: '此操作将开始备份文件, 是否继续？'
            },
            () => backup()
          )
        "
        v-loading.fullscreen.lock="fullscreenLoading"
        >备份</el-button
      >
      <el-button type="primary" @click="getBackupSet">备份设置</el-button>
      <el-button type="primary" @click="importBackup">数据同步</el-button>
      <el-button
        type="warning"
        @click="
          confirmation(
            {
              msg: '此操作将初始化系统数据，是否继续？'
            },
            () => initialize()
          )
        "
        :disabled="initloading"
        >系统初始化</el-button
      >
      <el-button type="primary" @click="importOperation">导入</el-button>
    </div>
    <LTable ref="table" :defaultFetch="false" :columns="columns" :dataSource="tableData" :options="options" :fetch="fetchTableData" :pagination="pagination" class="systemBackup-table"> </LTable>
    <el-dialog title="备份设置" :visible.sync="dialogVisible" width="400px" :before-close="cancel">
      <el-form ref="ruleForm" :model="form" label-width="110px" label-position="right" :rules="rules">
        <el-form-item label="自动备份：" prop="setupStatus">
          <el-switch :active-value="1" :inactive-value="0" v-model="form.setupStatus"></el-switch>
        </el-form-item>
        <el-form-item label="备份周期/天：" class="size" prop="intervalPeriod">
          <el-input v-model="form.intervalPeriod" placeholder="天" :disabled="!form.setupStatus"></el-input>
        </el-form-item>
        <el-form-item label="备份保留时间：" class="size" prop="retentionTime">
          <el-select style="width: 100%" v-model="form.retentionTime" placeholder="请选择保留时间" :disabled="!form.setupStatus">
            <el-option v-for="item in formOptions" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" style="display: flex; justify-content: center">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
      </div>
    </el-dialog>
    <UploadDialog v-bind="uploadObj" @uploadSuccess="uploadSuccess" ref="uploadDialog" />
    <!-- 导入 -->
    <ImportDialog ref="ImportDialog" @submitCallBack="ImportDialogCallBack" />
  </div>
</template>

<script>
import { useMessage } from '@/utils/element-ui'
import { columns, options } from './index'
import { backupList, backupRemove, backupAdd, recover, backUpSet, updateBackUpSet, systemInit, exportBackupData } from '@/api/system/systemBackup'
import { debounce } from '@/utils/index'
import { MessageBox } from 'element-ui'
import store from '@/store'
import UploadDialog from './uploadDialog/index.vue'
import ImportDialog from './importDialog/index.vue'

export default {
  name: 'SystemBackup',
  components: { UploadDialog, ImportDialog },
  data() {
    // 这里存放数据
    return {
      userInfo: store.state.user.userInfo.user,
      columns: columns(this),
      options,
      fullscreenLoading: false,
      dialogVisible: false,
      form: {
        setupId: '',
        setupStatus: 0,
        intervalPeriod: '',
        retentionTime: ''
      },
      formOptions: [],
      setupInfo: null,
      pagination: {
        total: 0,
        pageIndex: 1,
        pageSize: 20
      },
      debounceFn: debounce(this.fetchTableData, 500),
      tableData: [],
      rules: {
        intervalPeriod: {
          pattern: /^[1-9]\d*$/g,
          message: '必须为正整数',
          trigger: 'blur'
        }
      },
      initloading: false,
      // 导入文件
      uploadObj: {
        title: '导入备份',
        postData: {},
        postUrl: '/system/sysBackupData/backupDataReceive'
      }
    }
  },
  mounted() {
    this.fetchTableData()
  },
  methods: {
    async initialize() {
      this.initloading = true
      const loading = this.$loading({
        lock: true,
        text: '处理中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      try {
        const { msg } = await systemInit()
        this.$message({
          type: 'success',
          message: msg
        })
        this.$alert(msg + '跳转至首页', '提示', {
          confirmButtonText: '确定',
          callback: (action) => {
            this.$store.dispatch('user/loginOut')
          }
        })
      } catch (error) {}
      this.loading = false
      loading.close()
    },

    async fetchTableData() {
      const {
        data: { list, totalCount }
      } = await backupList({
        pageIndex: this.pagination.pageIndex,
        pageSize: this.pagination.pageSize
      })
      this.tableData = list
      this.pagination.total = totalCount
    },

    async backup() {
      this.fullscreenLoading = true
      setTimeout(async () => {
        const { success } = await backupAdd()
        if (success) {
          this.fetchTableData()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.fetchTableData()
        }
        this.fullscreenLoading = false
      }, 800)
    },

    confirmation(params, fun) {
      const { msg = '', title = '提示', confirmButtonText = '确定', cancelButtonText = '取消' } = params
      MessageBox.confirm(msg, title, {
        confirmButtonText: confirmButtonText,
        cancelButtonText: cancelButtonText,
        type: 'warning'
      })
        .then(() => {
          fun()
        })
        .catch(() => {})
    },

    triggerDialogVisible() {
      this.dialogVisible = !this.dialogVisible
    },

    async getBackupSet() {
      this.triggerDialogVisible()
      try {
        const {
          data: { options, setup }
        } = await backUpSet()
        const { setupId, intervalPeriod, retentionTime, setupStatus } = setup
        this.formOptions = options
        this.setupInfo = setup
        this.form.setupId = setupId
        this.form.setupStatus = setupStatus
        this.form.intervalPeriod = String(intervalPeriod == null ? '' : intervalPeriod)
        this.form.retentionTime = String(retentionTime == null ? '' : retentionTime)
      } catch (error) {}
    },

    cancel() {
      this.$refs['ruleForm'].resetFields()
      this.triggerDialogVisible()
    },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.updatebackUpSet()
        } else {
          return false
        }
      })
    },

    async updatebackUpSet() {
      const param = {
        setupId: this.setupInfo.setupId,
        ...this.form
      }
      try {
        const { success } = await updateBackUpSet(param)
        if (success) {
          useMessage('success', '更新成功！')
          this.fetchTableData()
        }
      } catch (error) {}
      this.triggerDialogVisible()
    },

    async handRowRemove(row) {
      const { sysBackupId } = row
      const { success } = await backupRemove({ sysBackupId })
      if (success) {
        this.fetchTableData()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }
    },

    async toDetails(row) {
      this.fullscreenLoading = true
      try {
        await recover({ sysBackupId: row.sysBackupId })
        this.$message({
          type: 'success',
          message: '恢复成功! 跳转至首页'
        })
        setTimeout(() => {
          this.fullscreenLoading = false
          this.$store.dispatch('user/loginOut')
        }, 2000)
      } catch (error) {
        this.fullscreenLoading = false
      }
    },

    async toSend(row) {
      const { sysBackupId } = row
      try {
        const res = await exportBackupData({
          sysBackupId: sysBackupId
        })
        this.$resolveBlob(res)
        this.fetchTableData()
      } catch (error) {}
    },

    importBackup() {
      this.$refs.uploadDialog.open()
    },

    uploadSuccess() {
      setTimeout(() => {
        this.$store.dispatch('user/loginOut')
      }, 2000)
    },
    //导入
    importOperation() {
      this.$refs.ImportDialog.triggerDialog()
    },
    //导入回写
    ImportDialogCallBack() {}
  }
}
</script>

<style lang="scss" scoped>
.systemBackup {
  width: 100%;
  &-btn {
    margin-bottom: 10px;
  }
  &-table {
  }
  .size {
  }
}
</style>
