<script>
import { ipcRenderer } from "electron";
import pkg from "../../../package.json";
import axios from "@/utils/axios";
const {
  setSkip,
  getSkipValue,
  setSkipVersion,
  getSkipVersion,
} = require("@/server/utils/store");

export default {
  data() {
    return {
      visible: false,
      version: pkg.version,
      downloaded: false,
      percent: 0,
      loading: false,
      speed: 0,
      item: {},
      skipVersion: "",
    };
  },
  created() {
    let that = this;

    ipcRenderer.on("update", (event, data) => {
      console.log("下載進度", data);
      if (!that.loading) that.loading = true;
      that.percent = data.percent;
      that.speed = data.speed;
    });

    ipcRenderer.on("update-error", (event, data) => {
      console.log(data);
      that.$message.error(`安装包下载失败`);
      that.loading = false;
    });
    ipcRenderer.on("downloaded", () => {
      that.loading = false;
      that.download();
    });
    // this.getSkipVersionFn();
  },
  methods: {
    async checkUpdate() {
      return new Promise((resolve, reject) => {
        try {
          axios
            .get(`/manage/rest/app/checkUpdate?version=${this.version}`)
            .then((res) => {
              resolve(res.data);
            })
            .catch((err) => {
              reject(err);
            });
        } catch (err) {
          reject(err);
        }
      });
    },
    download() {
      this.$confirm("新版本已下载，是否立即安装？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        showCancelButton: this.item.forcedUpdate === 0,
        showClose: this.item.forcedUpdate === 0,
        type: "success",
      })
        .then(() => {
          ipcRenderer.send("install");
          this.visible = false;
        })
        .catch(() => {});
    },
    incrementalUpdates() {
      this.$confirm("新版本已下载，是否刷新页面", "提示", {
        confirmButtonText: "确定",
        showCancelButton: this.item.forcedUpdate === 0,
        showClose: this.item.forcedUpdate === 0,
        cancelButtonText: "取消",
        type: "success",
      })
        .then(() => {
          window.location.reload();
        })
        .catch(() => {});
    },
    async toUpdate(type) {
      if (type === 1) {
        this.visible = false;
        if (this.loading) return;
      } else {
        this.loading = true;
      }
      if (!this.item.fileList || this.item.fileList.length === 0) {
        return this.$message.warning("缺少更新文件");
      }
      console.log("开始下载");
      if (this.item.fullUpdate) {
        // 全量更新
        const domain = "https://console.jomalls.com";
        this.item.url =
          domain + this.item.fileList[0].versionPath.replace("/data", "");
        console.log(this.item.url);
        ipcRenderer.send("toUpdateApp", this.item);
      } else {
        try {
          this.loading = false;
          await this.$api.post("/incrementalUpdates", {
            url: this.item.fileList[0].fileUrl.replace("/data", ""),
          });
          this.incrementalUpdates();
        } catch (e) {
          // this.$message.warning("更新失败");
        }
      }
    },
    open(data, type) {
      // console.log("更新", data);
      this.item = data;
      this.visible = true;

      if (this.version == this.item.version) {
        setSkip(2);
        setSkipVersion("1.0");
      }
      if (type == 2) {
        setSkip(2);
        setSkipVersion("1.0");
      }
    },
    skipUpdate() {
      setSkip(1);
      setSkipVersion(this.item.version);
      this.visible = false;
    },
    getSkipValueFn() {
      const isSkip = getSkipValue();
      const version = getSkipVersion();

      return { isSkip, version };
    },
  },
};
</script>

<template>
  <el-dialog
    v-if="
      getSkipValueFn().isSkip == 2 && getSkipValueFn().version !== item.version
    "
    :show-close="item.forcedUpdate === 0"
    destroy-on-close
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    width="500px"
    :title="item.title"
    :visible.sync="visible"
  >
    <pre>{{ item.content }}</pre>
    <!--    <el-progress  :text-inside="true" :stroke-width="26" :percentage="percent"></el-progress>-->
    <template slot="footer">
      <div style="display: flex;justify-content: space-between;">
        <div>
          <el-button @click="skipUpdate" size="small">跳过更新 </el-button>
        </div>
        <div>
          <el-button
            @click="visible = false"
            v-if="item.forcedUpdate === 0"
            size="small"
            >关闭
          </el-button>
          <el-button
            @click="toUpdate(2)"
            size="small"
            type="primary"
            :loading="loading"
          >
            {{ loading ? `正在下载中（${percent}%）` : "确定更新" }}
          </el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="less"></style>
