<template>
  <el-dialog
    :visible.sync="dialogVisible"
    :show-close="false"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :title="$t('auto.version.title')"
    width="600px"
  >
    <div class="version-notification">
      <div class="version-info">
        <span class="label">{{ $t('auto.version.versionNo') }}：</span>
        <el-tag type="success" size="medium">v{{ versionInfo.version }}</el-tag>
      </div>
      <div v-if="versionInfo.releaseTime" class="version-info">
        <span class="label">{{ $t('auto.version.releaseTime') }}：</span>
        <span>{{ versionInfo.releaseTime }}</span>
      </div>
      <div v-if="versionInfo.content" class="version-content">
        <div class="label">{{ $t('auto.version.content') }}：</div>
        <div class="content-body" v-html="versionInfo.content" />
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleConfirm">{{ $t('auto.version.confirm') }}</el-button>
    </div>
  </el-dialog>
</template>

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

export default {
  name: 'VersionNotification',
  data() {
    return {
      dialogVisible: false,
      versionInfo: {
        version: '',
        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.releaseTime = res.releaseTime || ''
        this.fetchVersionContent()
        this.dialogVisible = true
      })
    },
    fetchVersionContent() {
      // 从站内信获取最新的版本通知内容
      // 内容通过后端 /api/version/current 返回的 releaseTime 已含，
      // 如果需要额外展示详细内容，可调用通知接口查询
    },
    handleConfirm() {
      localStorage.setItem('lastSeenVersion', this.versionInfo.version)
      this.dialogVisible = false
    }
  }
}
</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>
