<template>
<view class="container" :style="{ height: `100vh` }">
    <view class="bg">
        <view class="env-txt" v-if="networkEnv==1">企业内网</view>
    </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,getCurrentInstance } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { MINIO_KEY } from '@/enums/cacheEnums';
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 { minioParam } from '@/api/polling.js'
import { useUserStore } from '@/stores/user';
const userStore = useUserStore();
const { proxy } = getCurrentInstance();
const networkEnv = ref(proxy.$NETWORK_ENV);//1-内网 2-外网

// #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
    //手机通知授权
    noticMsgTool();

    // 查询版本接口
    await getOSVesion();
    
    // 不更新版本 执行设备ID查询和绑定操作
    if(!versionVisible.value){
        try {
            // 授权设备存储
            // let granted =  requestAndroidPermission(systemInfo);
            // if(granted){
                // showAlert("22授权成功！")
                // setTimeout(()=>{
                    selectDeviceId();
                // },500)
            // }
        } 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',
            });
        }
    // },1000)
    // #endif

    // 内网才有minio参数
    // if(networkEnv.value==1){
    //     getMinioParam();
    // }

});

// 获取minio参数
const getMinioParam=async ()=>{
    let data = await minioParam({});
    let minioThumbUrl = data.endpoint + "/thumb/"+data.bucketName;
    let minioUrl = data.endpoint + "/"+data.bucketName
    uni.setStorageSync(MINIO_KEY,JSON.stringify({
        minioThumbUrl,minioUrl
    }))
}

// 检查版本是否是最新的s
const getOSVesion = async()=>{
    let networkEnv = proxy.$NETWORK_ENV;//1-内网 2-外网
    systemInfo = uni.getSystemInfoSync();
    let param = {
        runEnv:networkEnv,
        // #ifdef APP-PLUS
        verNumber:systemInfo.appWgtVersion,//当前版本号
        // #endif
        // #ifdef H5
        verNumber : systemInfo.appVersion,
        // #endif
        os: formatIOS(systemInfo.osName),//操作系统 Android  IOS
    }
    // 当前手机版本
    appVersion.value = param.verNumber;
    // console.log("appVersion=>",appVersion)
    versionData.value = param;
    let data = await versionCheck(param);
    newVersion.value = data.verNumber;
    downloadURL.value = data.downPageUrl || '';

    // 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;
                // showAlert("读取成功=>"+deviceId);
                if(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',
                                });
                            }
                        // },1000)
                    });
                }else{
                    uni.reLaunch({
                        url: '/pages/deviceAuth/deviceAuth',
                    });
                }
            
            } else {
                uni.reLaunch({
                    url: '/pages/deviceAuth/deviceAuth',
                });
            }
        })
    } catch (error) {
        console.log("getSafeFile=>",error)
        // showAlert("getSafeFile=>"+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()
    }
}

//通知授权
const noticMsgTool=()=>{
    if (uni.getSystemInfoSync().platform == "ios") {
        // iOS: 使用 iOS API 检查通知权限
        plus.ios.import('UserNotifications');
        var UNNotificationSettings = plus.ios.invoke('UNUserNotificationCenter', 'currentNotificationCenter');
        plus.ios.invoke(UNNotificationSettings, 'getNotificationSettingsWithCompletionHandler', function(settings) {
            var authorizationStatus = plus.ios.invoke(settings, 'authorizationStatus');
            if (authorizationStatus !== 3) { // 3表示已授权
                //苹果打开对应的通知栏
                uni.showModal({
                    title: '通知权限开启提醒',
                    content: '您还没有开启通知权限，无法接受到消息通知，请前往设置！',
                    showCancel: false,
                    confirmText: '去设置',
                    success: function(res) {
                        if (res.confirm) {
                            var app = plus.ios.invoke('UIApplication', 'sharedApplication');
                            var setting = plus.ios.invoke('NSURL', 'URLWithString:','app-settings:');
                            plus.ios.invoke(app, 'openURL:', setting);
                            plus.ios.deleteObject(setting);
                            plus.ios.deleteObject(app);
                        }
                    }
                });
            }
        });

    } else {
        //android打开对应的通知栏
        var main = plus.android.runtimeMainActivity();
        var pkName = main.getPackageName();
        var uid = main.getApplicationInfo().plusGetAttribute("uid");
        var context = main.getApplicationContext();
        var NotificationManager = plus.android.importClass('android.app.NotificationManager');
        var notificationManager = context.getSystemService(context.NOTIFICATION_SERVICE);
        var areNotificationsEnabled = notificationManager.areNotificationsEnabled();

        if (!areNotificationsEnabled) {
            // 提示用户开启通知权限
            uni.showModal({
                title: '通知权限开启提醒',
                content: '您还没有开启通知权限，无法接受到消息通知，请前往设置！',
                showCancel: false,
                confirmText: '去设置',
                success: function(res) {
                    if (res.confirm) {
                        var Intent = plus.android.importClass('android.content.Intent');
                        var Build = plus.android.importClass("android.os.Build");
                        //android 8.0引导  
                        if (Build.VERSION.SDK_INT >= 26) {
                            var intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS');
                            intent.putExtra('android.provider.extra.APP_PACKAGE', pkName);
                        } else if (Build.VERSION.SDK_INT >= 21) { //android 5.0-7.0  
                            var intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS');
                            intent.putExtra("app_package", pkName);
                            intent.putExtra("app_uid", uid);
                        } else { //(<21)其他--跳转到该应用管理的详情页  
                            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                            var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
                            intent.setData(uri);
                        }
                        // 跳转到该应用的系统通知设置页  
                        main.startActivity(intent);
                    }
                }
            });
        }

    }
}
</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;
    position: relative;
}
.container .bg .env-txt{
    position: absolute;
    right: 35rpx;
    top:10rpx;
    color:#fff;
    font-size: 36rpx;
    font-weight: bold;
}
.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>