<template>
    <view class="policy-consent-host">
        <policy-consent-modal ref="policyModal" @accepted="onPolicyAccepted" />
        <!-- #ifdef MP-WEIXIN -->
        <privacy-authorize-popup ref="privacyPopup" />
        <!-- #endif -->
    </view>
</template>

<script>
import PolicyConsentModal from '@/components/policy-consent-modal.vue'
import { eventBus } from '@/utils/event-bus'
import {
    registerPolicyHost,
    setPolicyConsented,
    unregisterPolicyHost,
} from '@/utils/policy-consent-manager.js'

// #ifdef MP-WEIXIN
import PrivacyAuthorizePopup from '@/components/privacy-authorize-popup.vue'
// #endif

export default {
    components: {
        PolicyConsentModal,
        // #ifdef MP-WEIXIN
        PrivacyAuthorizePopup,
        // #endif
    },
    mounted() {
        registerPolicyHost(this)
        this.tryOpenPolicyModal()
    },
    beforeDestroy() {
        unregisterPolicyHost(this)
    },
    methods: {
        tryOpenPolicyModal() {
            const app = getApp()
            if (!app || !app.globalData || !app.globalData.needPolicyConsent) return
            this.$nextTick(() => {
                this.$refs.policyModal && this.$refs.policyModal.open()
            })
        },
        tryOpenPrivacyPopup() {
            // #ifdef MP-WEIXIN
            this.$nextTick(() => {
                this.$refs.privacyPopup && this.$refs.privacyPopup.open()
            })
            // #endif
        },
        onPolicyAccepted() {
            setPolicyConsented()
            const app = getApp()
            if (app && app.globalData) {
                app.globalData.needPolicyConsent = false
            }
            eventBus.emit('policyAccepted')
            if (app && typeof app.runPendingLaunchLogin === 'function') {
                app.runPendingLaunchLogin()
            }
        },
    },
}
</script>
