| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797 |
- <template>
- <div class="crop-alert-floating-panel">
- <floating-panel
- class="floating-panel"
- :class="{ 'background-panel': isBackground }"
- :style="{ bottom: `${tabBarHeight}px` }"
- v-model:height="height"
- :anchors="anchors"
- :content-draggable="true"
- @height-change="handleHeightChange"
- >
- <div class="floating-panel-content">
- <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>
- <div class="switch-wrap">
- <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, index) in cropOptions"
- :key="index"
- class="crop-option-item"
- :class="{ active: index === activeIndex }"
- @click="handleSelectCrop(index)"
- >
- {{ item }}
- </div>
- </div>
- </template>
- <div
- class="switch-btn"
- :class="{ 'is-open': cropMenuVisible }"
- @click="dismissGuide"
- >
- <span>{{ t("growthReport.switchCategory") }}</span>
- <el-icon
- class="switch-btn__icon"
- :class="{ 'is-open-icon': cropMenuVisible }"
- >
- <CaretBottom />
- </el-icon>
- </div>
- </el-tooltip>
- <div v-if="guideVisible" class="crop-guide-bubble">
- <span class="crop-guide-bubble__arrow"></span>
- <div class="crop-guide-bubble__content">
- 当下作物为<span class="crop-guide-bubble__crop">{{ currentCropName }}</span>,请录入拟种植的作物,之后变为对应作物的气象预警
- </div>
- </div>
- </div>
- </div>
- <div class="alert-list" v-show="!isBackground">
- <div
- v-for="(item, index) in alertCards"
- :key="index"
- 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 && item.title !== '正常气象'"
- 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>
- </template>
- <script setup>
- import { FloatingPanel } from "vant";
- import { CaretBottom, Link } from "@element-plus/icons-vue";
- import { nextTick, onActivated, onBeforeUnmount, onMounted, ref, watch } from "vue";
- import { useStore } from "vuex";
- import { useI18n } from "@/i18n";
- import { useRouter } from "vue-router";
- const router = useRouter();
- const store = useStore();
- const { t } = useI18n();
- const GUIDE_STORAGE_KEY = "GROWTH_REPORT_CROP_SWITCH_GUIDE";
- const CARD_ID = {
- WARNING: "warning",
- STRESS: 2,
- };
- const props = defineProps({
- /** 当前选中农场 id,切换农场后触发分区 / 预警重拉 */
- farmId: {
- type: [String, Number],
- default: "",
- },
- cropName: {
- type: String,
- default: "",
- },
- cropAvatar: {
- type: String,
- default: "https://birdseye-img.sysuimars.com/dinggou-mini/defalut-icon.png",
- },
- });
- /** 分区列表(getZones),选项文案用 zone_name */
- const zoneList = ref([]);
- const cropOptions = ref([]);
- const selectedZoneId = ref(null);
- const activeIndex = ref(0);
- const emit = defineEmits(["viewDetail", "heightChange", "zoneChange"]);
- const weatherIcon = require("@/assets/img/report/weather.png");
- /** 底部 tabBar 高度(含小程序安全区),优先读 DOM / store */
- const resolveTabBarHeight = () => {
- const fromDom = document.querySelector(".van-tabbar")?.offsetHeight;
- const fromStore = Number(store.state.home.tabBarHeight) || 0;
- const fromStorage = Number(localStorage.getItem("tabBarHeight")) || 0;
- return fromDom || fromStore || fromStorage || 50;
- };
- const tabBarHeight = ref(resolveTabBarHeight());
- const currentCropName = ref(props.cropName || "");
- const cropMenuVisible = ref(false);
- const guideVisible = ref(false);
- /** 防止切换农场时旧请求回写覆盖新数据 */
- let reloadToken = 0;
- /** 展示名:优先当前分区 zone_name,其次 props / 农场缓存(新建农场尚无分区时用) */
- const resolveCropNameDisplay = () => {
- const zone = zoneList.value[activeIndex.value];
- if (zone?.variety_name) return zone.variety_name;
- const farm = getSelectedFarm();
- return (
- farm.variety_name ||
- farm.crop_name ||
- farm.farm_variety ||
- ""
- );
- };
- const syncCropNameDisplay = () => {
- currentCropName.value = resolveCropNameDisplay();
- };
- watch(
- () => props.cropName,
- () => {
- syncCropNameDisplay();
- }
- );
- watch(
- () => props.farmId,
- (id, prev) => {
- if (String(id ?? "") === String(prev ?? "")) return;
- syncCropNameDisplay();
- nextTick(() => reloadFarmAlerts());
- }
- );
- const dismissGuide = () => {
- if (!guideVisible.value) return;
- guideVisible.value = false;
- localStorage.setItem(GUIDE_STORAGE_KEY, "1");
- };
- const tryShowGuide = () => {
- if (localStorage.getItem(GUIDE_STORAGE_KEY)) return;
- guideVisible.value = true;
- };
- const handleOutsideClick = (event) => {
- if (!guideVisible.value) return;
- const target = event.target;
- if (target?.closest?.(".crop-guide-bubble") || target?.closest?.(".switch-btn")) return;
- dismissGuide();
- };
- watch(cropMenuVisible, (visible) => {
- if (visible) dismissGuide();
- });
- const applySelectedZone = (index) => {
- const zone = zoneList.value[index];
- if (!zone) {
- activeIndex.value = 0;
- selectedZoneId.value = null;
- syncCropNameDisplay();
- emit("zoneChange", null);
- return;
- }
- activeIndex.value = index;
- selectedZoneId.value = zone.zone_id ?? null;
- syncCropNameDisplay();
- emit("zoneChange", selectedZoneId.value);
- };
- const handleSelectCrop = (index) => {
- dismissGuide();
- cropMenuVisible.value = false;
- if (index === activeIndex.value) return;
- applySelectedZone(index);
- fetchAlertCards();
- };
- const PANEL_HEADER_BAR = 14; // van-floating-panel 原生 header 高度
- const PANEL_BOTTOM_GAP = 12;
- /** 收起态:仅作物头,高度不含 tabBar(tabBar 用 bottom 顶开) */
- const COLLAPSED_CONTENT_HEIGHT = 72;
- /** 锚点只算面板自身高度,底部用 style.bottom 避开 tabBar,避免高度+padding 重复抬高 */
- const getCollapsedAnchor = () => COLLAPSED_CONTENT_HEIGHT;
- const anchors = ref([getCollapsedAnchor(), 280]);
- const height = ref(anchors.value[1]);
- const isBackground = ref(false);
- const panelShellRef = ref(null);
- let resizeObserver = null;
- let syncing = false;
- const emitPanelHeight = (panelH = height.value) => {
- // 对外抛出「距视口底」的占用高度,方便邀请按钮等避让
- emit("heightChange", panelH + tabBarHeight.value);
- };
- const syncMidAnchor = () => {
- const shell = panelShellRef.value;
- if (!shell || syncing) return;
- tabBarHeight.value = resolveTabBarHeight();
- const collapsed = getCollapsedAnchor();
- // scrollHeight 才是内容真实高度;offsetHeight 在被裁切时会偏小
- const contentH = shell.scrollHeight;
- const idealMid = Math.round(contentH + PANEL_HEADER_BAR + PANEL_BOTTOM_GAP);
- // 留一点顶部空间,并扣掉底部 tabBar
- const maxMid = Math.round(window.innerHeight - tabBarHeight.value) - 48;
- const nextMid = Math.max(collapsed + 80, Math.min(idealMid, maxMid));
- if (
- Math.abs(nextMid - anchors.value[1]) < 2 &&
- Math.abs(collapsed - anchors.value[0]) < 2
- ) {
- return;
- }
- syncing = true;
- const wasAtMid = Math.abs(height.value - anchors.value[1]) < 2;
- const wasCollapsed = Math.abs(height.value - anchors.value[0]) < 2;
- anchors.value = [collapsed, nextMid];
- if (wasAtMid) {
- height.value = nextMid;
- } else if (wasCollapsed) {
- height.value = collapsed;
- }
- nextTick(() => {
- syncing = false;
- emitPanelHeight();
- });
- };
- watch(
- () => store.state.home.tabBarHeight,
- (val) => {
- if (!val) return;
- tabBarHeight.value = val;
- syncMidAnchor();
- }
- );
- const alertCards = ref([
- {
- id: CARD_ID.WARNING,
- source: "warning",
- title: "",
- icon: weatherIcon,
- content: "",
- patrolTip: "",
- },
- {
- id: CARD_ID.STRESS,
- source: "stress",
- type: "abnormal",
- title: "",
- icon: weatherIcon,
- content: "",
- patrolTip: "异常态势巡园要点",
- },
- ]);
- const getSelectedFarm = () => {
- try {
- return JSON.parse(localStorage.getItem("selectedFarmData") || "{}");
- } catch {
- return {};
- }
- };
- /** 以缓存为准,避免 onActivated 时 props.farmId 尚未跟上父组件同步 */
- const resolveFarmId = () => {
- const farm = getSelectedFarm();
- const id =
- localStorage.getItem("selectedFarmId") ||
- farm.farm_id ||
- farm.id ||
- props.farmId;
- return id != null && id !== "" ? id : "";
- };
- /** 保证有zone_id */
- const resolveZoneId = () => {
- const farm = getSelectedFarm();
- return farm.zone_id || "";
- };
- const formatLocalDate = (date) => {
- const y = date.getFullYear();
- const m = String(date.getMonth() + 1).padStart(2, "0");
- const d = String(date.getDate()).padStart(2, "0");
- return `${y}-${m}-${d}`;
- };
- /** 用当前选中农场 + 分区 + 当天日期(zone 只信面板选中态,避免缓存滞后) */
- const getQueryParams = () => {
- return {
- farm_id: resolveFarmId(),
- zone_id: selectedZoneId.value || resolveZoneId(),
- date: formatLocalDate(new Date()),
- };
- };
- /** 拉取分区列表,填充切换作物下拉 */
- const fetchZones = async (token = reloadToken) => {
- const farmId = resolveFarmId();
- if (farmId == null || farmId === "") {
- zoneList.value = [];
- cropOptions.value = [];
- applySelectedZone(-1);
- return;
- }
- try {
- const res = await VE_API.questionnaire.getZones({ farm_id: farmId });
- // 旧请求回包时不覆盖当前选中分区
- if (token !== reloadToken) return;
- const zones = Array.isArray(res?.data?.zones) ? res.data.zones : [];
- zoneList.value = zones;
- cropOptions.value = zones.map((item) => item.zone_name || "");
- applySelectedZone(zones.length ? 0 : -1);
- } catch (e) {
- if (token !== reloadToken) return;
- console.warn("[CropAlertPanel] getZones failed", e);
- zoneList.value = [];
- cropOptions.value = [];
- applySelectedZone(-1);
- }
- };
- /** 切换农场 / 回页:先清旧 zone,再拉分区,最后拉预警 */
- const reloadFarmAlerts = async () => {
- const token = ++reloadToken;
- selectedZoneId.value = null;
- activeIndex.value = 0;
- zoneList.value = [];
- cropOptions.value = [];
- syncCropNameDisplay();
- await fetchZones(token);
- if (token !== reloadToken) return;
- await fetchAlertCards(token);
- };
- /** 接口可能返回对象或数组,统一取第一条 */
- const pickFirstRecord = (res) => {
- const data = res?.data ?? res;
- if (Array.isArray(data)) return data[0] || null;
- if (data && typeof data === "object") return data;
- return null;
- };
- const patchAlertCard = (cardId, patch) => {
- const card = alertCards.value.find((item) => item.id === cardId);
- if (!card) return;
- Object.assign(card, patch);
- };
- const applyWeatherRisk = (record) => {
- patchAlertCard(CARD_ID.WARNING, {
- title: record?.risk_name || "",
- content: record?.explain_simple || "",
- });
- };
- const applyWeatherStress = (record) => {
- patchAlertCard(CARD_ID.STRESS, {
- title: record?.stress_name || "",
- content: record?.explain_simple || "",
- });
- };
- const fetchAlertCards = async (token = reloadToken) => {
- const queryParams = getQueryParams();
- if (queryParams.farm_id == null || queryParams.farm_id === "") {
- if (token !== reloadToken) return;
- applyWeatherRisk(null);
- applyWeatherStress(null);
- nextTick(() => syncMidAnchor());
- return;
- }
- const [riskRes, stressRes] = await Promise.allSettled([
- VE_API.questionnaire.getWeatherRisk(queryParams),
- VE_API.questionnaire.getWeatherStress(queryParams),
- ]);
- // 切换农场期间若有更新请求,丢弃旧回包
- if (token !== reloadToken) return;
- // 成功但无数据时清空旧卡片,避免切换农场后残留
- applyWeatherRisk(riskRes.status === "fulfilled" ? pickFirstRecord(riskRes.value) : null);
- applyWeatherStress(stressRes.status === "fulfilled" ? pickFirstRecord(stressRes.value) : null);
- nextTick(() => syncMidAnchor());
- };
- const handleViewDetail = (item) => {
- router.push({
- path: "/alert_detail",
- query: {
- title: item?.title || "具体预警",
- type: item?.source || "warning",
- },
- });
- };
- const handlePatrolTip = (item) => {
- const isAbnormal = item?.type === "abnormal";
- router.push({
- path: isAbnormal ? "/abnormal_track" : "/growth_track",
- query: {
- id: item.id,
- },
- });
- };
- const handleHeightChange = ({ height: nextHeight }) => {
- isBackground.value = nextHeight < anchors.value[1];
- emitPanelHeight(nextHeight);
- };
- onMounted(() => {
- nextTick(() => {
- tabBarHeight.value = resolveTabBarHeight();
- // 等布局完成后再量一次,避免首屏高度偏小;小程序里 tabBar 可能稍晚才量到
- requestAnimationFrame(() => {
- syncMidAnchor();
- setTimeout(() => {
- tabBarHeight.value = resolveTabBarHeight();
- syncMidAnchor();
- emitPanelHeight();
- tryShowGuide();
- }, 80);
- setTimeout(() => {
- tabBarHeight.value = resolveTabBarHeight();
- syncMidAnchor();
- }, 600);
- });
- if (!panelShellRef.value || typeof ResizeObserver === "undefined") return;
- resizeObserver = new ResizeObserver(() => {
- syncMidAnchor();
- emitPanelHeight();
- });
- resizeObserver.observe(panelShellRef.value);
- });
- document.addEventListener("click", handleOutsideClick, true);
- });
- /** 进入 / 从切换农场返回:nextTick 等父组件 syncSelectedFarmId 落盘后再拉 */
- onActivated(() => {
- syncCropNameDisplay();
- nextTick(() => {
- syncCropNameDisplay();
- reloadFarmAlerts();
- });
- });
- onBeforeUnmount(() => {
- document.removeEventListener("click", handleOutsideClick, true);
- resizeObserver?.disconnect?.();
- resizeObserver = null;
- });
- defineExpose({ refreshAlerts: fetchAlertCards, refreshZones: fetchZones, reloadFarmAlerts });
- </script>
- <style lang="scss" scoped>
- .van-floating-panel {
- border-radius: 0;
- }
- .floating-panel {
- background: transparent;
- ::v-deep {
- .van-floating-panel__header {
- background: transparent;
- height: 16px;
- }
- .van-floating-panel__header-bar {
- width: 36px;
- height: 4px;
- background: rgba(255, 255, 255, 0.5);
- border-radius: 4px;
- }
- .van-floating-panel__content {
- background: transparent;
- overflow-y: auto;
- }
- }
- .floating-panel-content {
- width: calc(100% - 20px);
- margin: 0 auto;
- // margin: 14px auto 0; // 补偿隐藏 header 的 10px,原本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-wrap {
- position: relative;
- flex-shrink: 0;
- z-index: 5;
- }
- .crop-guide-bubble {
- position: absolute;
- top: calc(100% + 10px);
- right: 20px;
- width: 216px;
- padding: 6px 10px;
- border-radius: 6px;
- background: rgba(0, 0, 0, 0.8);
- box-sizing: border-box;
- z-index: 20;
- pointer-events: auto;
- &__arrow {
- position: absolute;
- top: -5px;
- right: 12px;
- width: 0;
- height: 0;
- border-left: 6px solid transparent;
- border-right: 6px solid transparent;
- border-bottom: 6px solid rgba(0, 0, 0, 0.8);
- }
- &__content {
- font-size: 14px;
- line-height: 22px;
- color: #fff;
- word-break: break-all;
- text-align: justify;
- }
- &__crop {
- padding: 0 2px;
- color: #2199f8;
- }
- }
- .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: 14px;
- color: #2199f8;
- transition: transform 0.3s ease;
- }
- .is-open-icon {
- transform: rotate(180deg);
- }
- }
- .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 {
- .panel-shell {
- padding: 6px 10px 10px 10px;
- background: url("@/assets/img/report/type-bg.png");
- background-size: calc(100vw - 20px) 40px;
- background-repeat: no-repeat;
- background-position: center top;
- .crop-header {
- // padding-bottom: 60px;
- }
- }
- }
- }
- </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>
|