<template>
  <el-dialog
    :visible.sync="dialogVisible"
    :show-close="false"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    title="系统版本更新"
    width="600px"
  >
    <div class="version-notification">
      <div class="version-info">
        <span class="label">{{ '版本号' }}：</span>
        <el-tag type="success" size="medium">v{{ versionInfo.version }}</el-tag>
      </div>
      <div v-if="versionInfo.title" class="version-info">
        <span class="label">{{ 'noticeTitle' }}：</span>
        <span>{{ versionInfo.title }}</span>
      </div>
      <div v-if="versionInfo.releaseTime" class="version-info">
        <span class="label">{{ '发布时间' }}：</span>
        <span>{{ versionInfo.releaseTime }}</span>
      </div>
      <div v-if="versionInfo.content" class="version-content">
        <div class="label">{{ '更新内容' }}：</div>
        <div class="content-body" v-html="versionInfo.content" />
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleConfirm">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getCurrentVersion } from '@/api/system/version'

export default {
  name: 'VersionNotification',
  data() {
    return {
      dialogVisible: false,
      versionInfo: {
        version: '',
        title: '',
        releaseTime: '',
        content: ''
      }
    }
  },
  methods: {
    hasShown() {
      return this.dialogVisible
    },
    /**
     * 检查版本是否需要弹窗
     * @param {string} serverVersion 服务端版本号
     */
    checkVersion(serverVersion) {
      const lastSeen = localStorage.getItem('lastSeenVersion')
      if (!serverVersion || serverVersion === lastSeen) {
        return
      }
      this.show(serverVersion)
    },
    /**
     * 显示版本更新弹窗
     * @param {string} serverVersion 版本号
     */
    show(serverVersion) {
      getCurrentVersion().then(res => {
        if (!res.enabled) return
        this.versionInfo.version = res.version || serverVersion
        this.versionInfo.title = res.title || ''
        this.versionInfo.releaseTime = res.releaseTime || ''
        this.versionInfo.content = res.content || ''
        this.dialogVisible = true
      })
    },
    handleConfirm() {
      localStorage.setItem('lastSeenVersion', this.versionInfo.version)
      this.dialogVisible = false
      // 点击后跳转到版本信息页面
      this.$router.push('/system/version')
    }
  }
}
</script>

<style scoped>
.version-notification {
  padding: 10px 0;
}
.version-info {
  margin-bottom: 12px;
  font-size: 14px;
}
.version-info .label {
  font-weight: bold;
  color: #303133;
}
.version-content {
  margin-top: 16px;
}
.version-content .label {
  font-weight: bold;
  color: #303133;
  margin-bottom: 8px;
}
.version-content .content-body {
  padding: 12px;
  background: #f5f7fa;
  border-radius: 4px;
  font-size: 14px;
  color: #606266;
  line-height: 1.8;
}
.dialog-footer {
  text-align: center;
}
</style>
