import {
    onLaunch
} from '@dcloudio/uni-app'
import {
    getCurrentInstance
} from 'vue'
import './page-animation.css'

const DURATION = 130

export default function usePageAnimation() {
    // #ifdef H5
    const show = () => {
        const page = document.querySelector('uni-page')
        if (!page) return
        const cl = page.classList

        cl.add('animation-enter-from')
        cl.remove('animation-leave-to', 'animation-leave-active')

        requestAnimationFrame(() => {
            requestAnimationFrame(() => {
                cl.remove('animation-enter-from')
                cl.add('animation-enter-active', 'animation-show')

                setTimeout(() => {
                    cl.remove('animation-enter-active')
                }, DURATION)
            })
        })
    }

    const hide = (next) => {
        const page = document.querySelector('uni-page')
        if (!page) {
            next()
            return
        }
        const cl = page.classList

        cl.add('animation-leave-active')

        requestAnimationFrame(() => {
            cl.remove('animation-show')
            cl.add('animation-leave-to')

            setTimeout(() => {
                cl.remove('animation-leave-active', 'animation-leave-to')
                next()
            }, DURATION - 50)
        })
    }

    onLaunch(() => {
        const instance = getCurrentInstance()
        const router = instance?.proxy?.$router
        if (router) {
            show()

            router.beforeEach((to, from, next) => hide(next))

            router.afterEach(() => show())
        }
    })
    // #endif
}