<template>
    <div class="crop-alert-floating-panel">
        <floating-panel
            class="floating-panel"
            :class="{ 'background-panel': isBackground }"
            v-model:height="height"
            :anchors="anchors"
            :content-draggable="true"
            @height-change="handleHeightChange"
        >
            <div
                class="floating-panel-content"
                :style="{ paddingBottom: `${tabBarHeight}px` }"
            >
                <div class="panel-shell" ref="panelShellRef">
                    <div class="crop-header">
                        <div class="crop-info">
                            <el-avatar class="crop-avatar" :size="24" :src="cropAvatar" />
                            <span class="crop-name">{{ currentCropName }}</span>
                            <span class="crop-badge">当前作物</span>
                        </div>
                        <el-tooltip
                            v-model:visible="cropMenuVisible"
                            placement="bottom"
                            trigger="click"
                            effect="light"
                            :show-arrow="true"
                            popper-class="crop-switch-tooltip"
                            :teleported="true"
                        >
                            <template #content>
                                <div class="crop-option-list">
                                    <div
                                        v-for="item in cropOptions"
                                        :key="item"
                                        class="crop-option-item"
                                        :class="{ active: item === currentCropName }"
                                        @click="handleSelectCrop(item)"
                                    >
                                        {{ item }}
                                    </div>
                                </div>
                            </template>
                            <div class="switch-btn" :class="{ 'is-open': cropMenuVisible }">
                                <span>{{ t("growthReport.switchCategory") }}</span>
                                <icon
                                    :name="cropMenuVisible ? 'arrow-up' : 'arrow-down'"
                                    class="switch-btn__icon"
                                />
                            </div>
                        </el-tooltip>
                    </div>

                    <div class="alert-list">
                        <div
                            v-for="item in alertCards"
                            :key="item.id"
                            class="alert-card"
                        >
                            <div class="alert-card__header">
                                <div class="alert-card__title-wrap">
                                    <img class="alert-card__icon" :src="item.icon" alt="" />
                                    <span class="alert-card__title">{{ item.title }}</span>
                                </div>
                                <span class="alert-card__link" @click="handleViewDetail(item)">
                                    查看详情
                                </span>
                            </div>
                            <div class="alert-card__content-wrap">
                                <span class="alert-card__content">{{ item.content }}</span>
                                <span
                                    v-if="item.patrolTip"
                                    class="alert-card__patrol"
                                    @click="handlePatrolTip(item)"
                                >
                                    <el-icon class="alert-card__patrol-icon"><Link /></el-icon>
                                    <span>{{ item.patrolTip }}</span>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </floating-panel>

        <div class="expand-btn-wrap" v-show="height === defaultHeight">
            <span>{{ t("growthReport.cropTitle") }}</span>
            <div class="expand-btn" @click="handleExpandBtnClick">
                <span>{{ t("growthReport.expand") }}</span>
                <el-icon><ArrowUpBold /></el-icon>
            </div>
        </div>
    </div>
</template>

<script setup>
import { FloatingPanel, Icon } from "vant";
import { ArrowUpBold, Link } from "@element-plus/icons-vue";
import { nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue";
import { useI18n } from "@/i18n";

const { t } = useI18n();

const props = defineProps({
    cropName: {
        type: String,
        default: "水稻",
    },
    cropAvatar: {
        type: String,
        default: require("@/assets/img/home/banner.png"),
    },
    cropOptions: {
        type: Array,
        default: () => ["水稻", "荔枝", "香蕉"],
    },
});

const emit = defineEmits(["switchCategory", "viewDetail", "patrolTip", "heightChange"]);

const weatherIcon = require("@/assets/img/report/weather.png");
const tabBarHeight = ref(Number(localStorage.getItem("tabBarHeight")) || 50);

const currentCropName = ref(props.cropName);
const cropMenuVisible = ref(false);

watch(
    () => props.cropName,
    (name) => {
        if (name) currentCropName.value = name;
    }
);

const handleSelectCrop = (name) => {
    if (!name || name === currentCropName.value) {
        cropMenuVisible.value = false;
        return;
    }
    currentCropName.value = name;
    cropMenuVisible.value = false;
    emit("switchCategory", name);
};

const PANEL_HEADER_BAR = 30; // 隐藏原生 header 后，内容顶部留白
const PANEL_BOTTOM_GAP = 16;

const defaultHeight = ref(0);
const fullHeight = Math.round(window.innerHeight);
const anchors = ref([defaultHeight.value, 280 + tabBarHeight.value, fullHeight]);
const height = ref(anchors.value[1]);

const isBackground = ref(false);
const panelShellRef = ref(null);
let resizeObserver = null;
let syncing = false;

const syncMidAnchor = () => {
    const shell = panelShellRef.value;
    if (!shell || syncing) return;

    // scrollHeight 才是内容真实高度；offsetHeight 在被裁切时会偏小
    const contentH = shell.scrollHeight;
    const idealMid = Math.round(
        contentH + PANEL_HEADER_BAR + PANEL_BOTTOM_GAP + tabBarHeight.value
    );
    // 留一点顶部空间，避免直接顶满屏
    const maxMid = fullHeight - 48;
    const nextMid = Math.max(240, Math.min(idealMid, maxMid));

    if (Math.abs(nextMid - anchors.value[1]) < 2) return;

    syncing = true;
    const wasAtMid = Math.abs(height.value - anchors.value[1]) < 2;
    anchors.value = [defaultHeight.value, nextMid, fullHeight];
    if (wasAtMid) {
        height.value = nextMid;
    }
    nextTick(() => {
        syncing = false;
    });
};

const alertCards = [
    {
        id: "warning",
        title: "具体预警",
        icon: weatherIcon,
        content: "详情体预警体预警体预警体预警体预警体预详情详情详情详情详情详情详情详情详情详情",
        patrolTip: "",
    },
    {
        id: "stress",
        title: "某某胁迫",
        icon: weatherIcon,
        content: "详情详情详情具体预警具体预警情详情详详情详情详情详情详情详情",
        patrolTip: "异常态势巡园要点",
    },
];

const handleViewDetail = (item) => {
    emit("viewDetail", item);
};

const handlePatrolTip = (item) => {
    emit("patrolTip", item);
};

const handleHeightChange = ({ height: nextHeight }) => {
    isBackground.value = nextHeight > anchors.value[1];
    emit("heightChange", nextHeight);
};

const handleExpandBtnClick = () => {
    height.value = anchors.value[1];
    emit("heightChange", anchors.value[1]);
};

onMounted(() => {
    nextTick(() => {
        // 等布局完成后再量一次，避免首屏高度偏小
        requestAnimationFrame(() => {
            syncMidAnchor();
            setTimeout(() => {
                syncMidAnchor();
                emit("heightChange", height.value);
            }, 80);
        });
        if (!panelShellRef.value || typeof ResizeObserver === "undefined") return;
        resizeObserver = new ResizeObserver(() => {
            syncMidAnchor();
            emit("heightChange", height.value);
        });
        resizeObserver.observe(panelShellRef.value);
    });
});

onBeforeUnmount(() => {
    resizeObserver?.disconnect?.();
    resizeObserver = null;
});
</script>

<style lang="scss" scoped>
.van-floating-panel {
    border-radius: 0;
}

.floating-panel {
    background: transparent;

    ::v-deep {
        .van-floating-panel__content {
            background: transparent;
            overflow-y: auto;
        }

        // 隐藏拖拽条，并取消其占位
        .van-floating-panel__header {
            height: 0 !important;
            min-height: 0 !important;
            padding: 0 !important;
            margin: 0 !important;
            overflow: hidden;
            opacity: 0;
            pointer-events: none;
        }
    }

    .floating-panel-content {
        width: calc(100% - 20px);
        margin: 30px auto 0; // 补偿隐藏 header 的 30px，整体下移
        box-sizing: border-box;
    }

    .panel-shell {
        padding: 12px;
        border-radius: 16px;
        background: linear-gradient(180deg, #b2dbfb 0%, #cbe8ff 100%);
        box-sizing: border-box;
    }

    .crop-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 10px;
        margin-bottom: 10px;
    }

    .crop-info {
        display: flex;
        align-items: center;
        gap: 6px;
        min-width: 0;
    }

    .crop-avatar {
        flex-shrink: 0;
    }

    .crop-name {
        font-size: 18px;
        font-weight: 500;
        color: #000000;
        line-height: 26px;
    }

    .crop-badge {
        flex-shrink: 0;
        height: 20px;
        padding: 0 5px;
        border-radius: 2px;
        background: #2199f8;
        color: #fff;
        backdrop-filter: blur(4px);
        font-size: 12px;
        line-height: 20px;
    }

    .switch-btn {
        display: flex;
        align-items: center;
        gap: 2px;
        flex-shrink: 0;
        height: 28px;
        padding: 0 10px;
        border-radius: 14px;
        border: 1px solid #2199f8;
        background: #fff;
        color: #2199f8;
        font-size: 12px;

        &.is-open {
            border-color: #2199f8;
            box-shadow: 0 0 0 1px rgba(33, 153, 248, 0.15);
        }

        &__icon {
            font-size: 12px;
            color: #2199f8;
        }
    }

    .alert-list {
        display: flex;
        flex-direction: column;
        gap: 10px;
    }

    .alert-card {
        padding: 12px;
        border-radius: 12px;
        background: #fff;
        box-sizing: border-box;

        &__header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 8px;
        }

        &__title-wrap {
            display: flex;
            align-items: flex-end;
            gap: 6px;
            min-width: 0;
        }

        &__icon {
            width: 17px;
            height: 17px;
            flex-shrink: 0;
        }

        &__title {
            font-size: 14px;
            font-weight: 500;
            color: #000000;
        }

        &__link {
            flex-shrink: 0;
            font-size: 12px;
            color: #2199f8;
        }

        &__content-wrap {
            margin-top: 8px;
        }

        &__content {
            font-size: 14px;
            line-height: 21px;
            color: rgba(6, 6, 6, 0.5);
            word-break: break-all;
        }

        &__patrol {
            padding-left: 6px;
            display: inline-flex;
            align-items: center;
            gap: 4px;
            font-size: 14px;
            color: #2199f8;
            text-decoration: underline;
            text-underline-offset: 4px;
        }

        &__patrol-icon {
            font-size: 16px;
        }
    }

    &.background-panel {
        background: #f5f7fb;
    }
}

.expand-btn-wrap {
    position: absolute;
    bottom: 62px;
    left: 12px;
    width: calc(100% - 24px);
    background-image: linear-gradient(180deg, #d7eafc 0%, #ffffff 100%);
    border-radius: 14px;
    padding: 15px 12px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-weight: 500;
    font-size: 15px;

    .expand-btn {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 4px;
        font-size: 13px;
        color: #2199f8;
    }
}
</style>

<style lang="scss">
.crop-switch-tooltip {
    z-index: 3000 !important;
    padding: 8px 0 !important;
    min-width: 120px;
    border: none !important;
    border-radius: 12px !important;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12) !important;
    background: #fff !important;

    .el-popper__arrow::before {
        background: #fff !important;
        border: none !important;
    }

    .crop-option-list {
        display: flex;
        flex-direction: column;
    }

    .crop-option-item {
        padding: 10px 20px;
        font-size: 14px;
        line-height: 20px;
        color: #333;
        cursor: pointer;

        &:active,
        &.active {
            color: #2199f8;
            background: rgba(33, 153, 248, 0.06);
        }
    }
}
</style>
