<template>
  <div id="app">
    <RouterView />
    <GlobalProgress />
    <CommonProgress :visible.sync="visible" :title="title" :percentage="percentage" text="正在下载升级包，请等待..." />
  </div>
</template>

<script>
import GlobalProgress from '@/components/GlobalProgress.vue';
import CommonProgress from '@/components/CommonProgress.vue';

import { GetSysVersionInfo } from '@/api/app';

export default {
  name: 'App',
  components: {
    GlobalProgress,
    CommonProgress,
  },
  data() {
    return {
      savePath: '',
      client_download_url: '',
      version: '',
      visible: false,
      percentage: 0,
    };
  },
  computed: {
    title() {
      return `下载升级包（当前版本 ${Number(process.env.VUE_APP_VERSION.replace(/\./g, ''))}，升级包版本 ${this.version}）`;
    },
  },
  mounted() {
    const isDev = process.env.NODE_ENV === 'development';
    if (isDev) return;
    this.getSysVersionInfo();
  },
  methods: {
    /**
     * 获取系统版本信息，并检查是否有新版本可用
     */
    getSysVersionInfo() {
      GetSysVersionInfo().then(({ version, client_download_url }) => {
        let curVersion = Number(process.env.VUE_APP_VERSION.replace(/\./g, ''));
        if (curVersion < version) {
          this.$confirm('新版本可用。是否下载最新版本？', '更新提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'primary',
          })
            .then(() => {
              this.version = version;
              this.client_download_url = client_download_url;
              this.selectDirectory();
            })
            .catch(() => {});
        }
      });
    },
    /**
     * 选择保存更新包的目录
     */
    async selectDirectory() {
      const result = await window.fileAPI.openFileDialog({
        title: '请选择保存更新包的文件夹',
        properties: ['openDirectory', 'createDirectory'],
      });
      if (result.canceled) {
        this.$message.warning('未选择文件夹，操作已取消');
        return;
      }
      this.savePath = result.filePaths[0];
      const downloadDir = `${this.savePath}\\智慧梧桐数字教材编辑器_${this.version}.exe`;
      this.visible = true;
      const unsubscribe = window.fileAPI.onDownloadProgress(({ percentage }) => {
        this.percentage = percentage;
      });
      try {
        await window.fileAPI.downloadFile(this.client_download_url, downloadDir);
      } catch (err) {
        this.$message.error(`下载失败：${err && err.message}`);
      } finally {
        unsubscribe();
        this.visible = false;
      }
      await window.updateAPI.installUpdate(downloadDir); // 调用安装更新的API
      this.percentage = 0;
    },
  },
};
</script>
