<template>
    <view>
        <UpsellShare v-if="enableUpsell" ref="shareRef" @viewRules="emitViewRules" />
        <ReduceShare v-if="enableReduce" ref="reduceShareRef" @viewRules="emitViewRules" />
    </view>
</template>

<script>
import UpsellShare from "@/pages/home/components/upsell-share.vue";
import ReduceShare from "@/pages/home/components/reduce-share.vue";
import { eventBus } from "@/utils/event-bus";
import { shouldBlockMarketingPopup } from "@/utils/policy-consent-manager.js";

export default {
    name: "ActivityHost",
    props: {
        enableUpsell: {
            type: Boolean,
            default: true,
        },
        enableReduce: {
            type: Boolean,
            default: true,
        },
    },
    components: {
        UpsellShare,
        ReduceShare,
    },
    data() {
        return {
            loginSuccessHandler: null,
            appShowActivityHandler: null,
            policyAcceptedHandler: null,
            pendingLoginData: null,
            pendingPageOptions: null,
        };
    },
    mounted() {
        this.bindLoginSuccess();
        this.bindAppShowActivity();
        this.bindPolicyAccepted();
        this.tryOpenPendingActivity();
    },
    beforeDestroy() {
        this.unbindLoginSuccess();
        this.unbindAppShowActivity();
        this.unbindPolicyAccepted();
    },
    methods: {
        bindLoginSuccess() {
            if (this.loginSuccessHandler) return;

            this.loginSuccessHandler = (data) => {
                if (shouldBlockMarketingPopup()) {
                    this.pendingLoginData = data || null;
                    return;
                }
                const app = getApp();
                if (app && app.globalData) {
                    app.globalData.isColdLaunch = false;
                }
                // 优先处理带参数的入口（如分享减价链接），避免与 storage 重复弹窗
                if (this.pendingPageOptions) {
                    const options = this.pendingPageOptions;
                    this.pendingPageOptions = null;
                    this.openByPageOptions(options);
                    return;
                }
                this.openByLoginSuccess(data);
            };
            eventBus.on("loginSuccess", this.loginSuccessHandler);
        },
        bindAppShowActivity() {
            if (this.appShowActivityHandler) return;

            this.appShowActivityHandler = (data) => {
                if (shouldBlockMarketingPopup()) {
                    this.pendingLoginData = data || null;
                    return;
                }
                this.openByLoginSuccess(data);
            };
            eventBus.on("appShowActivity", this.appShowActivityHandler);
        },
        unbindLoginSuccess() {
            if (!this.loginSuccessHandler) return;
            eventBus.off("loginSuccess", this.loginSuccessHandler);
            this.loginSuccessHandler = null;
        },
        unbindAppShowActivity() {
            if (!this.appShowActivityHandler) return;
            eventBus.off("appShowActivity", this.appShowActivityHandler);
            this.appShowActivityHandler = null;
        },
        bindPolicyAccepted() {
            if (this.policyAcceptedHandler) return;
            this.policyAcceptedHandler = () => {
                this.flushPendingMarketingPopups();
            };
            eventBus.on("policyAccepted", this.policyAcceptedHandler);
        },
        unbindPolicyAccepted() {
            if (!this.policyAcceptedHandler) return;
            eventBus.off("policyAccepted", this.policyAcceptedHandler);
            this.policyAcceptedHandler = null;
        },
        tryOpenPendingActivity() {
            if (shouldBlockMarketingPopup()) return;

            const token = uni.getStorageSync("token");
            const upsellCode = uni.getStorageSync("upsellCode");
            const reduceCode = uni.getStorageSync("reduceCode");
            if (!token || (!upsellCode && !reduceCode)) return;

            this.openByLoginSuccess();
        },
        openByLoginSuccess(data) {
            if (shouldBlockMarketingPopup()) {
                this.pendingLoginData = data || null;
                return;
            }

            const upsellCode = uni.getStorageSync("upsellCode") || data?.params?.upsellCode;
            const reduceCode = uni.getStorageSync("reduceCode") || data?.params?.reduceCode;

            if (this.enableUpsell && upsellCode) {
                this.$refs.shareRef?.open(upsellCode);
            }
            if (this.enableReduce && reduceCode) {
                this.$refs.reduceShareRef?.open(reduceCode);
            }
            this.$emit("refresh-order");
        },
        handlePageOptions(options = {}, isColdLaunch = false) {
            if (isColdLaunch) return;

            if (shouldBlockMarketingPopup()) {
                this.pendingPageOptions = options;
                return;
            }

            this.openByPageOptions(options);
        },
        openByPageOptions(options = {}) {
            const params = this.parseEntryParams(options);
            if (this.enableUpsell && params.upsellCode) {
                this.$refs.shareRef?.open(params.upsellCode);
                this.$emit("refresh-order");
                return;
            }
            if (this.enableReduce && params.reduceCode) {
                this.$refs.reduceShareRef?.open(params.reduceCode);
                return;
            }
            this.$emit("refresh-order");
        },
        flushPendingMarketingPopups() {
            if (shouldBlockMarketingPopup()) return;

            if (this.pendingPageOptions) {
                const options = this.pendingPageOptions;
                this.pendingPageOptions = null;
                this.openByPageOptions(options);
                return;
            }

            const token = uni.getStorageSync("token");
            if (!token) return;

            this.openByLoginSuccess(this.pendingLoginData);
            this.pendingLoginData = null;
        },
        parseEntryParams(options = {}) {
            if (!options.scene) return options;

            const params = {};
            const decodeScene = decodeURIComponent(options.scene);
            const paramPairs = decodeScene.split("&");
            paramPairs.forEach((pair) => {
                const [key, value] = pair.split("=");
                params[key] = value;
            });
            return params;
        },
        emitViewRules() {
            this.$emit("view-rules");
        },
        getShareAppMessage(res) {
            if (this.enableUpsell && res.from === "button" && res.target && res.target.dataset && res.target.dataset.shareType === "upsell") {
                const upsellCode = uni.getStorageSync("upsellCodeShare");
                uni.$u.http.get("/token/order/goToShare?upsellCode=" + upsellCode);
                return {
                    title: "书嗨",
                    path: "/pages/home/index?upsellCode=" + upsellCode,
                    imageUrl: "https://shuhi.oss-cn-qingdao.aliyuncs.com/mini/share.jpg",
                    desc: "书嗨，专注于书籍交易的平台，提供新书和二手书的买卖服务",
                };
            }

            if (this.enableReduce && res.from === "button" && res.target && res.target.dataset && res.target.dataset.shareType === "reduce") {
                const reduceCode = uni.getStorageSync("reduceCodeShare");
                if (uni.$u && uni.$u.api && uni.$u.api.goToReduceShareAjax) {
                    uni.$u.api.goToReduceShareAjax({ reduceCode: reduceCode });
                } else {
                    uni.$u && uni.$u.http && uni.$u.http.get("/token/shop/order/goToShare", { reduceCode: reduceCode });
                }
                return {
                    title: "快来帮我减钱买书吧！",
                    path: "/pages/sell/index?reduceCode=" + reduceCode,
                    imageUrl: "https://shuhi.oss-cn-qingdao.aliyuncs.com/mini/share.jpg",
                    desc: "书嗨，专注于书籍交易的平台，提供新书和二手书的买卖服务",
                };
            }

            return null;
        },
        getShareTimeline(res) {
            if (this.enableUpsell && res.from === "button" && res.target && res.target.dataset && res.target.dataset.shareType === "upsell") {
                const upsellCode = uni.getStorageSync("upsellCodeShare");
                uni.$u.http.get("/token/order/goToShare?upsellCode=" + upsellCode);
                return {
                    title: "书嗨",
                    path: "/pages/home/index?upsellCode=" + upsellCode,
                    imageUrl: "https://shuhi.oss-cn-qingdao.aliyuncs.com/mini/share.jpg",
                    desc: "书嗨，专注于书籍交易的平台，提供新书和二手书的买卖服务",
                };
            }

            if (this.enableReduce && res.from === "button" && res.target && res.target.dataset && res.target.dataset.shareType === "reduce") {
                const reduceCode = uni.getStorageSync("reduceCodeShare");
                if (uni.$u && uni.$u.api && uni.$u.api.goToReduceShareAjax) {
                    uni.$u.api.goToReduceShareAjax({ reduceCode: reduceCode });
                } else {
                    uni.$u && uni.$u.http && uni.$u.http.get("/token/shop/order/goToShare", { reduceCode: reduceCode });
                }
                return {
                    title: "快来帮我减钱买书吧！",
                    path: "/pages/sell/index?reduceCode=" + reduceCode,
                    imageUrl: "https://shuhi.oss-cn-qingdao.aliyuncs.com/mini/share.jpg",
                    desc: "书嗨，专注于书籍交易的平台，提供新书和二手书的买卖服务",
                };
            }

            return null;
        },
    },
};
</script>
