import {tipView, updateView} from '@/static/app/js/updateView'
import {appVersionIsUpdateVersionPost} from '@/service'
import {dayjs} from '@/plugin/index'
import Config from "@/config";
import {i18n} from "@/locale";


// 比较版本号 v1 > v2 返回1，v1 < v2 返回-1，v1 = v2 返回0
export function compareVersion(v1: string | undefined, v2: string | undefined) {
    if (!v1 || !v2) {
        return 0
    }

    const v1Arr = v1.split('.')
    const v2Arr = v2.split('.')
    const len = Math.max(v1Arr.length, v2Arr.length)
    while (v1Arr.length < len) {
        v1Arr.push('0')
    }
    while (v2Arr.length < len) {
        v2Arr.push('0')
    }

    for (let i = 0; i < len; i++) {
        const num1 = parseInt(v1Arr[i])
        const num2 = parseInt(v2Arr[i])

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

// app版本更新
export function appUpdate() {
    if (!plus?.runtime?.appid) {
        return
    }
    plus?.runtime?.getProperty(plus?.runtime?.appid, async (info) => {
        const currentVersion = info.version as string
        const platform = plus?.os?.name

        console.log('info', platform, platform === 'iOS', info)


        if (platform === 'Android') {
            await updateAndroid(currentVersion, platform)
        } else if (platform === 'iOS') {
            await updateIos(currentVersion, platform)
        }
    })
}

async function updateAndroid(currentVersion: string, platform: string) {
    try {
        const res = await appVersionIsUpdateVersionPost({
            body: {
                port: 2,
                // 设备类型：1-安卓(默认) 2-ios
                appType: 1,
            }
        })
        console.log('res', res)
        const versionInfo: AppVersion = res.data
        const newVersion = versionInfo?.versionNo
        const result = compareVersion(currentVersion, newVersion)
        console.log(result)
        // 本地版本最新
        if (result >= 0) {
            return
        }
        if (+versionInfo.isForce === 1) {
            installApp(versionInfo.url)
        } else {
            tipView.viewHotFixInit(versionInfo, platform)
        }
    } catch (e) {
    }
}

async function updateIos(currentVersion: string, platform: string) {

    const res = await appVersionIsUpdateVersionPost({
        body: {
            port: 2,
            // 设备类型：1-安卓(默认) 2-ios
            appType: 2,
        }
    })
    console.log('res', res)
    const versionInfo: AppVersion = res.data
    const newVersion = versionInfo?.versionNo
    const result = compareVersion(currentVersion, newVersion)
    console.log(result)
    // 本地版本最新
    if (result >= 0) {
        return
    }
    if (+versionInfo.isForce === 1) {
        installApp(versionInfo.url)
    } else {
        tipView.viewHotFixInit(versionInfo, platform)
    }
}

async function updateIosOnline(currentVersion: string, platform: string, versionInfo: AppVersion) {
    const res = await uni.request({
        method: 'POST',
        url: `https://itunes.apple.com/lookup?id=${Config.iosId}`,
    })
    console.log('iOS', res)
    // @ts-ignore
    const {currentVersionReleaseDate, version} = res?.data?.results[0] ?? {}

    const res1 = await uni.request({
        method: 'POST',
        url: `https://itunes.apple.com/cn/lookup?id=${Config.iosId}`,
    })
    console.log('iOS', res1)

    const {
        currentVersionReleaseDate: currentVersionReleaseDate1,
        version: version1
        // @ts-ignore
    } = res1?.data?.results[0] ?? {}

    if (version || version1) {
        if (currentVersionReleaseDate && version && currentVersionReleaseDate1 && version1) {
            let newVersion
            if (dayjs(currentVersionReleaseDate).isSameOrAfter(currentVersionReleaseDate1)) {
                newVersion = version
            } else {
                newVersion = version1
            }
            const result = compareVersion(currentVersion, newVersion)
            // 本地版本最新
            if (result >= 0) {
                return
            }

            tipView.viewHotFixInit(versionInfo, platform)

        } else {
            const result = compareVersion(currentVersion, version || version1)
            // 本地版本最新
            if (result >= 0) {
                return
            }
            tipView.viewHotFixInit(versionInfo, platform)

        }
    }

}

// app安装
export function installApp(downloadUrl: string) {
    updateView.viewHotFixInit()
    uni
        .downloadFile({
            url: downloadUrl,
            complete: (res) => {
                console.log('res', downloadUrl, res)
                updateView.viewHotFixHide()
                if (res && res.statusCode === 200) {
                    plus.runtime.install(
                        (res.tempFilePath),
                        {
                            force: true
                        },
                        function (widgetInfo) {
                            console.log(widgetInfo)
                            uni.showToast({
                                title: i18n.global.t('common.prompt.update-successfully'),
                                icon: 'none',
                                position: 'bottom',
                                duration: 2000,
                            })
                            setTimeout(() => {
                                plus.runtime.restart()
                            }, 1000)

                        },
                        function (error) {
                            console.log(error)
                            uni.showToast({
                                title: i18n.global.t('common.prompt.update-failed'),
                                icon: 'none',
                                position: 'bottom',
                                duration: 2000,
                            })
                        },
                    )
                } else {
                    uni.showToast({
                        title: i18n.global.t('common.prompt.download-failed'),
                        icon: 'none',
                        position: 'bottom',
                        duration: 2000,
                    })
                }
            },
        })
        .onProgressUpdate((res) => {
            // console.log('下载进度' + res.progress);
            updateView.viewHotFixUpdate(res.progress)
        })
}
