<template>
    <div class="suspension-wrapper">
        <div ref="floatingMenu" class="jd-floating-menu"
            :class="[themeClass, { collapsed: isCollapsed && !showActivityList, 'left-side': !isOnRightSide }]" :style="menuPositionStyle">
            <!-- 展开的子按钮 -->
            <div class="jd-menu-buttons" :class="{ expanded: isExpanded }">
                <div class="jd-menu-btn" @click.stop="goToShopHome" :style="styleData.menuBtnStyle">
                    <svg viewBox="0 0 24 24">
                        <path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z" />
                    </svg>
                    <span>店铺</span>
                </div>
                <div class="jd-menu-btn" @click.stop="goToMyOrders" :style="styleData.menuBtnStyle">
                    <svg viewBox="0 0 24 24">
                        <path
                            d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-5 14H7v-2h7v2zm3-4H7v-2h10v2zm0-4H7V7h10v2z" />
                    </svg>
                    <span>订单</span>
                </div>
                <div class="jd-menu-btn" @click.stop="openActivityList" :style="styleData.menuBtnStyle">
                    <svg viewBox="0 0 24 24">
                        <path d="M4 6h16v2H4zm0 5h16v2H4zm0 5h16v2H4z" />
                    </svg>
                    <span>活动</span>
                </div>
            </div>
            <!-- 主按钮 -->
            <div ref="menuMain" class="jd-menu-main" :style="styleData.menuMainStyle" @touchstart.passive="handleStart"
                @mousedown="handleStart" @click.stop="onMainClick">
                <svg viewBox="0 0 24 24">
                    <path d="M3 18h18v-2H3v2zm0-5h18v-2H3v2zm0-7v2h18V6H3z" />
                </svg>
            </div>
        </div>
        <!-- 活动列表弹层 - 放在 floatingMenu 外面，避免 transform 影响 fixed 定位 -->
        <activityList :visible="showActivityList" @close="closeActivityList" />
    </div>
</template>

<script>
import store from "../../../store/store";
import activityList from "./activityList.vue";

export default {
    name: "suspension",
    components: { activityList },
    props: {
        styleData: {
            type: Object,
            default: () => ({}),
        },
        datas: {
            type: Object,
            default: () => ({}),
        },
        keyData: {
            type: Object,
            default: () => ({}),
        },
        isTemplate: {
            type: Boolean,
            default: false,
        },
    },
    data() {
        return {
            isDragging: false,
            dragOccurred: false,
            isExpanded: false,
            isOnRightSide: true,
            isCollapsed: false,
            themeClass: "light-theme",
            currentX: 0,
            currentY: 0,
            startX: undefined,
            startY: undefined,
            initialX: 0,
            initialY: 0,
            autoHideTimer: null,
            autoCollapseTimer: null,
            menuSize: 60,
            showActivityList: false,
        };
    },
    computed: {
        menuPositionStyle() {
            return {
                left: this.currentX + "px",
                top: this.currentY + "px",
                right: "auto",
            };
        },
    },
    mounted() {
        // 初始化位置：屏幕右侧，垂直60%
        this.currentX = window.innerWidth - this.menuSize;
        this.currentY = window.innerHeight * 0.6;
        this.updateTheme();
        this.resetAutoHideTimer();

        // 绑定全局事件
        document.addEventListener("touchmove", this.handleMove, { passive: false });
        document.addEventListener("touchend", this.handleEnd);
        document.addEventListener("touchcancel", this.handleEnd);
        document.addEventListener("mousemove", this.handleMove);
        document.addEventListener("mouseup", this.handleEnd);

        window.addEventListener("scroll", this.onScroll);
    },
    beforeDestroy() {
        // 清除定时器
        if (this.autoHideTimer) clearTimeout(this.autoHideTimer);
        if (this.autoCollapseTimer) clearTimeout(this.autoCollapseTimer);
        // 移除全局事件
        document.removeEventListener("touchmove", this.handleMove);
        document.removeEventListener("touchend", this.handleEnd);
        document.removeEventListener("touchcancel", this.handleEnd);
        document.removeEventListener("mousemove", this.handleMove);
        document.removeEventListener("mouseup", this.handleEnd);
        window.removeEventListener("scroll", this.onScroll);
    },
    methods: {
        onScroll() {
            setTimeout(() => {
                this.updateTheme();
            }, 100);
        },

        // 获取背景亮度，决定明暗主题
        getBackgroundBrightness(x, y) {
            try {
                var element = document.elementFromPoint(x + 30, y + 30);
                if (element) {
                    var computedStyle = window.getComputedStyle(element);
                    var bgColor = computedStyle.backgroundColor;
                    if (
                        bgColor &&
                        bgColor !== "transparent" &&
                        bgColor !== "rgba(0, 0, 0, 0)"
                    ) {
                        var rgbMatch = bgColor.match(/\d+/g);
                        if (rgbMatch && rgbMatch.length >= 3) {
                            var r = parseInt(rgbMatch[0]);
                            var g = parseInt(rgbMatch[1]);
                            var b = parseInt(rgbMatch[2]);
                            return (r * 299 + g * 587 + b * 114) / 1000;
                        }
                    }
                }
            } catch (e) {
                console.log("Error getting background color:", e);
            }
            return 128;
        },

        updateTheme() {
            var brightness = this.getBackgroundBrightness(
                this.currentX,
                this.currentY
            );
            this.themeClass = brightness > 160 ? "light-theme" : "dark-theme";
        },

        resetAutoHideTimer() {
            if (this.autoHideTimer) clearTimeout(this.autoHideTimer);
            this.isCollapsed = false;
            this.autoHideTimer = setTimeout(() => {
                if (!this.isExpanded && !this.showActivityList) {
                    this.isCollapsed = true;
                }
            }, 2000);
        },

        resetAutoCollapseTimer() {
            if (this.autoCollapseTimer) clearTimeout(this.autoCollapseTimer);
            if (this.isExpanded) {
                this.autoCollapseTimer = setTimeout(() => {
                    this.collapseMenu();
                }, 5000);
            }
        },

        collapseMenu() {
            this.isExpanded = false;
            this.resetAutoHideTimer();
        },

        getEventPos(e) {
            if (e.touches && e.touches.length > 0) {
                return { x: e.touches[0].clientX, y: e.touches[0].clientY };
            }
            if (e.changedTouches && e.changedTouches.length > 0) {
                return { x: e.changedTouches[0].clientX, y: e.changedTouches[0].clientY };
            }
            return { x: e.clientX, y: e.clientY };
        },

        handleStart(e) {
            this.isDragging = false;
            this.dragOccurred = false;
            var pos = this.getEventPos(e);
            this.startX = pos.x;
            this.startY = pos.y;
            this.initialX = this.currentX;
            this.initialY = this.currentY;

            if (this.autoHideTimer) clearTimeout(this.autoHideTimer);
            if (this.autoCollapseTimer) clearTimeout(this.autoCollapseTimer);
            this.isCollapsed = false;
        },

        handleMove(e) {
            if (this.startX === undefined || this.startY === undefined) return;

            var pos = this.getEventPos(e);
            var deltaX = Math.abs(pos.x - this.startX);
            var deltaY = Math.abs(pos.y - this.startY);

            if (!this.isDragging && (deltaX > 5 || deltaY > 5)) {
                this.isDragging = true;
            }

            if (this.isDragging) {
                e.preventDefault();
                var moveDeltaX = pos.x - this.startX;
                var moveDeltaY = pos.y - this.startY;
                this.currentY = this.initialY + moveDeltaY;
                this.currentX = this.initialX + moveDeltaX;

                var maxY = window.innerHeight - this.menuSize;
                if (this.currentY < 50) this.currentY = 50;
                if (this.currentY > maxY) this.currentY = maxY;
                if (this.currentX < 0) this.currentX = 0;
                if (this.currentX > window.innerWidth - this.menuSize)
                    this.currentX = window.innerWidth - this.menuSize;

                // 拖拽时移除过渡动画
                this.$refs.floatingMenu.style.transition = "none";
                this.updateTheme();
            }
        },

        handleEnd(e) {
            if (this.startX === undefined || this.startY === undefined) return;

            if (this.isDragging) {
                this.dragOccurred = true;
                // 拖拽结束，吸附到左右边缘
                if (this.currentX + 30 < window.innerWidth / 2) {
                    this.isOnRightSide = false;
                    this.currentX = 0;
                } else {
                    this.isOnRightSide = true;
                    this.currentX = window.innerWidth - this.menuSize;
                }
                // 添加吸附过渡动画
                this.$refs.floatingMenu.style.transition =
                    "left 0.3s ease, top 0.3s ease, transform 0.3s ease";
                setTimeout(() => {
                    this.updateTheme();
                }, 300);
            }

            this.isDragging = false;
            this.startX = undefined;
            this.startY = undefined;

            if (this.isExpanded) {
                this.resetAutoCollapseTimer();
            } else {
                this.resetAutoHideTimer();
            }
        },

        // 主按钮点击 - 直接用 @click 事件，拖拽后屏蔽
        onMainClick() {
            if (this.dragOccurred) {
                this.dragOccurred = false;
                return;
            }
            this.handleClick();
        },

        handleClick() {
            this.isExpanded = !this.isExpanded;
            if (this.isExpanded) {
                this.isCollapsed = false;
                if (this.autoHideTimer) clearTimeout(this.autoHideTimer);
                this.resetAutoCollapseTimer();
            } else {
                this.collapseMenu();
            }
        },

        // 获取shopId
        resolveShopId() {
            return (
                store.state.shopId ||
                sessionStorage.getItem("shopId") ||
                localStorage.getItem("shopId") ||
                ""
            );
        },

        // 跳转店铺首页
        goToShopHome() {
            var shopId = this.resolveShopId();
            if (!shopId) return;
            try {
                if (typeof jmfe !== "undefined" && jmfe.toAny) {
                    jmfe.toAny(
                        'openapp.jdmobile://virtual?params={"des":"jshopMain","category":"jump","shopId":"' +
                        shopId +
                        '"}'
                    );
                }
            } catch (e) {
                console.log("跳转店铺失败:", e);
            }
        },

        // 跳转我的订单
        goToMyOrders() {
            try {
                if (typeof jmfe !== "undefined" && jmfe.toAny) {
                    jmfe.toAny(
                        'openapp.jdmobile://virtual?params={"des":"orderlist","category":"jump"}'
                    );
                }
            } catch (e) {
                console.log("跳转订单失败:", e);
            }
        },

        // 打开活动列表
        openActivityList() {
            this.showActivityList = true;
            this.isExpanded = false;
            // 清除所有定时器，防止自动收缩
            if (this.autoHideTimer) clearTimeout(this.autoHideTimer);
            if (this.autoCollapseTimer) clearTimeout(this.autoCollapseTimer);
        },

        // 关闭活动列表
        closeActivityList() {
            this.showActivityList = false;
            this.resetAutoHideTimer();
        },
    },
};
</script>

<style scoped>
.jd-floating-menu {
    position: fixed;
    z-index: 1000;
    width: 60px;
    height: 60px;
    touch-action: none;
    transition: left 0.3s ease, top 0.3s ease, transform 0.3s ease;
}

.jd-floating-menu.collapsed {
    transform: translateX(20px);
}

.jd-floating-menu.left-side.collapsed {
    transform: translateX(-20px);
}

.jd-menu-main {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 60px;
    height: 60px;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.25);
    backdrop-filter: blur(20px);
    -webkit-backdrop-filter: blur(20px);
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    user-select: none;
    z-index: 2;
    border: 1px solid rgba(255, 255, 255, 0.3);
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.15);
    transition: background 0.2s ease, border-color 0.2s ease,
        box-shadow 0.2s ease;
}

.jd-menu-main svg {
    width: 28px;
    height: 28px;
    fill: #ffffff;
    transition: fill 0.2s ease;
}

/* 暗色主题 */
.jd-floating-menu.dark-theme .jd-menu-main {
    background: rgba(0, 0, 0, 0.4);
    border-color: rgba(255, 255, 255, 0.4);
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.25);
}

.jd-floating-menu.dark-theme .jd-menu-main svg {
    fill: #ffffff;
}

/* 亮色主题 */
.jd-floating-menu.light-theme .jd-menu-main {
    background: rgba(255, 255, 255, 0.8);
    border-color: rgba(0, 0, 0, 0.15);
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.12);
}

.jd-floating-menu.light-theme .jd-menu-main svg {
    fill: #333333;
}

/* 子菜单按钮容器 */
.jd-menu-buttons {
    position: absolute;
    bottom: 70px;
    left: 5px;
    display: flex;
    flex-direction: column;
    gap: 10px;
    pointer-events: none;
    z-index: 1;
}

.jd-menu-buttons.expanded {
    pointer-events: auto;
}

/* 子菜单按钮 */
.jd-menu-btn {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.25);
    backdrop-filter: blur(20px);
    -webkit-backdrop-filter: blur(20px);
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    flex-direction: column;
    color: #ffffff;
    font-size: 10px;
    text-align: center;
    flex-shrink: 0;
    opacity: 0;
    transform: translateY(20px);
    transition: opacity 0.3s ease, transform 0.3s ease, background 0.2s ease,
        border-color 0.2s ease, box-shadow 0.2s ease, color 0.2s ease;
    border: 1px solid rgba(255, 255, 255, 0.3);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.12);
}

.jd-floating-menu.dark-theme .jd-menu-btn {
    background: rgba(0, 0, 0, 0.4);
    border-color: rgba(255, 255, 255, 0.4);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
    color: #ffffff;
}

.jd-floating-menu.light-theme .jd-menu-btn {
    background: rgba(255, 255, 255, 0.85);
    border-color: rgba(0, 0, 0, 0.15);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    color: #333333;
}

.jd-menu-btn svg {
    width: 22px;
    height: 22px;
    fill: #ffffff;
    margin-bottom: 2px;
    transition: fill 0.2s ease;
}

.jd-floating-menu.dark-theme .jd-menu-btn svg {
    fill: #ffffff;
}

.jd-floating-menu.light-theme .jd-menu-btn svg {
    fill: #333333;
}

.jd-menu-btn span {
    color: #ffffff;
    transition: color 0.2s ease;
}

.jd-floating-menu.dark-theme .jd-menu-btn span {
    color: #ffffff;
}

.jd-floating-menu.light-theme .jd-menu-btn span {
    color: #333333;
}

/* 展开动画 */
.jd-menu-buttons.expanded .jd-menu-btn {
    opacity: 1;
    transform: translateY(0);
}

.jd-menu-buttons.expanded .jd-menu-btn:nth-child(1) {
    transition-delay: 0s;
}

.jd-menu-buttons.expanded .jd-menu-btn:nth-child(2) {
    transition-delay: 0.08s;
}

.jd-menu-buttons.expanded .jd-menu-btn:nth-child(3) {
    transition-delay: 0.16s;
}
</style>