<template>
<view class="container" :style="{ height: `100vh` }">
    <view class="bg"></view>
    <view class="version">Version {{ appVersion }}</view>
    <!-- <view class="bottom-bg"></view> -->

    <!-- 检查版本弹窗 -->
    <view class="version-con" v-if="versionVisible">
        <view class="v-bg">
            <view class="v-title">发现新版本</view>
            <uni-icons custom-prefix="iconfont" color="#28B6FF" type="icon-phonefilled" size="40"></uni-icons>
            <view class="v-version">最新版本 Version {{ newVersion }}</view>
            <view class="v-update">立刻更新吗？</view>
            <view class="version-btn" @click="handleDown">更 新</view>
            <view class="version-sub" @click="handleClose" v-if="btnVisible">暂不处理</view>
        </view>
    </view>
</view>

</template>

<script setup>
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { versionCheck,getBindStatus } from '@/api/auth.js';
import { formatIOS } from '@/utils/status.js'
import { requestAndroidPermissionAsync,requestAndroidPermission } from '@/utils/common.js'
import {showAlert} from '@/utils/message.js'
import { useUserStore } from '@/stores/user';
const userStore = useUserStore();

// #ifdef APP-PLUS
// 获取 存储手机的module 
const safeSave = uni.requireNativePlugin("Tm-TmSafeSaveFileModule");
// #endif

let systemInfo={};
let appVersion = ref("1.0.0");//当前版本号
let newVersion = ref('1.0.0');//最新版本号
let versionVisible=ref(false);//版本弹窗
let btnVisible = ref(true);// 暂不处理 按钮是否显示
let downloadURL = ref(''); //下载地址
let versionData = ref({}); //版本参数
// 初始load页面
onLoad(async(opt) => {
    console.log("onLoad");

    uni.preloadPage({url: "/pages/login/login"});
    uni.preloadPage({url: "/pages/deviceAuth/deviceAuth"});
    uni.preloadPage({url: "/pages/home/home"});

    // #ifdef APP-PLUS
    // 查询版本接口
    await getOSVesion();
    
    // 不更新版本 执行设备ID查询和绑定操作
    if(!versionVisible.value){
        try {
            // 授权设备存储
            // let result = {granted:false}
            // if(systemInfo.osVersion<13){
            //     let permissions = ['android.permission.READ_EXTERNAL_STORAGE', 'android.permission.WRITE_EXTERNAL_STORAGE'];
            //     result = await requestAndroidPermissionAsync(systemInfo,permissions);
            // }else if(systemInfo.osVersion==13){
            //     let permissions = ['android.permission.READ_MEDIA_IMAGES', 'android.permission.READ_MEDIA_VIDEO', 'android.permission.READ_MEDIA_AUDIO'];
            //     result = await requestAndroidPermissionAsync(systemInfo,permissions);
            // }else{
            //     let permissions = ['android.permission.READ_MEDIA_VISUAL_USER_SELECTED'];
            //     result = await requestAndroidPermissionAsync(systemInfo,permissions);
            // }

            // if (result.granted) {
            //     showAlert("11授权成功！")
            //     setTimeout(()=>{
            //         selectDeviceId();
            //     },500)
            // } else {
                let granted =  requestAndroidPermission(systemInfo);
                if(granted){
                    showAlert("22授权成功！")
                    setTimeout(()=>{
                        selectDeviceId();
                    },500)
                }
                // showAlert("您还没对设备授权，请授权！")
            // }
        } catch (error) {
            console.error('权限请求出错:', error);
            showAlert(JSON.stringify(error))
        }
    }
    // #endif

    // #ifdef H5
    setTimeout(()=>{
        if(userStore.isLogin){
            uni.reLaunch({
                url: '/pages/home/home',
            });
        }else{
            uni.reLaunch({
                url: '/pages/login/login',
            });
        }
    },2000)
    // #endif

});

// 检查版本是否是最新的s
const getOSVesion = async()=>{
    systemInfo = uni.getSystemInfoSync();
    let param = {
        // #ifdef APP-PLUS
        verNumber:systemInfo.appWgtVersion,//当前版本号
        // #endif
        // #ifdef H5
        verNumber : systemInfo.appVersion,
        // #endif
        // deviceType:systemInfo.model,//型号
        os: formatIOS(systemInfo.osName),//操作系统 Android  IOS
        // osVersion:systemInfo.osVersion,//操作系统版本
        // resolution:systemInfo.windowWidth+"*"+systemInfo.windowHeight,//分辨率
        // trademark:systemInfo.deviceBrand,//设备品牌
        // uniqueCode:systemInfo.deviceId//设备ID
    }
    // 当前手机版本
    appVersion.value = param.verNumber;
    // console.log("appVersion=>",appVersion)
    versionData.value = param;
    let data = await versionCheck(param);
    newVersion.value = data.verNumber;
    downloadURL.value = data.downloadUrl || '';

    // isForceUpdate 是否强制更新 1-是 2-否
    let isForceUpdate = data.isForceUpdate;
    if(isForceUpdate==1){
        btnVisible.value = false;
    }else{
        btnVisible.value = true;
    }
    // 是否为当前最新版本(是=1，否=2)
    let isCurrent = data.isCurrent;
    if(isCurrent == 1){
        versionVisible.value=false;
    }else{
        versionVisible.value=true;
    }
}

// 查询设备ID
const selectDeviceId = async()=>{
    // 查询本地缓存的设备状态是否绑定过
    // let deviceId = uni.getStorageSync('app_device_id');// 本地设备ID
    try {
        // showAlert("safeSave=>"+safeSave)
        safeSave.getSafeFile({ "key": "app_device_id" }, res2 => {
            // showAlert("读取成功=>"+JSON.stringify(res2));
            if (res2.code == 1) {
                let deviceId = res2.data;
                console.log("读取成功=>",deviceId)
                showAlert("读取成功=>"+deviceId);
                getBindStatus({uniqCode:deviceId}).then(res=>{
                    let bindStatus = res.bindStatus
                    setTimeout(()=>{
                        // 绑定状态（1=已提交、2=等待审核、3=审核通过、4=绑定成功、5=审核拒绝）
                        if(bindStatus == 4){
                            // 检查是否已登录 并 获取用户信息
                            if (userStore.isLogin) {
                                uni.reLaunch({
                                    url: '/pages/home/home',
                                });
                            
                            }else{
                                uni.reLaunch({
                                    url: '/pages/login/login',
                                });
                            }
                        }else{
                            uni.reLaunch({
                                url: '/pages/deviceAuth/deviceAuth',
                            });
                        }
                    },2000)
                });
            } else {
                showAlert('读取失败:'+res2.msg)
                setTimeout(()=>{
                    uni.reLaunch({
                        url: '/pages/deviceAuth/deviceAuth',
                    });
                },2000)
            }
        })
    } catch (error) {
        showAlert("catch=>"+error)
    }
}
// 下载最新版本
const handleDown = ()=>{
    // 跳转到应用商店或下载最新版本的页面
    plus.runtime.openURL(downloadURL.value);			
    if (versionData.value.os == 'ios'){
        plus.ios.import("UIApplication").sharedApplication().performSelector("exit")
    } else if (versionData.value.os == 'android'){
        plus.runtime.quit();
    }
}

//版本更新关闭
const handleClose=()=>{
    versionVisible.value = false;
    // 不更新版本 执行设备ID查询和绑定操作
    if(!versionVisible.value){
        selectDeviceId()
    }
}
</script>

<style>
.container {
	background:#307AF5 !important;
	height: calc(100vh - 100px) !important;
	position: relative;
    padding-top:100px;
}
.container .bg{
    background:url('@/static/images/loading-logo.png') no-repeat;
    background-size:700rpx 800rpx;
    width: 700rpx;
    height: 800rpx;
    margin:0 auto;
}
.container .version{
    color:#A8D4FF;
    font-size:32rpx;
    text-align: center;
    margin-top:35rpx;
}
.container .bottom-bg{
    background:url('@/static/images/loading-txt.png') no-repeat;
    background-size:656rpx 123rpx;
    width: 656rpx;
    height: 123rpx;
    position: absolute;
    bottom:48rpx;
    left:50%;
    margin-left:-328rpx;
}

.container .version-con{
    width:100%;
    position: fixed;
    top:0;
    left:0;
    height: 100vh;
    background: rgba(0, 0, 0, 0.4);
}
.version-con .v-bg{
    position: absolute;
    top:50%;
    left: 50%;
    /* width:620rpx; */
    width:540rpx;
    background-color: #fff;
    border-radius: 20rpx;
    padding:40rpx;
    margin-left:-310rpx;
    margin-top:-45%;
    text-align: center;
}
.version-con .v-bg .v-title{
    font-size: 36rpx;
    font-weight: bold;
    text-align: center;
    margin-bottom:30rpx;
}
.version-con .v-bg .v-icon{
    font-size:70rpx;
    color:#28B6FF;
   
}
.version-con .v-bg .v-version{
    color:#0395E0;
    font-size:42rpx;
    font-weight: bold;
    margin:20rpx 0 30rpx;
}
.version-con .v-bg .v-update{
    font-size:32rpx;
    margin-bottom:70rpx;
}
.version-con .v-bg .version-btn{
    background-color: #05A3F4;
    text-align: center;
    width:360rpx;
    height:80rpx;
    line-height: 80rpx;
    border-radius: 40rpx;
    margin:0 auto;
    color:#fff;
}
.version-con .v-bg .version-sub{
    color:#05A3F4;
    font-size:32rpx;
    margin:40rpx 0 30rpx;
}
</style>