<template>
    <view class="hc-update-app-box" v-if="isShow">
        <view class="update-head-bar">
            <view class="head-bar">
                <image class="head-img" src="/static/update/1.png"/>
                <view class="relative flex">
                    <view class="flex-1 text-white hc-p">
                        <view class="text-34">发现新版本</view>
                        <view class="mt-2">v{{versionData.versionNumber}}</view>
                    </view>
                    <view class="relative top--60 right-40">
                        <c-lottie src='/static/update/2.json' width="240rpx" height='240rpx' :loop="true"/>
                    </view>
                </view>
            </view>
            <view class="update-content-bar hc-p">
                <scroll-view scroll-y>
                    <view class="text-gray-5 text-26">{{versionData.updateDate}}</view>
                    <view class="mt-1">本次更新升级内容：</view>
                    <view class="mt-3 text-gray-6" style="white-space: pre;">{{versionData.updateContent}}</view>
                </scroll-view>
            </view>
            <view class="update-action-bar">
                <view class="relative hc-p" v-if="isDownload">
                    <view class="hc-flex justify-between mb-1">
                        <view class="text-24 text-gray-5">已下载：{{downloaded}}</view>
                        <view class="text-24 text-gray-5">总大小：{{totalFileSize}}</view>
                    </view>
                    <uv-line-progress :percentage="downloadNum"/>
                </view>
                <template v-else>
                    <view class="hc-flex hc-p" v-if="versionData.constraintUpdate !== 1">
                        <button class="cu-btn bg-blue-5 text-white flex-1 mr-2" @click="updateClick">立即更新</button>
                        <button class="cu-btn bg-gray-4 text-white flex-1 ml-2" @click="nextTap">下次再说</button>
                    </view>
                    <view class="hc-flex hc-p" v-else>
                        <button class="cu-btn bg-blue-5 text-white flex-1" @click="updateClick">立即更新</button>
                    </view>
                </template>
            </view>
        </view>
    </view>
</template>

<script setup>
import {onMounted, ref, watch} from "vue";
import {getVersionData} from "~api/other";
import website from '@/config/index';
import {getObjValue} from "js-fast-way";
import {filterSize} from "@/utils/utils";
import {errorToast, successToast} from "@/utils/tools";
import {useAppStore} from "@/store";

//初始变量
const store = useAppStore()
const isShow = ref(false)
const onUpdate = ref(store.onUpdate)
const appUpdate = ref(store.appUpdate)
const appInfo = ref({osName: '', version: ''})

//渲染完成
onMounted(() => {
    const {appVersion, appWgtVersion, osName} = uni.getSystemInfoSync();
    let version = appVersion
    if (appVersion === appWgtVersion) {
        version = appVersion
    } else if (!appVersion && appWgtVersion) {
        version = appWgtVersion
    } else if (appVersion && !appWgtVersion) {
        version = appVersion
    } else if (appVersion > appWgtVersion) {
        version = appVersion
    } else if (appVersion < appWgtVersion) {
        version = appWgtVersion
    }
    appInfo.value = {osName: osName, version: version}
    appUpdate.value.appVersion = version
    getVersionDataApi()
})

//监听
watch(() => [
    store.onUpdate
], ([val]) => {
    if (val) {
        const { version } = appInfo.value
        const { versionNumber } = versionData.value
        if (versionNumber > version) {
            isShow.value = true
        }
    }
})

//获取新版本信息
const versionData = ref({})
const getVersionDataApi = async () => {
    const { osName, version } = appInfo.value
    const type = osName === 'ios' ? 2 : 1
    const { data } = await getVersionData({
        softwareType: type,
        platform: website.platform
    })
    const res = getObjValue(data)
    versionData.value = res
    appUpdate.value.version = res.versionNumber
    const toUpdate = appUpdate.value.toUpdate
    if (res.versionNumber > version) {
        appUpdate.value.isUpdate = true
        isShow.value = toUpdate
    } else {
        appUpdate.value.isUpdate = false
        appUpdate.value.toUpdate = false
    }
    store.setAppUpdate(appUpdate.value)
}

//立即强制更新
const isDownload = ref(false)
const updateClick = async () => {
    const {osName} = appInfo.value
    const {fileType, fileUrl} = versionData.value
    //ios的完整安装包
    if (osName === 'ios' && fileType === 0) {
        plus.runtime.openURL(fileUrl)
        return false
    }
    //其他类型，安卓、ios的热更新包
    downloadFile(fileUrl)
}

//下载相关文件资料
const downloadNum = ref(0)
const totalFileSize = ref('')
const downloaded = ref('')
const downloadFile = (fileUrl) => {
    isDownload.value = true
    const downloadTask = uni.downloadFile({
        url: fileUrl,
        success: ({statusCode, tempFilePath}) => {
            if (statusCode === 200) {
                installAppFile(tempFilePath)
            } else {
                errorToast('下载失败，请联系管理员')
                nextTap()
            }
        },
        fail: () => {
            errorToast('下载失败，请联系管理员')
            nextTap()
        }
    });
    downloadTask.onProgressUpdate((res) => {
        const {totalBytesExpectedToWrite, totalBytesWritten, progress} = getObjValue(res)
        totalFileSize.value = filterSize(totalBytesExpectedToWrite)
        downloadNum.value = progress
        downloaded.value = filterSize(totalBytesWritten)
    });
}

//安装相关资源文件
const installAppFile = (file) => {
    //0 完整安装包, 1 wgt热更新包
    const {fileType} = versionData.value
    plus.runtime.install(file, {
        force: false
    }, function() {
        successToast('本次升级成功')
        setTimeout(() => {
            plus.runtime.restart();
        }, 1500)
    }, function(e) {
        console.log(e)
        errorToast('本次升级失败，请联系管理员')
        nextTap()
    });
}

//下次再说
const nextTap = () => {
    appUpdate.value.toUpdate = false
    store.setAppUpdate(appUpdate.value)
    isShow.value = false
    isDownload.value = false
}
</script>

<style scoped lang="scss">
@import "./style.scss";
</style>
