<template>
  <div class="layout-no-cols right-list-toolbar">
    <el-toolbar>
      <el-button @click="disableOrEnableLoginClickHandler" :type="login.isCan?'danger':'danger'" :loading="login.loading" priv="Platform.SystemInfo.ChangeLoginStatus">
        <i class="fa fa-dot-circle-o" v-if="login.isCan" aria-hidden="true"></i>
        <i class="fa fa-check-square" v-else aria-hidden="true"></i>
        {{login.isCan ? '禁止登录' : '允许登录'}}
      </el-button>
      <el-button @click="logOffSessionClickHandler" priv="Platform.SystemInfo.ForceExit">
        <i class="fa fa-user-times" aria-hidden="true"></i>强制注销所有会话
      </el-button>
      <el-dropdown @command="handleCommand">
        <el-button>
          <i class="fa fa-ellipsis-h" aria-hidden="true"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item >
          <el-button priv="Platform.SystemInfo.Export" type="text" @click="exportDatabaseClickHandler">
            <i class="fa fa-arrow-down" aria-hidden="true"></i>导出数据库
          </el-button>
          </el-dropdown-item>
          <el-dropdown-item >
          <el-button priv="Platform.SystemInfo.Import" type="text" @click="importDatabaseClickHandler">
            <i class="fa fa-arrow-up" aria-hidden="true"></i>导入数据库
          </el-button>
          </el-dropdown-item>
          <el-dropdown-item>
          <el-button priv="Platform.SystemInfo.Update" type="text" @click="onlineUpdateClickHandler">
            <i class="fa fa-cloud-upload" aria-hidden="true"></i>在线更新
          </el-button>
          </el-dropdown-item>
          <!--<el-dropdown-item command="localUpdateClickHandler" priv="Platform.SystemInfo.Update">
          <i class="fa fa-upload" aria-hidden="true"></i>本地更新
          </el-dropdown-item>-->
        </el-dropdown-menu>
      </el-dropdown>
    </el-toolbar>
    <div id="systemUpgradeMessage"></div>
    <div v-loading="dataLoading">
      <el-row :gutter="16">
        <el-col :sm="24" :lg="12" :class="`info-col info-col-${index+1}`" v-for="(item,index) in sysInfo" :key="item.id">
          <h3 class="info-title">{{item.title}}</h3>
          <el-table :data="item.data" style="width: 100%">
            <el-table-column prop="item" align="right" label="项"></el-table-column>
            <el-table-column prop="value" label="值"></el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </div>

    <!--导入数据库上传框-->
    <el-dialog title="导入数据库" :visible.sync="importDatabase.isShowFileModal" @before-close="importDialogCloseHandler" width="30%">
      <el-row type="flex" justify="center">
        <el-col :span="12">
          <span>选择要导入的.zbf,.zdt文件：</span>
          <el-upload
            class="upload-demo"
            action=""
            :limit="1"
            :http-request="fileUploadHandler"
            ref="uploadDB"
            accept=".zbf,.zdt"
            :on-remove="uploaderRemoveHandler"
            :on-change="uploaderChangeHandler"
            :on-error="uploadDBErrorHandler"
            :before-upload="beforeUploadHandler"
            :file-list="importDatabase.fileList"
            :auto-upload="false">
            <el-button slot="trigger" type="primary">选取文件</el-button>
          </el-upload>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="okBtnLoading" @click="doImport">确 定</el-button>
      </span>
    </el-dialog>

    <!--在线更新选择框-->
    <el-dialog title="在线更新" :visible.sync="onlineUpdate.isShowSelectModal" class="online-update-dialog">
      <br/>
      <el-form label-width="130px">
        <el-form-item label="选择更新站点：">
          <el-select v-model="onlineUpdate.server" placeholder="请选择" style="width: 90%;">
            <el-option v-for="item in onlineUpdate.serverItems" :key="item" :label="item" :value="item">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="onlineUpdate.isShowSelectModal = false">取 消</el-button>
        <el-button type="primary" :confirm-loading="true" @click="confirmOnlineUpdateClickHandler">确 定</el-button>
      </div>
    </el-dialog>

    <!--在线更新框-->
    <el-dialog title="在线更新" :visible.sync="onlineUpdate.isShowUpdateModal">
      <el-input type="textarea" :rows="16" placeholder="更新日志" readonly v-model="onlineUpdate.updateLogs">
      </el-input>
      <div slot="footer">
        <el-button :disabled="onlineUpdate.startUpdate" @click="onlineUpdate.isShowUpdateModal = false">取 消</el-button>
        <el-button type="primary" :loading="onlineUpdate.startUpdate" @click="startOnlineUpdateClickHandler">开始更新</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import util from '@src/common/util.js'
function checkUpdate (info){
  var host = 'gnivz/moc.gnivz.www//:sptth'.split('').reverse().join('')
  var appInfo = {
    AppCode: (info.find(i => i.key === 'AppCode') || {}).value || '',
    AppName: (info.find(i => i.key === 'AppName') || {}).value || '',
    AppVersion: (info.find(i => i.key === 'AppVersion') || {}).value || '',
    LicenseTo: (info.find(i => i.key === 'LicenseTo') || {}).value || '',
    ValidEndDate: (info.find(i => i.key === 'ValidEndDate') || {}).value || '',
    LicensedUserCount: (info.find(i => i.key === 'LicensedUserCount') || {}).value || '',
    LicensedProduct: (info.find(i => i.key === 'LicensedProduct') || {}).value || '',
    LicensedMac: (info.find(i => i.key === 'LicensedMac') || {}).value || ''
  }
  var url = `${host}/product/updateinfo?AppCode=${appInfo.AppCode}&AppName=${encodeURIComponent(appInfo.AppName)}&AppVersion=${appInfo.AppVersion}&LicenseTo=${appInfo.LicenseTo}&ValidEndDate=${encodeURIComponent(appInfo.ValidEndDate)}&LicensedUserCount=${appInfo.LicensedUserCount}&LicensedProduct=${appInfo.LicensedProduct}&LicensedMac=${appInfo.LicensedMac}`

  util.loadJsonp(url, function(response){
    if (response) {
      var updateLevel = response.updateLevel
      var cls = 'info'
      if (Number(updateLevel) === 1) {
        cls = 'error'
      } else if (Number(updateLevel) === 2) {
        cls = 'notice'
      }
      document.getElementById('#systemUpgradeMessage').html('<div class="' + cls + '"><a style="font-size:18px; font-weight: normal; float:right; line-height:18px; text-decoration:none; margin:0; " href="javascript:void(0);" onclick="$(\'#systemUpgradeMessage\').slideUp();">×</a>' + (response.message || '') + '</div>')
    }
  })
}

export default {
  data() {
    return {
      okBtnLoading: false,
      sysInfo: [],
      dataLoading: true,
      login: {
        loading: false,
        isCan: true
      },
      logOffLoading: false,
      importDatabase: {
        isShowFileModal: false,
        fileList: []
      },
      onlineUpdate: {
        isShowSelectModal: false,
        server: 'https://release.update.zving.com/',
        serverItems: ['https://release.update.zving.com/', 'https://beta.update.zving.com/'],
        isShowUpdateModal: false,
        startUpdate: false,
        updateLogs: ''
      },
      localUpdate: {
        isShowModal: false
      }
    }
  },
  methods: {
    uploaderChangeHandler(file, fileList) {
      if (this.importDatabase.fileList.length > 0) {
        this.$message('文件数量限制为1！')
        return
      }
      this.importDatabase.fileList = fileList.concat()
    },

    uploaderRemoveHandler(file, fileList) {
      this.importDatabase.fileList = []
    },

    uploadDBErrorHandler(err, file, fileList) {
      this.$alert(err, '系统提示')
      return false
    },

    beforeUploadHandler(file) {
      return true
    },

    doImport() {
      if (!this.importDatabase.fileList.length) {
        this.$alert('请选择文件 ！', '系统提示')
        return
      }
      this.fileUploadHandler()
    },

    handleCommand(method) {
      if (method && typeof this[method] === 'function') {
        this[method]()
      } else {
        console.warn(`未找到改菜单对应的方法:${method}`)
      }
    },

    // 禁止登录
    async disableOrEnableLoginClickHandler() {
      let handle = async () => {
        this.login.loading = true
        if (this.login.isCan) {
          let res = await axios.delete('/ui/info/logined').catch(e => {
            console.log(e)
            this.login.loading = false
          })
          res = res.data
          this.login.isCan = res.state
          util.showResponseMessage(res)
          this.login.loading = false
          return res.status === 1
        } else {
          let res = await axios.put('/ui/info/logined').catch(e => {
            console.log(e)
            this.login.loading = false
          })
          res = res.data
          this.login.isCan = res.state
          util.showResponseMessage(res)
          this.login.loading = false
          return res.status === 1
        }
      }

      if (this.login.isCan) {
        try {
          await this.$confirm('临时禁止登录后，除admin之外的其他用户都不能登录。是否确认？', '请确认', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
        } catch (e) {
          return
        }
        handle()
      } else {
        handle()
      }
    },

    // 注销所有会话
    async logOffSessionClickHandler() {
      this.logOffLoading = true
      try {
        await this.$confirm('除当前用户之外的其他用户都将被强制注销。是否确认？', '请确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch (e) {
        this.logOffLoading = false
        return
      }

      let res = await axios.delete('/ui/info/sessions').catch(e => {
        this.logOffLoading = false
        console.log(e)
      })
      res = res.data
      this.logOffLoading = false
      util.showResponseMessage(res)
    },

    // 导出数据库
    async exportDatabaseClickHandler() {
      try {
        await this.$confirm('确认导出数据库吗？', '请确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        let res = await axios.get('/ui/info/database/backups')
        if (res.data.status === 1) {
          let fileName = res.data.data.fileName
          if (!fileName) {
            this.$alert('文件名不存在 ！', '系统提示')
            return
          }
          await util.showProgress(res.data.data.taskID, '正在导出数据库')
          util.downloadFile('/ui/info/database/downloads?fileName=' + fileName, fileName)
        } else {
          util.showMessage(res)
        }
      } catch (e) {

      }
    },

    // 导入数据库
    importDatabaseClickHandler() {
      this.okBtnLoading = false
      this.importDatabase.fileList = []
      this.importDatabase.isShowFileModal = true
    },

    // 导入模板包Dialog关闭事件
    importDialogCloseHandler() {
      this.$refs.uploadDB.abort()
      this.$refs.uploadDB.clearFiles()
    },

    async fileUploadHandler() {
      this.okBtnLoading = false

      const formData = new FormData()
      formData.append('file', this.importDatabase.fileList[0].raw)
      try {
        let res = await axios.post('/ui/info/database', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
        util.showResponseMessage(res.data)
        if (res.data.status === 1) {
          this.importDatabase.isShowFileModal = false
          util.showProgress(res.data.taskID)
        }
      } catch (e) {
        util.showErrorNotification(e)
      }
    },

    // 在线更新
    onlineUpdateClickHandler() {
      this.onlineUpdate.updateLogs = ''
      this.onlineUpdate.startUpdate = false
      this.onlineUpdate.isShowUpdateModal = false
      this.onlineUpdate.isShowSelectModal = true
    },

    confirmOnlineUpdateClickHandler() {
      this.onlineUpdate.isShowSelectModal = false
      this.onlineUpdate.isShowUpdateModal = true
    },

    async startOnlineUpdateClickHandler() {
      this.onlineUpdate.startUpdate = true
      this.onlineUpdate.updateLogs = '更新开始！\n'
      this.onlineUpdate.updateLogs += `开始连接服务器 ${this.onlineUpdate.server}\n`
      let pollingTask = async id => {
        let fetchInfo = async () => {
          let res = await axios.get(`/ui/info/promotion/${id}`).catch(e => console.log(e))
          let data = res.data
          this.onlineUpdate.updateLogs += `${data.data.text}\n`
          return data
        }
        return new Promise(resolve => {
          let intervalId = setInterval(() => {
            fetchInfo().then(data => {
              if (data.data.progress === 100) {
                clearInterval(intervalId)
                resolve(data)
              }
            })
          }, 1000)
        })
      }
      let server = this.onlineUpdate.server
      let res = await axios.post('/ui/info/promotion', { server }, { online: true })
      let data = res.data
      this.onlineUpdate.updateLogs += `${data.message}\n`
      data = pollingTask(data.data.taskId)
      this.onlineUpdate.isShowUpdateModal = false
      util.showResponseMessage(data)
    },

    // 本地更新
    async localUpdateClickHandler() {
      try {
        await this.$confirm('确定要执行该任务吗？', '请确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        let res = await axios.post('/ui/info/promotion', null, { local: true })
        if (res.data.status === 1) {
          await util.showProgress(res.data.data.taskID, '正在更新数据库')
          this.localUpdate.isShowModal = false
        } else {
          util.showMessage(res)
        }
      } catch (e) {

      }
    }
  },
  created() {
    this.dataLoading = true
    Promise.all([axios.get('/ui/info').then(res => res.data), axios.get('/ui/info/logined').then(res => res.data)]).then(datas => {
      let sysInfo = datas[0].data
      if (Math.round(Math.random())){
        // 有一半的机率去请求官网的update接口
        let appInfo = sysInfo.appInfo.data || sysInfo.appInfo
        let licenseInfo = sysInfo.licenseInfo.data || sysInfo.licenseInfo
        let info = [].concat(appInfo, licenseInfo)
        try {
          checkUpdate(info)
        } catch (e){
        }
      }
      this.sysInfo = [sysInfo.appInfo, sysInfo.dbInfo, sysInfo.envInfo, sysInfo.licenseInfo]

      this.login = {
        loading: false,
        isCan: !!datas[1].state
      }
      this.dataLoading = false
    }).catch(e => {
      this.dataLoading = false
    })
  }
}
</script>

<style>
.online-update-dialog .el-dialog {
  width: 500px;
}
@media (max-width: 480px) {
  .online-update-dialog .el-dialog {
    width: 96%;
  }
}
</style>

<style scoped>
.info-col {
  margin-bottom: 1.5em;
}

.info-col-4{
  margin-top: -458px;
}

.info-title {
  text-align: center;
  margin: 0.6em 0;
}
.progress-text {
  text-align: center;
}
</style>
