<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, isString} from "js-fast-way";
    import {getWssApiUrl} from "@/config/envApi";

	export default {
        data() {
            return {
                userInfo: {}, refreshLock: false, isSocket: false
            }
        },
		onLaunch: function() {
			//console.log('App Launch')
		},
		onShow: function() {
			//console.log('App Show')
		},
		onHide: function() {
			//console.log('App Hide')
		},
        mounted() {
            const store = useAppStore()
            this.userInfo = store.userInfo
            this.getRefreshToken()
            this.setInitSocket()
        },
        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)
                }
            },
            //长连接
            setInitSocket() {
                const _this = this
                const timeId = setInterval(() => {
                    if (_this.isSocket) {
                        clearInterval(timeId)
                    } else {
                        _this.setAppSocket(timeId)
                    }
                }, 3000)
            },
            setAppSocket() {
                const {user_id} = this.userInfo
                if (user_id) this.initWebSocket(user_id)
            },
            initWebSocket(user_id) {
                const _this = this
                uni.connectSocket({
                    url: getWssApiUrl() + user_id,
                    complete: ()=> {
                        console.log('websocket链接成功')
                    }
                });
                uni.onSocketOpen((res) => {
                    _this.isSocket = true
                    console.log('WebSocket连接已打开！');
                    _this.sendSocketMessage();
                });
                uni.onSocketError((res) => {
                    _this.isSocket = false
                    console.log('WebSocket连接打开失败，请检查！');
                });
                uni.onSocketClose((res) => {
                    _this.isSocket = false
                    console.log('WebSocket 已关闭！');
                    //关闭后在连接
                    _this.setInitSocket()
                });
                //收到的消息
                uni.onSocketMessage(({data}) => {
                    const countData = isString(data) ? JSON.parse(data) : {}
                    console.log(countData)
                });
            },
            sendSocketMessage() {
                const store = useAppStore()
                uni.sendSocketMessage({
                    data: store.projectId + ',' + store.contractId
                });
            },
        }
	}
</script>

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