<template>
  <div class="version-container">
    <!-- 当前版本信息 -->
    <el-card class="version-card" style="margin-top: 20px">
      <div slot="header" class="card-header">
        <span>{{ $t('auto.version.currentInfo') }}</span>
      </div>
      <el-descriptions :column="2" border>
        <el-descriptions-item :label="$t('auto.version.versionNo')">
          <el-tag type="success">{{ currentVersion }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item :label="$t('auto.version.switch')">
          <el-tag
            :type="enabled ? 'success' : 'danger'"
          >{{ enabled ? $t('auto.version.enabled') : $t('auto.version.disabled') }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item
          :label="$t('auto.version.pollInterval')"
        >{{ pollInterval }}{{ $t('auto.version.seconds') }}</el-descriptions-item>
        <el-descriptions-item :label="$t('auto.version.releaseTime')">{{ releaseTime || '-' }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 版本历史列表 -->
    <el-card class="version-card" style="margin-top: 20px">
      <div slot="header" class="card-header">
        <span>版本历史</span>
      </div>
      <el-table v-loading="tableLoading" :data="tableData" style="width: 100%">
        <el-table-column prop="_versionNo" label="版本号" width="120" show-overflow-tooltip />
        <el-table-column prop="_noticeTitle" label="通知标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="notice_content" label="更新内容" min-width="300" show-overflow-tooltip />
        <el-table-column prop="create_time" label="发布时间" width="180" />
        <el-table-column v-if="isAdmin" label="操作" width="180" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button v-if="isAdmin" type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
              v-if="isAdmin"
              type="text"
              size="small"
              style="color: #f56c6c"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 发布版本表单（仅管理员可见） -->
    <el-card v-if="isAdmin" class="version-card">
      <div slot="header" class="card-header">
        <span>{{ $t('auto.version.releaseTitle') }}</span>
      </div>
      <el-form ref="publishForm" :model="publishForm" :rules="rules" label-width="100px">
        <el-form-item :label="$t('auto.version.versionNo')" prop="version">
          <el-input v-model="publishForm.version" placeholder="例如：2.7.0" style="width: 300px" />
        </el-form-item>
        <el-form-item :label="$t('auto.version.noticeTitle')" prop="title">
          <el-input v-model="publishForm.title" placeholder="例如：新增AGV多车调度功能" style="width: 500px" />
        </el-form-item>
        <el-form-item :label="$t('auto.version.content')" prop="content">
          <el-input
            v-model="publishForm.content"
            type="textarea"
            :rows="8"
            placeholder="请输入更新内容，支持HTML格式"
            style="width: 600px"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            v-if="isAdmin"
            type="primary"
            :loading="loading"
            @click="handleRelease"
          >{{ $t('auto.version.release') }}</el-button>
          <el-button @click="handleReset">{{ $t('auto.common.Reset') }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 编辑弹窗 -->
    <el-dialog title="编辑版本通知" :visible.sync="editDialogVisible" width="700px">
      <el-form ref="editForm" :model="editForm" :rules="editRules" label-width="100px">
        <el-form-item label="通知标题" prop="title">
          <el-input v-model="editForm.title" style="width: 520px" />
        </el-form-item>
        <el-form-item label="更新内容" prop="content">
          <el-input
            v-model="editForm.content"
            type="textarea"
            :rows="8"
            placeholder="请输入更新内容，支持HTML格式"
            style="width: 520px"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="editLoading" @click="submitEdit">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCurrentVersion,
  releaseVersion,
  listVersions,
  updateVersion,
  deleteVersion
} from '@/api/system/version'

export default {
  name: 'VersionRelease',
  data() {
    return {
      // 发布表单
      loading: false,
      publishForm: {
        version: '',
        title: '',
        content: ''
      },
      rules: {
        version: [{ required: true, message: '请输入版本号', trigger: 'blur' }],
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }]
      },
      // 当前版本信息
      currentVersion: '',
      enabled: false,
      pollInterval: 30,
      releaseTime: '',
      // 表格
      tableLoading: false,
      tableData: [],
      // 编辑弹窗
      editDialogVisible: false,
      editLoading: false,
      editForm: {
        id: '',
        title: '',
        content: ''
      },
      editRules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }]
      }
    }
  },
  computed: {
    /**
     * 判断当前用户是否为管理员
     * @returns {boolean}
     */
    isAdmin() {
      const roles = this.$store.getters && this.$store.getters.roles
      return roles && roles.includes('admin')
    }
  },
  mounted() {
    this.fetchCurrentVersion()
    this.fetchList()
  },
  methods: {
    fetchCurrentVersion() {
      getCurrentVersion().then(res => {
        this.currentVersion = res.version || '-'
        // 表单默认填充当前版本号，供管理员参考修改
        this.publishForm.version = res.version || ''
        this.enabled = res.enabled
        this.pollInterval = res.pollInterval || 30
        this.releaseTime = res.releaseTime || ''
      })
    },
    fetchList() {
      this.tableLoading = true
      listVersions({ page: 0, size: 999 })
        .then(res => {
          // notice_title 格式为 "version title"，拆分出版本号和标题
          this.tableData = (res.records || []).map(item => {
            const titleStr = item.notice_title || ''
            const idx = titleStr.indexOf(' ')
            const versionNo = idx >= 0 ? titleStr.substring(0, idx) : titleStr
            const noticeTitle = idx >= 0 ? titleStr.substring(idx + 1) : ''
            return {
              ...item,
              _versionNo: versionNo,
              _noticeTitle: noticeTitle
            }
          })
        })
        .finally(() => {
          this.tableLoading = false
        })
    },
    handleRelease() {
      this.$refs.publishForm.validate(valid => {
        if (!valid) return
        this.loading = true
        releaseVersion(this.publishForm)
          .then(() => {
            this.$message.success('版本更新通知已发布')
            this.handleReset()
            this.fetchCurrentVersion()
            this.fetchList()
          })
          .finally(() => {
            this.loading = false
          })
      })
    },
    handleReset() {
      this.publishForm = {
        version: '',
        title: '',
        content: ''
      }
      this.$refs.publishForm && this.$refs.publishForm.clearValidate()
    },
    handleEdit(row) {
      this.editForm = {
        id: row.notice_id,
        title: row.notice_title,
        content: row.notice_content || ''
      }
      this.editDialogVisible = true
      this.$nextTick(() => {
        this.$refs.editForm && this.$refs.editForm.clearValidate()
      })
    },
    submitEdit() {
      this.$refs.editForm.validate(valid => {
        if (!valid) return
        this.editLoading = true
        updateVersion(this.editForm)
          .then(() => {
            this.$message.success('修改成功')
            this.editDialogVisible = false
            this.fetchList()
          })
          .finally(() => {
            this.editLoading = false
          })
      })
    },
    handleDelete(row) {
      this.$confirm('确认删除该版本通知？', '提示', { type: 'warning' }).then(
        () => {
          deleteVersion(row.notice_id).then(() => {
            this.$message.success('删除成功')
            this.fetchList()
            this.fetchCurrentVersion()
          })
        }
      )
    }
  }
}
</script>

<style scoped>
.version-container {
  padding: 20px;
}
.version-card {
}
.card-header {
  font-weight: bold;
}
.dialog-footer {
  text-align: center;
}
</style>
