<template>
  <div class="package-manage">
    <el-row :gutter="20" type="flex">
      <el-col :span="12">
        <el-card class="card-box upload-card" header="包上传">
          <el-form>
            <el-form-item label="文件类型：">
              <el-select v-model="fileType" :disabled="loading">
                <el-option value="INSTALL" label="安装包"></el-option>
                <el-option value="UPGRADE" label="升级包"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <el-upload
            drag
            action="/api/admin/sys/client/package/upload"
            :accept="accept"
            :show-file-list="false"
            :on-error="handleError"
            :on-success="handleSuccess"
            :http-request="upload"
            :disabled="loading"
            :on-change="handleFileChange"
            ref="UploadComp"
          >
            <i class="el-icon-upload"></i><br />
            <em class="el-upload__text">点击或将文件拖拽到这里上传</em>
            <p
              slot="tip"
              :class="[
                `info-tips`,
                {
                  'tips-success': result.success,
                  'tips-error': !result.success,
                },
              ]"
              v-if="result.message"
            >
              {{ result.message }}
            </p>
          </el-upload>
          <div
            v-if="curProcess.filename && loading"
            class="upload-precess box-justify"
          >
            <div class="upload-name">
              <p>{{ curProcess.filename }}</p>
              <el-progress :percentage="curProcess.progress"></el-progress>
            </div>
            <i class="icon icon-close-act" @click="toDelete"></i>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="card-box package-card" header="包信息">
          <h3>
            安装包（更新时间：{{
              info.install.installUploadTime | timestampFilter
            }}）
          </h3>
          <p>
            <span>下载地址：</span>
            <a v-if="installUrl" :href="installUrl" download>
              {{ info.install.fileName }}</a
            >
            <span v-else>--</span>
          </p>

          <h3>
            升级包（更新时间：{{
              info.upgrade.upgradeUploadTime | timestampFilter
            }}）
          </h3>
          <p>
            <span>版本名称：</span
            ><span>{{ info.upgrade.version || "--" }}</span>
          </p>
          <p>
            <span>版本号：</span><span>{{ info.upgrade.build || "--" }}</span>
          </p>
          <p>
            <span>增量升级最低版本号：</span
            ><span>{{ info.upgrade.supportMin || "--" }}</span>
          </p>
          <p>
            <span>文件清单：</span>
            <a v-if="info.upgrade.index" :href="manfestUrl" download>
              mainfest.json
            </a>
            <span v-else>--</span>
          </p>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { packageInfo, uploadPackage } from "../api";
import { fileMD5 } from "@/plugins/md5";

export default {
  name: "package-manage",
  data() {
    return {
      info: {
        install: {},
        upgrade: {},
      },
      fileType: "INSTALL",
      result: {
        message: "",
        success: true,
      },
      curProcess: {
        filename: "",
        progress: 0,
      },
      loading: false,
      uploadController: null,
    };
  },
  computed: {
    installUrl() {
      return this.info.prefix
        ? `${this.info.prefix}/${this.info.install.url}`
        : "";
    },
    manfestUrl() {
      return this.info.prefix
        ? `${this.info.prefix}/${this.info.upgrade.index}`
        : "";
    },
    accept() {
      return this.fileType === "INSTALL" ? ".exe" : ".zip";
    },
  },
  mounted() {
    this.getInfo();
  },
  methods: {
    initData() {
      this.result = {
        message: "",
        success: true,
      };
      this.curProcess = {
        filename: "",
        progress: 0,
      };
      this.loading = false;
      this.uploadController = null;
    },
    async getInfo() {
      const res = await packageInfo();
      this.info = res || {};
    },
    handleFileChange(file) {
      if (file.status === "ready") {
        this.initData();
      }
      this.curProcess.filename = file.name;
    },
    async upload(options) {
      this.uploadController = new AbortController();
      this.loading = true;
      let formData = new FormData();
      formData.append("type", this.fileType);
      formData.append("file", options.file);
      const md5 = await fileMD5(options.file);
      formData.append("md5", md5);

      return uploadPackage(formData, {
        timeout: 60 * 60 * 1000,
        signal: this.uploadController.signal,
        onUploadProgress: ({ loaded, total }) => {
          this.curProcess.progress = Math.floor((100 * loaded) / total);
        },
      });
    },
    handleError(error) {
      const message = error.message === "canceled" ? "已取消" : error.message;

      this.loading = false;
      this.result = {
        success: false,
        message,
      };
    },
    handleSuccess(responseData) {
      this.loading = false;
      this.result = {
        success: true,
        message: "导入成功！",
      };
      this.initData();
      this.getInfo();
    },
    async toDelete() {
      const confirm = await this.$confirm(`确定要取消上传吗?`, "提示", {
        type: "warning",
      }).catch(() => {});
      if (confirm !== "confirm") return;

      this.uploadController && this.uploadController.abort();
      this.initData();
    },
  },
};
</script>
