<script setup>
import { reactive, inject, onMounted } from 'vue';
import { onLaunch, onShow, onHide } from '@dcloudio/uni-app';
import { IncreaseRevie } from '@/common/all-in-one-listen.js';
import useUserStore from './stores/useUserStore';
import usePageAnimation from './hook/usePageAnimation';
import useDictStore from './stores/useDictStore';
import { GlobalInactivityManager } from '@/utils/GlobalInactivityManager';
const {
    $api,
    navTo,
    appendScriptTagElement,
    aes_Decrypt,
    sm2_Decrypt,
    safeReLaunch,
    isY9MachineType,
    isAsdMachineType,
} = inject('globalFunction');
import config from '@/config.js';
import baseDB from '@/utils/db.js';
import { $confirm } from '@/utils/modal.js';
import useLocationStore from '@/stores/useLocationStore';
const appword = 'aKd20dbGdFvmuwrt'; // 固定值
let uQRListen = null;
let inactivityManager = null;
let inactivityModalTimer = null;

usePageAnimation();
onLaunch((options) => {
    useDictStore().getDictData();
    if (isAsdMachineType()) {
        console.warn('爱山东环境');
        getUserInfo();
        useUserStore().changMiniProgramAppStatus(false);
        useUserStore().changMachineEnv(false);
        useLocationStore().getLocationLoop(); //循环获取定位
        return;
    }
    if (isY9MachineType()) {
        console.warn('求职一体机环境');
        baseDB.resetAndReinit(); // 清空indexdb
        useUserStore().logOutApp();
        useUserStore().changMiniProgramAppStatus(true);
        useUserStore().changMachineEnv(true);
        (function loop() {
            console.log('📍一体机尝试获取定位');
            useLocationStore()
                .getLocation()
                .then(({ longitude, latitude }) => {
                    console.log(`✅一体机获取定位成功:lng:${longitude},lat${latitude}`);
                })
                .catch((err) => {
                    console.log('❌一体机获取定位失败,30s后尝试重新获取');
                    setTimeout(() => {
                        loop();
                    }, 3000);
                });
        })();
        uQRListen = new IncreaseRevie();
        inactivityManager = new GlobalInactivityManager(handleInactivity, 60 * 1000);
        inactivityManager.start();
        return;
    }
    // 正式上线去除此方法
    console.warn('浏览器环境');
    useLocationStore().getLocationLoop(); //循环获取定位
    useUserStore().changMiniProgramAppStatus(true);
    useUserStore().changMachineEnv(false);
    useUserStore().initSeesionId(); //更新
    let token = uni.getStorageSync('token') || '';
    if (token) {
        useUserStore()
            .loginSetToken(token)
            .then(() => {
                $api.msg('登录成功');
            });
    } else {
        safeReLaunch('/pages/login/login');
    }
});

onMounted(() => {});

onShow(() => {
    console.log('App Show');
});

onHide(() => {
    console.log('App Hide');
});

function handleInactivity() {
    console.log('【全局】60秒无操作，执行安全逻辑');
    if (inactivityModalTimer) {
        clearTimeout(inactivityModalTimer);
        inactivityModalTimer = null;
    }

    if (useUserStore().hasLogin) {
        // 1. 正常弹出确认框
        $confirm({
            title: '会话即将过期',
            content: '长时间无操作，是否继续使用？',
            success: (res) => {
                if (inactivityModalTimer) {
                    clearTimeout(inactivityModalTimer);
                    inactivityModalTimer = null;
                }
                if (res.confirm) {
                    inactivityManager?.resume();
                } else {
                    performLogout();
                }
            },
            fail: () => {
                if (inactivityModalTimer) {
                    clearTimeout(inactivityModalTimer);
                    inactivityModalTimer = null;
                }
                performLogout();
            },
        });

        // 2. 启动 10 秒倒计时
        inactivityModalTimer = setTimeout(() => {
            inactivityModalTimer = null;
            console.log('【自动登出】10秒无响应，强制清理状态');

            // 【关键改进】：通知全局组件强制关闭弹窗，防止用户点击陈旧弹窗
            uni.$emit('hide-global-popup');

            performLogout();
        }, 10000);
    } else {
        inactivityManager?.resume();
    }
}

function performLogout() {
    uni.clearStorageSync();
    baseDB.resetAndReinit();
    useUserStore().logOutApp();
    inactivityManager?.resume(); // 恢复监听
}

// 爱山东环境登录
function getUserInfo() {
    lightAppJssdk.user.getUserInfoWithEncryptedParamByAppId({
        appId: config.appInfo.loveShandong, // 接入方在成功创建应用后自动生成
        success: function (data) {
            if (data == '未登录') onLoginApp();
            else {
                if (typeof data == 'string') data = JSON.parse(data);
                const sm2_privateKey = config.appInfo.sm2PrivateKey;
                let sm2_encrypt_result = data.data;
                let sm2_decrypt_result = sm2_Decrypt(sm2_encrypt_result, sm2_privateKey);
                if (typeof sm2_decrypt_result == 'string') sm2_decrypt_result = JSON.parse(sm2_decrypt_result);

                // 其次,对sm2解密后的结果进行 aes解密
                // aes解密需要用到 appword , 为固定值,使用示例代码中的即可
                let aes_encrypt_result = sm2_decrypt_result.data;
                let aes_decrypt_result = aes_Decrypt(aes_encrypt_result, appword);
                // 加密
                loginCallback(aes_decrypt_result);
            }
        },
        fail: function (data) {
            console.log('err', data);
        },
    });
}

/**
 * 使用jssdk调用登录页面
 */
function onLoginApp() {
    lightAppJssdk.user.loginapp({
        success: function (data) {
            if (data == '未登录') {
                //取消登录或登录失败，关闭页面
                oncloseWindow();
            } else {
                getUserInfo();
            }
        },
        fail: function (data) {
            //关闭页面
            oncloseWindow();
        },
    });
}

/**
 * 关闭容器
 */
function oncloseWindow() {
    lightAppJssdk.navigation.close({
        success: function (data) {},
        fail: function (data) {},
    });
}

function loginCallback(userInfo) {
    let params = {
        userInfo,
    };
    $api.createRequest('/app/login', params, 'post').then((resData) => {
        useUserStore()
            .loginSetToken(resData.token)
            .then((resume) => {
                if (resume.data.jobTitleId) {
                    useUserStore().initSeesionId();
                    safeReLaunch('/pages/index/index');
                } else {
                    safeReLaunch('/pages/login/login');
                }
            });
    });
}
</script>

<style>
/*每个页面公共css */
@import '@/common/animation.css';
@import '@/common/common.css';

/* 修改pages tabbar样式 H5才有效 */
.uni-tabbar .uni-tabbar__item:nth-child(4) .uni-tabbar__bd .uni-tabbar__icon {
    width: 108rpx !important;
    height: 98rpx !important;
    margin-top: 0rpx;
    transition: transform 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275);
    transform-origin: center center;
    /* transition: transform 0.15s ease-in-out; */
    /* transform-origin: center center; */
}

.uni-tabbar .uni-tabbar__item:nth-child(4) .uni-tabbar__bd .uni-tabbar__icon:active {
    transform: scale(0.8);
    transition: transform 0.1s ease-out;
    /* animation: jelly 0.5s; */
}

.uni-tabbar-border {
    background-color: transparent !important;
    /* background-color: #e4e4e4 !important; */
}
.uni-popup {
    z-index: 1001 !important;
}
/* 提升toast层级 */
uni-toast,
uni-modal,
.uni-modal,
.uni-mask {
    z-index: 998;
}

@font-face {
    font-family: DingTalk JinBuTi;
    src: url('/static/font/DingTalk JinBuTi_min.woff2') format('woff2');
    font-display: swap;
}

@font-face {
    font-family: PingFangSC-Regular;
    src: url('/static/font/PingFangSC-Regular.woff2') format('woff2');
    font-display: swap;
}

@font-face {
    font-family: PingFangSC-Medium;
    src: url('/static/font/PingFangSC-Medium.woff2') format('woff2');
    font-display: swap;
}

@font-face {
    font-family: DIN-Medium;
    src: url('/static/font/DIN-Medium.woff2') format('woff2');
    font-display: swap;
}

body {
    font-family: 'PingFangSC-Regular', 'PingFang SC', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif;
}
</style>
