<template>
    <el-dialog v-model="showDialog" :title="`发现新版本v${newVersionRef}`" top="30vh" width="500" :close-on-click-modal="false"
        :close-on-press-escape="false" :show-close="false">
        <div class="message" v-html="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.isForce && !isUpload" @click="closeHandle">下次更新</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/system.js'
import packageData from "../../package.json";
import { ipcRenderer } from 'electron'
import useStorage from '@/utils/useStorage.js'

import { useUser } from "@/store/user.js";

const store = useUser()

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

// 关闭更新弹窗，下次登录在提示
function closeHandle() {
    showDialog.value = false
    useStorage.set('updateFlag', true)
}

// 检查版本更新
async function findVersionAjax() {
    try {
        let updateFlag = useStorage.get('updateFlag')
        const res = await findVersion()
        if (res && res.version) {
            const newVersion = res.version;
            const oldVersion = packageData.version;

            console.log('当前版本:', oldVersion);
            console.log('获取版本:', newVersion);

            const result = compareVersions(newVersion, oldVersion);
            if (result > 0) {
                if (!updateFlag) {
                    newVersionRef.value = newVersion
                    showDialog.value = true
                    updataInfo.value = res
                }
            }
        }
    } catch (error) {
        console.log('检查版本更新===', error);
    }
}

// 比较版本号
function compareVersions(version1, version2) {
    const v1 = version1.split('.').map(Number);
    const v2 = version2.split('.').map(Number);
    const maxLength = Math.max(v1.length, v2.length);

    for (let i = 0; i < maxLength; i++) {
        const num1 = v1[i] || 0;
        const num2 = v2[i] || 0;

        if (num1 > num2) {
            return 1;
        } else if (num1 < num2) {
            return -1;
        }
    }
    return 0;
}

// 下载新版本
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(() => {
    if (store.shopInfo.id) {
        findVersionAjax()
    }
    ipcRenderer.on('updateProgress', (event, res) => {
        uploadPro.value = res
    })
})
</script>