<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="getVersionInfo">刷新版本信息</el-button>
        <el-button type="success" icon="el-icon-upload" size="mini" @click="handleUpload" v-hasPermi="['system:version:upload']">上传新版本</el-button>
      </el-form-item>
    </el-form>
    <!-- 版本信息卡片 -->
    <el-row  class="mb8">
      <el-col s>
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>当前版本信息</span>
          </div>
          <div class="version-info">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="当前版本">
                <el-tag type="primary" size="medium">{{ versionInfo.currentVersion }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="更新时间">
                {{ parseTime(versionInfo.updateTime) }}
              </el-descriptions-item>
              <el-descriptions-item label="ASAR下载链接" v-if="versionInfo.asarUrl">
                <el-link :href="versionInfo.asarUrl" target="_blank" type="primary">
                  {{ versionInfo.asarUrl }}
                </el-link>
              </el-descriptions-item>
              <el-descriptions-item label="JAR下载链接" v-if="versionInfo.jarUrl">
                <el-link :href="versionInfo.jarUrl" target="_blank" type="success">
                  {{ versionInfo.jarUrl }}
                </el-link>
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 上传对话框 -->
    <el-dialog title="上传新版本" :visible.sync="uploadVisible" width="500px" append-to-body>
      <el-form ref="uploadForm" :model="uploadForm" :rules="uploadRules" label-width="100px">
        <el-form-item label="版本号" prop="version">
          <el-input v-model="uploadForm.version" placeholder="请输入版本号，如：2.4.7"></el-input>
        </el-form-item>
        <el-form-item label="更新内容" prop="updateNotes">
          <el-input v-model="uploadForm.updateNotes" type="textarea" :rows="4" placeholder="请输入更新内容"></el-input>
        </el-form-item>
        <el-form-item label="ASAR文件" prop="asarFile">
          <el-upload
            ref="asarUpload"
            action="#"
            :limit="1"
            accept=".asar"
            :on-exceed="handleAsarExceed"
            :file-list="asarFileList"
            :auto-upload="false"
            :on-change="handleAsarFileChange"
            :on-remove="handleAsarFileRemove">
            <el-button slot="trigger" size="small" type="primary">选择ASAR文件</el-button>
            <div slot="tip" class="el-upload__tip">只能上传asar文件，且不超过800MB</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="JAR文件" prop="jarFile">
          <el-upload
            ref="jarUpload"
            action="#"
            :limit="1"
            accept=".jar"
            :on-exceed="handleJarExceed"
            :file-list="jarFileList"
            :auto-upload="false"
            :on-change="handleJarFileChange"
            :on-remove="handleJarFileRemove">
            <el-button slot="trigger" size="small" type="success">选择JAR文件</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jar文件，且不超过200MB</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="uploadVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitUpload" :loading="uploadLoading">{{ uploadLoading ? '上传中...' : '确 定' }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getVersionInfo, uploadFile, updateVersion } from "@/api/monitor/version"

export default {
  name: "Version",
  data() {
    return {
      // 查询参数
      queryParams: {},
      // 显示搜索条件
      showSearch: true,
      // 版本信息
      versionInfo: {
        currentVersion: '2.0.0',
        updateTime: null,
        asarUrl: null,
        jarUrl: null
      },
      // 版本检查表单
      checkForm: {
        testVersion: '1.0.0'
      },
      // 检查结果
      checkResult: null,
      // 检查加载状态
      checkLoading: false,
      // 上传对话框
      uploadVisible: false,
      // 上传表单
      uploadForm: {
        version: '',
        updateNotes: '',
        asarFile: null,
        jarFile: null
      },
      // 上传规则
      uploadRules: {
        version: [
          { required: true, message: "版本号不能为空", trigger: "blur" },
          { pattern: /^\d+\.\d+\.\d+$/, message: "版本号格式不正确，应为x.y.z格式", trigger: "blur" }
        ],
        updateNotes: [
          { required: true, message: "更新内容不能为空", trigger: "blur" }
        ]
      },
      // 文件列表
      asarFileList: [],
      jarFileList: [],
      // 上传加载状态
      uploadLoading: false,
      // 上传进度
      uploadProgress: 0
    };
  },
  created() {
    this.getVersionInfo();
  },
  methods: {
    /** 查询版本信息 */
    getVersionInfo() {
      getVersionInfo().then(response => {
        this.versionInfo = response.data;
      });
    },

    /** 处理上传 */
    handleUpload() {
      this.uploadVisible = true;
      this.resetUploadForm();
    },
    /** 重置上传表单 */
    resetUploadForm() {
      this.uploadForm = {
        version: '',
        updateNotes: '',
        asarFile: null,
        jarFile: null
      };
      this.asarFileList = [];
      this.jarFileList = [];
      this.uploadProgress = 0;
      if (this.$refs.uploadForm) {
        this.$refs.uploadForm.resetFields();
      }
    },
    /** ASAR文件超出限制 */
    handleAsarExceed() {
      this.$modal.msgError("只能选择一个ASAR文件");
    },
    /** ASAR文件改变 */
    handleAsarFileChange(file, fileList) {
      this.uploadForm.asarFile = file.raw;
      this.asarFileList = fileList;
    },
    /** ASAR文件移除 */
    handleAsarFileRemove() {
      this.uploadForm.asarFile = null;
      this.asarFileList = [];
    },
    /** JAR文件超出限制 */
    handleJarExceed() {
      this.$modal.msgError("只能选择一个JAR文件");
    },
    /** JAR文件改变 */
    handleJarFileChange(file, fileList) {
      this.uploadForm.jarFile = file.raw;
      this.jarFileList = fileList;
    },
    /** JAR文件移除 */
    handleJarFileRemove() {
      this.uploadForm.jarFile = null;
      this.jarFileList = [];
    },
    /** 提交上传 */
    submitUpload() {
      this.$refs.uploadForm.validate(valid => {
        if (valid) {
          if (!this.uploadForm.asarFile && !this.uploadForm.jarFile) {
            this.$modal.msgError("请至少选择一个文件上传");
            return;
          }

          // 验证ASAR文件
          if (this.uploadForm.asarFile) {
            if (this.uploadForm.asarFile.size > 800 * 1024 * 1024) {
              this.$modal.msgError("ASAR文件大小不能超过800MB");
              return;
            }
            if (!this.uploadForm.asarFile.name.endsWith('.asar')) {
              this.$modal.msgError("只支持上传.asar文件");
              return;
            }
          }

          // 验证JAR文件
          if (this.uploadForm.jarFile) {
            if (this.uploadForm.jarFile.size > 200 * 1024 * 1024) {
              this.$modal.msgError("JAR文件大小不能超过200MB");
              return;
            }
            if (!this.uploadForm.jarFile.name.endsWith('.jar')) {
              this.$modal.msgError("只支持上传.jar文件");
              return;
            }
          }

          this.uploadLoading = true;

          const formData = new FormData();
          if (this.uploadForm.asarFile) {
            formData.append('files', this.uploadForm.asarFile);
          }
          if (this.uploadForm.jarFile) {
            formData.append('files', this.uploadForm.jarFile);
          }

          uploadFile(formData).then(response => {
            if (response && response.data) {
              let asarUrl = null;
              let jarUrl = null;

              // 解析上传结果
              response.data.forEach(fileInfo => {
                const url = fileInfo.fileUrl || fileInfo.url;
                if (fileInfo.fileName && fileInfo.fileName.endsWith('.asar')) {
                  asarUrl = url;
                } else if (fileInfo.fileName && fileInfo.fileName.endsWith('.jar')) {
                  jarUrl = url;
                }
              });

              updateVersion({
                version: this.uploadForm.version,
                asarUrl: asarUrl,
                jarUrl: jarUrl,
                updateNotes: this.uploadForm.updateNotes
              }).then(() => {
                this.$modal.msgSuccess("版本文件上传成功");
                this.uploadVisible = false;
                this.uploadLoading = false;
                this.getVersionInfo();
              });
            }
          }).catch(() => {
            this.$modal.msgError("文件上传失败");
            this.uploadLoading = false;
          });
        }
      });
    }
  }
};
</script>

<style scoped>
.version-info {
  margin-top: 10px;
}
.box-card {
  margin-bottom: 20px;
}
</style>
