<script>
    import {useAppStore} from "@/store";
    import website from "@/config/index";
    import userApi from '~api/user/index';
    import {getStorage, setStorage} from "@/utils/storage";
    import {calcDate, getObjValue, isNullES} from "js-fast-way";
    import HcSocket from "@/httpApi/request/socket";

	export default {
        data() {
            return {
                userInfo: {}, refreshLock: false, isSocket: false, timeId: null,
            }
        },
		onLaunch() {
            HcSocket.initSocket()
		},
		onShow() {
			//console.log('App Show')
		},
		onHide() {
			//console.log('App Hide')
		},
        mounted() {
            const store = useAppStore()
            this.userInfo = store.userInfo
            this.getRefreshToken()
        },
        methods:{
            //刷新token
            getRefreshToken() {
                let _this = this;
                setInterval(() => {
                    const token = getStorage('token', true)
                    const date = calcDate(token.datetime, new Date().getTime())
                    if (isNullES(date)) return false;
                    if (date.seconds >= website.tokenTime && !this.refreshLock) {
                        this.refreshLock = true
                        console.log('刷新token')
                        this.refreshTokenApi().then(() => {
                            _this.refreshLock = false
                        }).catch(() => {
                            _this.refreshLock = false
                            uni.reLaunch({
                                url: '/pages/login/login'
                            });
                        })
                    }
                }, 10000)
            },
            async refreshTokenApi() {
                const store = useAppStore()
                const { dept_id, role_id, tenant_id } = this.userInfo
                const refreshToken = getStorage('refreshToken')
                const {error, status, res} = await userApi.refreshToken({
                    token: refreshToken,
                    tenantId: tenant_id,
                    deptId: dept_id,
                    roleId: role_id
                });
                if (!error && status === 200) {
                    const data = getObjValue(res)
                    setStorage('token', data?.access_token)
                    setStorage('refreshToken', data?.refresh_token)
                    store.setUserInfo(res)
                    return Promise.resolve(res)
                } else {
                    return Promise.reject(res)
                }
            },
        }
	}
</script>

<style lang="scss">
@import "@/colorui/main.css";
@import "@/colorui/icon.css";
@import "@/style/app.scss";
</style>
