<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";

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

            this.loginSuccessHandler = (data) => {
                this.openByLoginSuccess(data);
                const app = getApp();
                if (app && app.globalData) {
                    app.globalData.isColdLaunch = false;
                }
            };
            eventBus.on("loginSuccess", this.loginSuccessHandler);
        },
        bindAppShowActivity() {
            if (this.appShowActivityHandler) return;

            this.appShowActivityHandler = (data) => {
                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;
        },
        tryOpenPendingActivity() {
            const token = uni.getStorageSync("token");
            const upsellCode = uni.getStorageSync("upsellCode");
            const reduceCode = uni.getStorageSync("reduceCode");
            if (!token || (!upsellCode && !reduceCode)) return;

            this.openByLoginSuccess();
        },
        openByLoginSuccess(data) {
            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;

            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");
        },
        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>
