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

<script>
import PolicyConsentModal from '@/components/policy-consent-modal.vue'
import { eventBus } from '@/utils/event-bus'
import {
    markHomeRefreshAfterPolicy,
    registerPolicyHost,
    setPolicyConsented,
    setTabbarBlockedState,
    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
    },
    data() {
        return {
            policyModalVisible: false,
            privacyModalVisible: false,
        }
    },
    computed: {
        tabbarBlocked() {
            return this.policyModalVisible || this.privacyModalVisible
        },
    },
    watch: {
        tabbarBlocked: {
            immediate: true,
            handler(val) {
                setTabbarBlockedState(val)
            },
        },
    },
    mounted() {
        registerPolicyHost(this)
        this.tryOpenPolicyModal()
    },
    beforeDestroy() {
        setTabbarBlockedState(false)
        unregisterPolicyHost(this)
    },
    methods: {
        onPolicyModalVisibility(visible) {
            this.policyModalVisible = visible
        },
        onPrivacyModalVisibility(visible) {
            this.privacyModalVisible = visible
        },
        tryOpenPolicyModal() {
            const app = getApp()
            if (!app || !app.globalData || !app.globalData.needPolicyConsent) return
            this.$nextTick(() => {
                if (this.$refs.policyModal) {
                    setTabbarBlockedState(true)
                    this.$refs.policyModal.open()
                }
            })
        },
        tryOpenPrivacyPopup() {
            // #ifdef MP-WEIXIN
            this.$nextTick(() => {
                if (this.$refs.privacyPopup) {
                    setTabbarBlockedState(true)
                    this.$refs.privacyPopup.open()
                }
            })
            // #endif
        },
        onPolicyAccepted() {
            setPolicyConsented()
            const app = getApp()
            if (app && app.globalData) {
                app.globalData.needPolicyConsent = false
            }
            markHomeRefreshAfterPolicy()
            eventBus.emit('policyAccepted')
            if (app && typeof app.runPendingLaunchLogin === 'function') {
                app.runPendingLaunchLogin()
            }
        },
    },
}
</script>
