<template>
    <Dialog teleport="body" class="app-updater" v-model:show="show" :title="message ? '提示' : '下载中'"
        :show-confirm-button="showConfirmButton" :confirm-button-text="confirmButtonText" show-cancel-button
        :before-close="onbeforeClose" @confirm="onConfirm" @cancel="onCancel">
        <div class="app-updater-message" v-if="message">
            <span>{{ message }}</span>
        </div>
        <div class="app-updater-progress" v-else>
            <span class="app-updater-progress__bar" :style="styles"></span>
            <span class="app-updater-progress__text">{{ downloadProgress.toFixed(0) }}%</span>
        </div>
    </Dialog>
</template>

<script lang="ts" setup>
import { shallowRef, computed, onMounted, onUnmounted } from 'vue'
import { Dialog } from 'vant'
import { versionToNumber } from '@/filters'
import { GetAppUpdateInfo } from '@/services/api/common'
import plus from '@/utils/h5plus'

const props = defineProps({
    iosUpdateUrl: String
})

const show = shallowRef(false)
const pending = shallowRef(true) // 是否进行中状态
const showConfirmButton = shallowRef(true)
const message = shallowRef('')
const confirmButtonText = shallowRef('')
const downloadUrl = shallowRef('') // 下载地址
const downloadProgress = shallowRef(0) // 下载进度
const fileUrl = shallowRef('') // 文件安装地址

const styles = computed(() => ({
    width: downloadProgress.value + '%'
}))

// 监听下载进度
const ondownload = plus.onDownloadProgress((progress) => {
    downloadProgress.value = progress
})

const onbeforeClose = () => {
    return false
}

const onConfirm = () => {
    const os = plus.getSystemInfo('os')
    if (os === 'iOS') {
        show.value = false
        plus.openURL(downloadUrl.value)
    } else if (downloadProgress.value === 100) {
        show.value = false
        plus.installApp(fileUrl.value)
    } else if (confirmButtonText.value === '隐藏') {
        show.value = false
    } else {
        message.value = ''
        confirmButtonText.value = '隐藏'
        plus.createDownload(downloadUrl.value).then((res) => {
            fileUrl.value = res.filename
            message.value = '下载完成，是否立即安装？'
            confirmButtonText.value = '安装'
        }).catch((err) => {
            message.value = err
            showConfirmButton.value = false
        }).finally(() => {
            show.value = pending.value
        })
    }
}

const onCancel = () => {
    if (fileUrl.value) {
        plus.deleteFile(fileUrl.value)
    }
    ondownload.cancel()
    pending.value = false
    show.value = false
}

onMounted(() => {
    const os = plus.getSystemInfo('os')
    const currentVersion = plus.getSystemInfo('version')
    const currentVersionCode = plus.getSystemInfo('versionCode')

    if (os === 'Android') {
        // 获取应用更新信息
        GetAppUpdateInfo().then((res) => {
            const data = JSON.parse(res)
            if (data) {
                const { LastVersionCode, ApkUrl } = data[0] as Model.AppUpdateInfo
                if (Number(LastVersionCode) > Number(currentVersionCode)) {
                    downloadUrl.value = ApkUrl
                    message.value = '发现新版本，是否更新？'
                    confirmButtonText.value = '下载'
                    show.value = true
                }
            }
        })
    }

    if (os === 'iOS' && props.iosUpdateUrl) {
        plus.httpRequest({
            url: props.iosUpdateUrl
        }).then((res) => {
            const results = res.data.results
            if (results?.length) {
                const { version, trackViewUrl } = results[0]
                if (versionToNumber(version) > versionToNumber(currentVersion)) {
                    downloadUrl.value = trackViewUrl
                    message.value = '发现新版本，是否更新？'
                    confirmButtonText.value = '更新'
                    show.value = true
                }
            }
        })
    }
})

onUnmounted(() => ondownload.cancel())
</script>

<style lang="less">
@import './index.less';
</style>