<template>
    <el-dialog v-model="showDialog" title="发现新版本" width="500" :close-on-click-modal="false"
        :close-on-press-escape="false" :show-close="false">
        <div class="message">
            {{ updataInfo.message }}
        </div>
        <div class="progress_wrap" style="padding-top: 20px;">
            <el-progress :percentage="uploadPro" :stroke-width="15" striped :striped-flow="uploadPro < 100" />
        </div>
        <template #footer>
            <div class="footer" style="padding: 0 20px 20px;">
                <el-button v-if="!updataInfo.isUp">下次更新</el-button>
                <el-button type="primary" :loading="isUpload" @click="uplaodHandle">
                    <template v-if="!uploadSucess">
                        <template v-if="!isUpload">
                            立即更新
                        </template>
                        <template v-else>
                            下载中...
                        </template>
                    </template>
                    <template v-else>
                        立即安装
                    </template>
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { findVersion } from '@/api/user.js'
import packageData from "../../../package.json";
import { ipcRenderer } from 'electron'

const showDialog = ref(false)
const updataInfo = ref({})
const isUpload = ref(false)
const uploadPro = ref(0)
const uploadSucess = ref(false)
const uploadResponse = ref({})
const tempFilePath = ref('')

// 检查版本更新
async function findVersionAjax() {
    try {
        const res = await findVersion()
        let reg = /\./g;
        if (res.version.replace(reg, '') > packageData.version.replace(reg, '') && res.url) {
            showDialog.value = true
            updataInfo.value = res
        }
    } catch (error) {
        console.log(error);
    }
}

// 下载新版本
async function uplaodHandle() {
    try {
        if (!uploadSucess.value) {
            isUpload.value = true
            ipcRenderer.send('downloadFile', JSON.stringify({ url: updataInfo.value.url }))
            // await downloadFile(updataInfo.value.url)
            // isUpload.value = false
            // uploadSucess.value = true
        } else {
            // 安装文件
        }
    } catch (error) {
        console.log(error);
    }
}

onMounted(() => {
    findVersionAjax()
    ipcRenderer.on('updateProgress', (event, res) => {
        // console.log('updateProgress===', event, res);
        uploadPro.value = res
    })
})
</script>