Ver código fonte

fix: 增加分享

lxf 5 dias atrás
pai
commit
d403e85009

+ 35 - 11
src/App.vue

@@ -78,6 +78,36 @@ const elementLocale = computed(() => (locale.value === "en" ? en : zhCn));
 const route = useRoute();
 const router = useRouter();
 
+function isTruthyFlag(value) {
+    return value === 1 || value === "1" || value === true || value === "true";
+}
+
+function parseMaybeJson(value) {
+    if (value == null || value === "") return null;
+    if (typeof value === "object") return value;
+    try {
+        return JSON.parse(value);
+    } catch {
+        return null;
+    }
+}
+
+/** 分享进页(fromShare):即使路由带 showTabbar 也不展示底部菜单 */
+function isFromShareRoute(r = route) {
+    const q = r.query || {};
+    if (isTruthyFlag(q.fromShare)) return true;
+    const paramsPage = parseMaybeJson(q.paramsPage);
+    if (isTruthyFlag(paramsPage?.fromShare)) return true;
+    const mini = parseMaybeJson(q.miniJson);
+    if (isTruthyFlag(mini?.fromShare)) return true;
+    if (isTruthyFlag(parseMaybeJson(mini?.paramsPage)?.fromShare)) return true;
+    return false;
+}
+
+function syncTabbarVisible() {
+    showTab.value = !!(route.meta.showTabbar && !isFromShareRoute(route));
+}
+
 // 首页loading加载完才显示底部导航栏
 const showTab = ref(false);
 // 0: 农户, 1: 专家, 2:农资农服
@@ -131,9 +161,7 @@ watch(
 onMounted(() => {
     setTimeout(() => {
         curRole.value = store.state.app.curRole;
-        if (route.meta.showTabbar) {
-            showTab.value = true;
-        }
+        syncTabbarVisible();
         nextTick(() => {
             const tabBarElement = document.querySelector(".van-tabbar");
             if (tabBarElement) {
@@ -146,13 +174,9 @@ onMounted(() => {
 });
 
 watch(
-    () => route.name,
-    (newName, oldName) => {
-        // 在这里执行你的自定义逻辑
-        showTab.value = false;
-        if (route.meta.showTabbar) {
-            showTab.value = true;
-        }
+    () => [route.name, route.fullPath],
+    () => {
+        syncTabbarVisible();
         nextTick(() => {
             const tabBarElement = document.querySelector(".van-tabbar");
             if (tabBarElement) {
@@ -160,7 +184,7 @@ watch(
                 localStorage.setItem("tabBarHeight", tabBarHeight);
                 store.commit("home/SET_TAB_BAR_HEIGHT", tabBarHeight);
             }
-            curRole.value = store.state.app.curRole
+            curRole.value = store.state.app.curRole;
         });
     },
     { immediate: false }

BIN
src/assets/img/type_icon/小麦.png


BIN
src/assets/img/type_icon/李.png


BIN
src/assets/img/type_icon/桃.png


BIN
src/assets/img/type_icon/梨.png


BIN
src/assets/img/type_icon/棉花.png


BIN
src/assets/img/type_icon/油菜.png


BIN
src/assets/img/type_icon/苹果.png


+ 1 - 1
src/components/customHeader.vue

@@ -1,7 +1,7 @@
 <template>
     <div class="custom-header" :style="{ background: bgColor, color: titleColor }">
         <div class="home" @click="goHome" v-if="showHome">
-            <el-icon class="icon" :color="iconColor"><HomeFilled /></el-icon>
+            <el-icon size="20" class="icon" :color="iconColor"><HomeFilled /></el-icon>
         </div>
         <div class="back" @click="goback" v-else-if="!isClose">
             <el-icon class="icon" :color="iconColor"><ArrowLeftBold /></el-icon>

+ 34 - 4
src/components/popup/restorePlantingPopup.vue

@@ -16,7 +16,7 @@
             <div class="restore-planting-popup__header">
                 <div class="restore-planting-popup__title">
                     <div>{{ t("agriFile.restoreFillQuestions") }}</div>
-                    <div>立即 <span class="light-text">恢复种植服务</span></div>
+                    <div>生成 <span class="light-text">精准农事档案</span></div>
                 </div>
             </div>
 
@@ -298,6 +298,24 @@ const applyDateInteract = (data) => {
     sampleImage.value = resolveImageUrl(data.guide_url) || DEFAULT_SAMPLE_IMAGE;
 };
 
+/** 默认勾选中间项(3 项时为「顺利到达」),并写入可提交的 period_code */
+function selectMiddlePhenologyOption() {
+    const options = phenologyOptions.value;
+    if (!options.length) {
+        phenologyAnswer.value = "";
+        selectedPeriodCode.value = "";
+        return;
+    }
+    const middle = options[Math.floor(options.length / 2)];
+    phenologyAnswer.value = middle.value;
+    if (middle.value === "reached") {
+        selectedPeriodCode.value =
+            interactMap.value[currentInteractKey.value]?.period_code || "";
+        return;
+    }
+    selectedPeriodCode.value = "";
+}
+
 /** 按 interact key 刷新问题二文案与配图 */
 const applyPhenologyByKey = (key) => {
     const item = interactMap.value[key];
@@ -308,7 +326,7 @@ const applyPhenologyByKey = (key) => {
     phenologyQuestion.value = `${PHENOLOGY_PREFIX}${name} ?`;
     phenologyImage.value = resolveImageUrl(item.pheno_pic_url) || DEFAULT_PHENOLOGY_IMAGE;
     patrolGuideImage.value = resolveImageUrl(item.interact_pic_url) || (base_img_url2 + PATROL_GUIDE_IMAGE_PATH);
-    selectedPeriodCode.value = "";
+    selectMiddlePhenologyOption();
 };
 
 const hasInteractOptions = (key) => {
@@ -326,12 +344,19 @@ const movePhenology = (direction) => {
     while (nextIdx >= 0 && nextIdx < keys.length) {
         if (hasInteractOptions(keys[nextIdx])) {
             applyPhenologyByKey(keys[nextIdx]);
-            phenologyAnswer.value = "";
             return true;
         }
         nextIdx += step;
     }
-    showWarning(direction === "prev" ? "已是最早物候期" : "已是最晚物候期");
+    const periodName =
+        interactMap.value[currentInteractKey.value]?.period_name ||
+        phenologyHighlight.value ||
+        "当前物候期";
+    const tip =
+        direction === "prev"
+            ? `系统推测当前该作物最早处于 ${periodName},\n请您确认所选物候期是否正确`
+            : `系统推测当前该作物最晚处于 ${periodName},\n请您确认所选物候期是否正确`;
+    showWarning(tip);
     return false;
 };
 
@@ -897,6 +922,11 @@ linear-gradient(180deg, rgba(255, 212, 137, 0.36) 0%, rgba(255, 212, 137, 0) 12%
 
 .el-message.restore-planting-message {
     z-index: 40000 !important;
+    white-space: pre-line;
+    &.el-message--warning .el-message__content {
+        width: max-content;
+        line-height: 19px;
+    }
 }
 
 .restore-planting-success-popup {

+ 7 - 0
src/utils/cropIcon.js

@@ -7,6 +7,13 @@ export const CROP_ICON_MAP = {
     水稻: require("@/assets/img/type_icon/水稻.png"),
     玉米: require("@/assets/img/type_icon/玉米.png"),
     荔枝: require("@/assets/img/type_icon/荔枝.png"),
+    梨: require("@/assets/img/type_icon/梨.png"),
+    李: require("@/assets/img/type_icon/李.png"),
+    棉花: require("@/assets/img/type_icon/棉花.png"),
+    苹果: require("@/assets/img/type_icon/苹果.png"),
+    桃: require("@/assets/img/type_icon/桃.png"),
+    油菜: require("@/assets/img/type_icon/油菜.png"),
+    小麦: require("@/assets/img/type_icon/小麦.png"),
 };
 
 /**

+ 155 - 8
src/views/old_mini/agri_file/pages/diagnosisReport.vue

@@ -1,5 +1,16 @@
 <template>
-    <div class="diagnosis-report-page" v-loading="loading" element-loading-background="rgba(15, 15, 15, 0.55)">
+    <div
+        class="diagnosis-report-page"
+        :class="{ 'is-from-share': isFromShare }"
+        v-loading="loading"
+        element-loading-background="rgba(15, 15, 15, 0.55)"
+    >
+        <custom-header
+            v-if="isFromShare"
+            name="种植全析"
+            :showHome="true"
+            :isGoBack="false"
+        />
         <div class="page-content">
             <div v-if="reportGenerating" class="report-progress">
                 <div class="report-progress__content">
@@ -15,6 +26,10 @@
             </div>
             <template v-else>
                 <div class="diagnosis-header">
+                    <div class="header-share" @click="handleShare">
+                        <Icon name="share" color="rgba(255,255,255,0.85)" />
+                        <span>转发</span>
+                    </div>
                     <div class="diagnosis-header__title-row">
                         <div class="diagnosis-header__title">
                             <div>一份报告</div>
@@ -146,7 +161,8 @@
 
 <script setup>
 import { computed, onActivated, onDeactivated, onBeforeUnmount, ref } from "vue";
-import { useRouter } from "vue-router";
+import { useRoute, useRouter } from "vue-router";
+import { Icon } from "vant";
 // import { useStore } from "vuex";
 import { ElMessage } from "element-plus";
 import { Plus, Edit, List } from "@element-plus/icons-vue";
@@ -156,10 +172,14 @@ import editPlantPointPopup from "../components/editPlantPointPopup.vue";
 // import completeFarmInfoPopup from "@/components/popup/completeFarmInfoPopup.vue";
 // import completeFarmPopupImage from "@/assets/img/common/empty-bg-3.png";
 import restorePlantingPopup from "@/components/popup/restorePlantingPopup.vue";
+import customHeader from "@/components/customHeader.vue";
+import { ensureFarmContext } from "@/utils/selectedFarm";
+import wx from "weixin-js-sdk";
 
 // ---------------------------------------------------------------------------
 // Props / Emits — 无
 // ---------------------------------------------------------------------------
+const route = useRoute();
 const router = useRouter();
 // const store = useStore();
 
@@ -228,6 +248,16 @@ let viewToken = 0;
 // ---------------------------------------------------------------------------
 // 计算属性
 // ---------------------------------------------------------------------------
+const pageParams = computed(() => resolvePageParams());
+/** 通过分享进入:顶栏小房子回首页,且 App 侧隐藏底部菜单 */
+const isFromShare = computed(() => isTruthyFlag(pageParams.value?.fromShare));
+const shareFarmId = computed(
+    () => pageParams.value.farm_id || pageParams.value.farmId || "",
+);
+const shareZoneId = computed(
+    () => pageParams.value.zone_id || pageParams.value.zoneId || "",
+);
+
 const reportTabs = computed(() =>
     MODULE_DEFS.map((def) => {
         const mod = moduleMap.value[def.key];
@@ -244,9 +274,36 @@ const activeModule = computed(() => moduleMap.value[activeReportTab.value] || nu
 // ---------------------------------------------------------------------------
 // 工具函数
 // ---------------------------------------------------------------------------
-// function getMiniUserId() {
-//     return store.state.home.miniUserId || localStorage.getItem("MINI_USER_ID");
-// }
+function isTruthyFlag(value) {
+    return value === 1 || value === "1" || value === true || value === "true";
+}
+
+function parseMaybeJson(value) {
+    if (value == null || value === "") return null;
+    if (typeof value === "object") return value;
+    try {
+        return JSON.parse(value);
+    } catch {
+        return null;
+    }
+}
+
+/**
+ * 分享链路:dev_login 把整份登录 query 塞进 miniJson,
+ * 真正的页面参数在 miniJson.paramsPage(farm_id / zone_id / fromShare)
+ */
+function resolvePageParams() {
+    const mini = parseMaybeJson(route.query.miniJson);
+    if (mini) {
+        const page = parseMaybeJson(mini.paramsPage) || {};
+        return { ...mini, ...page };
+    }
+    const paramsPage = parseMaybeJson(route.query.paramsPage);
+    if (paramsPage) {
+        return { ...route.query, ...paramsPage };
+    }
+    return { ...(route.query || {}) };
+}
 
 function getSelectedFarm() {
     try {
@@ -365,7 +422,7 @@ function resetReportView(farm = {}) {
     moduleMap.value = {};
 }
 
-/** 拉取分区;优先沿用当前选中 / 农场缓存分区 */
+/** 拉取分区;优先分享 zone_id → 当前选中 → 农场缓存分区 */
 async function fetchZoneList(farmId) {
     if (farmId == null || farmId === "") {
         zoneList.value = [];
@@ -377,7 +434,11 @@ async function fetchZoneList(farmId) {
         const zones = Array.isArray(res?.data?.zones) ? res.data.zones : [];
         zoneList.value = zones;
         const farm = getSelectedFarm();
-        const prefer = selectedZoneId.value ?? farm.zone_id ?? farm.zoneId;
+        const prefer =
+            shareZoneId.value ||
+            selectedZoneId.value ||
+            farm.zone_id ||
+            farm.zoneId;
         const matched = zones.find((z) => String(z.zone_id) === String(prefer));
         selectedZoneId.value = (matched || zones[0])?.zone_id ?? null;
     } catch (e) {
@@ -690,6 +751,32 @@ const goAddVariety = () => {
     });
 };
 
+/** 转发种植全析:带 farm_id / zone_id / fromShare */
+const handleShare = () => {
+    const farm = getSelectedFarm();
+    const farmId = farm.farm_id ?? farm.id ?? shareFarmId.value;
+    const zoneId = selectedZoneId.value ?? shareZoneId.value;
+    const farmName = farm.farmName || "我的农场";
+    if (farmId == null || farmId === "" || zoneId == null || zoneId === "") {
+        ElMessage.warning("当前农场或分区信息不全,暂无法转发");
+        return;
+    }
+    const query = {
+        askInfo: { title: "转发种植全析", content: "是否分享该报告给好友" },
+        shareText: `【${farmName}】 种植全析报告已生成,请点击查看!`,
+        targetUrl: "diagnosis_report",
+        paramsPage: JSON.stringify({
+            farm_id: farmId,
+            zone_id: zoneId,
+            fromShare: 1,
+        }),
+        imageUrl: "https://birdseye-img.sysuimars.com/farm-h5/report_cover.png",
+    };
+    wx.miniProgram.navigateTo({
+        url: `/pages/subPages/share_page/index?pageParams=${JSON.stringify(query)}&type=sharePage`,
+    });
+};
+
 const handleBaseAction = (key) => {
     if (key === "adjustPhenology") {
         adjustPhenologyPopupRef.value?.open();
@@ -727,7 +814,15 @@ const handlePlantPointConfirm = (payload) => {
 // };
 
 // tabbar 切换时组件被 keep-alive 缓存,需在激活时重新拉报告 / 校验农场
-onActivated(() => {
+onActivated(async () => {
+    // 分享进页:先按 farm_id / zone_id 切回分享上下文
+    await ensureFarmContext({
+        farmId: shareFarmId.value,
+        zoneId: shareZoneId.value,
+    });
+    if (shareZoneId.value) {
+        selectedZoneId.value = shareZoneId.value;
+    }
     // checkCompleteFarmPopup(); // 暂无农场时不弹「完善农场信息」
     fetchDiagnosisReport();
 });
@@ -758,6 +853,37 @@ onBeforeUnmount(() => {
     background: #060300;
     position: relative;
 
+    &.is-from-share {
+        height: 100vh;
+        display: flex;
+        flex-direction: column;
+        padding-bottom: calc(2px + env(safe-area-inset-bottom));
+        &::before {
+            top: 36px;
+            background: none;
+        }
+        .page-content {
+            position: relative;
+            &::before {
+        content: "";
+        height: 250px;
+        width: 100%;
+        position: absolute;
+        top: 0;
+        left: 0;
+        background: #0a0a0a url("@/assets/img/agricultural/report-bg.png") no-repeat top center;
+        background-size: 100% 250px;
+            }
+        }
+
+        .page-content {
+            flex: 1;
+            min-height: 0;
+            overflow: auto;
+            -webkit-overflow-scrolling: touch;
+        }
+    }
+
     &::before {
         content: "";
         height: 250px;
@@ -821,6 +947,25 @@ onBeforeUnmount(() => {
         padding: 42px 14px 8px;
         box-sizing: border-box;
         color: #fff;
+        position: relative;
+        .header-share {
+            position: absolute;
+            right: 16px;
+            top: 20px;
+            z-index: 2;
+            display: inline-flex;
+            align-items: center;
+            gap: 4px;
+            height: 28px;
+            padding: 0 12px;
+            border-radius: 14px;
+            background: rgba(0, 0, 0, 0.6);
+            border: 1px solid rgba(255, 255, 255, 0.12);
+            color: rgba(255, 255, 255, 0.85);
+            backdrop-filter: blur(4px);
+            font-size: 12px;
+            cursor: pointer;
+        }
 
         &__title-row {
             display: flex;
@@ -867,6 +1012,8 @@ onBeforeUnmount(() => {
     .diagnosis-content {
         padding: 12px 12px;
         background: #060300;
+        position: relative;
+        z-index: 2;
         background: linear-gradient(180deg, rgba(6, 3, 0, 0.1) 0%, rgba(6, 3, 0, 0.8) 2%, #060300 100%);
 
         .variety-bar {

+ 201 - 14
src/views/old_mini/growth_report/growthReportMap.js

@@ -20,21 +20,115 @@ const NO_RANGE_SIDE_METERS = 280;
 /** 可视区中心相对几何中心下移(px),点位略靠下更好看 */
 const VISIBLE_CENTER_OFFSET_Y = 28;
 
+/** 与 add_zone 已有分区一致:深色半透明 + 浅灰描边 */
+const DEFAULT_ZONE_RANGE_STYLE = {
+  fill: "rgba(0, 0, 0, 0.38)",
+  stroke: "rgba(200, 200, 200, 0.55)",
+};
+
+/** 分区名称标签:黑金胶囊(与 add_zone / MapManage 一致) */
+const ZONE_LABEL_CACHE = {};
+const ZONE_LABEL_CACHE_VER = "v2";
+const ZONE_LABEL_FONT = "13px sans-serif";
+const ZONE_LABEL_RADIUS = 20;
+
+function roundRectPath(ctx, x, y, width, height, radius) {
+  const r = Math.min(radius, width / 2, height / 2);
+  ctx.beginPath();
+  ctx.moveTo(x + r, y);
+  ctx.arcTo(x + width, y, x + width, y + height, r);
+  ctx.arcTo(x + width, y + height, x, y + height, r);
+  ctx.arcTo(x, y + height, x, y, r);
+  ctx.arcTo(x, y, x + width, y, r);
+  ctx.closePath();
+}
+
+/** Icon 只能画在 Point 上;用 extent 中心,兼容 Polygon / MultiPolygon */
+function getZoneLabelPoint(geometry) {
+  if (!geometry) return null;
+  try {
+    if (typeof geometry.getType === "function" && geometry.getType() === "Point") {
+      return geometry;
+    }
+    if (
+      typeof geometry.getInteriorPoint === "function" &&
+      typeof geometry.getType === "function" &&
+      geometry.getType() === "Polygon"
+    ) {
+      return geometry.getInteriorPoint();
+    }
+    const extent = typeof geometry.getExtent === "function" ? geometry.getExtent() : null;
+    if (extent && extent.length >= 4) {
+      return new Point([(extent[0] + extent[2]) / 2, (extent[1] + extent[3]) / 2]);
+    }
+  } catch (e) {
+    console.warn("[growthReportMap] getZoneLabelPoint failed", e);
+  }
+  return null;
+}
+
+function createZoneNameLabelStyle(name) {
+  const text = String(name || "");
+  const cacheKey = `${ZONE_LABEL_CACHE_VER}:${text}`;
+  if (ZONE_LABEL_CACHE[cacheKey]) return ZONE_LABEL_CACHE[cacheKey];
+
+  const padX = 12;
+  const boxH = 28;
+  const measure = document.createElement("canvas").getContext("2d");
+  measure.font = ZONE_LABEL_FONT;
+  const textWidth = Math.ceil(measure.measureText(text).width);
+  const boxW = Math.max(textWidth + padX * 2, boxH);
+  const dpr = window.devicePixelRatio || 2;
+  const canvas = document.createElement("canvas");
+  canvas.width = Math.ceil((boxW + 4) * dpr);
+  canvas.height = Math.ceil((boxH + 4) * dpr);
+  const ctx = canvas.getContext("2d");
+  ctx.scale(dpr, dpr);
+  ctx.imageSmoothingEnabled = true;
+
+  const x = 2;
+  const y = 2;
+  roundRectPath(ctx, x, y, boxW, boxH, ZONE_LABEL_RADIUS);
+  ctx.fillStyle = "#181818";
+  ctx.fill();
+  ctx.lineWidth = 1;
+  ctx.strokeStyle = "rgba(232, 197, 106, 0.35)";
+  ctx.stroke();
+
+  ctx.font = ZONE_LABEL_FONT;
+  ctx.fillStyle = "#E8C56A";
+  ctx.textAlign = "center";
+  ctx.textBaseline = "middle";
+  ctx.fillText(text, x + boxW / 2, y + boxH / 2 - 0.5);
+
+  const style = new Style({
+    geometry: (feature) => getZoneLabelPoint(feature.getGeometry()),
+    zIndex: 2,
+    image: new Icon({
+      src: canvas.toDataURL(),
+      scale: 1 / dpr,
+      anchor: [0.5, 0.5],
+    }),
+  });
+  ZONE_LABEL_CACHE[cacheKey] = style;
+  return style;
+}
+
 /**
  * @description 地图层对象
  */
 class IndexMap {
   constructor() {
-    let that = this;
     let vectorStyle = new KMap.VectorStyle();
     this.vectorStyle = vectorStyle;
     this.noRangeTipOverlay = null;
     /** 底部浮层面板叠在地图上的高度(px),用于可视区中心偏移 */
     this._bottomOverlayHeight = 0;
+    this.wktFormat = new WKT();
 
     // 位置图标
     this.clickPointLayer = new KMap.VectorLayer("clickPointLayer", 9999, {
-      style: (f) => {
+      style: () => {
         return new Style({
           image: new Icon({
             src: require("@/assets/img/home/garden-point.png"),
@@ -56,6 +150,11 @@ class IndexMap {
           }),
         }),
     });
+
+    // 已有种植范围(与 add_zone existingVarietyLayer 同风格)
+    this.zoneRangeLayer = new KMap.VectorLayer("zoneRangeLayer", 9997, {
+      style: (feature) => this.createZoneRangeStyle(feature),
+    });
   }
 
   initMap(location, target) {
@@ -64,11 +163,28 @@ class IndexMap {
     this.kmap = new KMap.Map(target, level, coordinate[0], coordinate[1], null, 8, 22);
     let xyz2 = config.base_img_url3 + "map/lby/{z}/{x}/{y}.png";
     this.kmap.addXYZLayer(xyz2, { minZoom: 8, maxZoom: 22 }, 2);
+    this.kmap.addLayer(this.zoneRangeLayer.layer);
     this.kmap.addLayer(this.noRangeGuideLayer.layer);
     this.kmap.addLayer(this.clickPointLayer.layer);
     // 初始按面板上方可视区定中心,避免被底部面板挡住
     this.setMapPosition(coordinate);
-    // this.addMapSingerClick()
+  }
+
+  createZoneRangeStyle(feature) {
+    const name = String(feature.get("name") || "");
+    const fill = feature.get("fill") || DEFAULT_ZONE_RANGE_STYLE.fill;
+    const stroke = feature.get("stroke") || DEFAULT_ZONE_RANGE_STYLE.stroke;
+    const styles = [
+      new Style({
+        fill: new Fill({ color: fill }),
+        stroke: new Stroke({
+          color: stroke,
+          width: 2,
+        }),
+      }),
+    ];
+    if (name) styles.push(createZoneNameLabelStyle(name));
+    return styles;
   }
 
   /** 底部面板叠在地图上的高度(px),中心点按「面板以上」区域计算 */
@@ -113,11 +229,17 @@ class IndexMap {
     this.centerOnVisibleArea(coord);
   }
 
+  hasZoneRanges() {
+    return (this.zoneRangeLayer?.source?.getFeatures?.() || []).length > 0;
+  }
+
   setMapPoint(coordinate) {
-    this.clickPointLayer.source.clear()
-    let point = new Feature(new Point(coordinate))
-    this.clickPointLayer.addFeature(point)
-    mapLocation.data = coordinate
+    this.clickPointLayer.source.clear();
+    mapLocation.data = coordinate;
+    // 已有种植范围时不显示中心种植点图标
+    if (!this.hasZoneRanges() && coordinate?.length) {
+      this.clickPointLayer.addFeature(new Feature(new Point(coordinate)));
+    }
     // 示意框跟着中心点走
     if (this.noRangeGuideLayer?.source?.getFeatures?.()?.length) {
       this.drawNoRangeSquare(coordinate);
@@ -157,7 +279,7 @@ class IndexMap {
     this.noRangeTipOverlay.setPosition(tipCoord);
   }
 
-  /** 无范围引导:中心示意方框 + 下方提示 Overlay */
+  /** 无范围引导:中心示意方框 + 下方提示 Overlay(不清已有分区范围) */
   showNoRangeGuide(coordinate, tipEl) {
     if (!this.kmap?.map || !coordinate?.length) return;
     this.drawNoRangeSquare(coordinate);
@@ -184,6 +306,56 @@ class IndexMap {
     }
   }
 
+  clearZoneRanges() {
+    const hadRanges = this.hasZoneRanges();
+    this.zoneRangeLayer?.source?.clear?.();
+    // 清掉范围后恢复种植点图标
+    if (hadRanges && mapLocation.data?.length) {
+      this.setMapPoint(mapLocation.data);
+    }
+  }
+
+  /**
+   * 展示已有种植范围 + 黑金名称标签(样式对齐 add_zone)
+   * @param {{ id?: string|number, name: string, polygon: string, fill?: string, stroke?: string }[]} zones
+   * @param {{ fit?: boolean }} options
+   */
+  setZoneRanges(zones = [], options = {}) {
+    if (!this.kmap || !this.zoneRangeLayer?.source) return;
+    this.clearNoRangeGuide();
+    this.clearZoneRanges();
+    const projection = this.kmap.map.getView().getProjection();
+    const list = Array.isArray(zones) ? zones : [];
+    list.forEach((item) => {
+      const wkt = item?.polygon || item?.wkt;
+      if (!wkt) return;
+      try {
+        const geometry = this.wktFormat.readGeometry(String(wkt).trim(), {
+          dataProjection: "EPSG:4326",
+          featureProjection: projection,
+        });
+        const feature = new Feature({ geometry });
+        feature.set("id", item.id);
+        feature.set("name", item.name || "");
+        feature.set("fill", item.fill || DEFAULT_ZONE_RANGE_STYLE.fill);
+        feature.set("stroke", item.stroke || DEFAULT_ZONE_RANGE_STYLE.stroke);
+        this.zoneRangeLayer.source.addFeature(feature);
+      } catch (e) {
+        console.warn("[growthReportMap] zone polygon parse failed", e);
+      }
+    });
+    this.zoneRangeLayer.layer.changed();
+    // 有范围隐藏种植点;无范围则按当前点位恢复图标
+    if (this.hasZoneRanges()) {
+      this.clickPointLayer?.source?.clear?.();
+    } else if (mapLocation.data?.length) {
+      this.setMapPoint(mapLocation.data);
+    }
+    if (options.fit !== false && this.hasZoneRanges()) {
+      this.scheduleFitZoneRanges();
+    }
+  }
+
   /** 当前地图点位(优先标记点,其次视图中心) */
   getCurrentCoordinate() {
     const features = this.clickPointLayer?.source?.getFeatures?.() || [];
@@ -202,18 +374,12 @@ class IndexMap {
   addMapSingerClick() {
     let that = this;
     that.kmap.on("singleclick", (evt) => {
-      // that.kmap.map.forEachFeatureAtPixel(evt.pixel, function (feature, layer) {
-      //   if ( layer instanceof VectorLayer && layer.get("name") === "reportPolygonLayer" ) {
-      //     areaId.data = feature.get("id")
-      //   }
-      // });
       that.setMapPoint(evt.coordinate)
       mapLocation.data = evt.coordinate
     });
   }
 
   clearLayer() {
-    // this.kmap.removeLayer(this.clickPointLayer.layer)
     this.kmap.polygonLayer.source.clear();
   }
 
@@ -261,12 +427,33 @@ class IndexMap {
     });
   }
 
+  fitZoneRanges(options = {}) {
+    const map = this.kmap?.map;
+    if (!map) return;
+    map.updateSize();
+    const extent = this.zoneRangeLayer?.source?.getExtent?.();
+    if (!extent || !isFinite(extent[0])) return;
+    const bottom = Math.max(48, this._bottomOverlayHeight || 0);
+    map.getView().fit(extent, {
+      duration: options.duration ?? 0,
+      padding: options.padding ?? [120, 48, bottom, 48],
+      maxZoom: options.maxZoom ?? 18,
+    });
+  }
+
   scheduleFitView(options = {}) {
     const run = () => this.fitView(options);
     requestAnimationFrame(() => {
       setTimeout(run, 50);
     });
   }
+
+  scheduleFitZoneRanges(options = {}) {
+    const run = () => this.fitZoneRanges(options);
+    requestAnimationFrame(() => {
+      setTimeout(run, 50);
+    });
+  }
 }
 
 export default IndexMap;

+ 57 - 7
src/views/old_mini/growth_report/index.vue

@@ -124,6 +124,13 @@ const growthReportMap = new GrowthReportMap();
 const locationName = ref("");
 /** status≠1 时展示中心勾画引导 */
 const noFarmRange = ref(false);
+/** 与 add_zone 已有分区一致的范围样式 */
+const ZONE_RANGE_STYLE = {
+    fill: "rgba(0, 0, 0, 0.38)",
+    stroke: "rgba(200, 200, 200, 0.55)",
+};
+/** 防止切分区时旧 getZones 回写 */
+let zoneRangeFetchToken = 0;
 const selectedFarmId = ref(localStorage.getItem("selectedFarmId") || "");
 /** 无农场时区县码(逆地理 adcode) */
 const countyCode = ref(localStorage.getItem(COUNTY_CODE_STORAGE_KEY) || "");
@@ -219,12 +226,12 @@ async function fetchFarmRangeStatus() {
     // 无农场不展示勾画引导
     if (farmId == null || farmId === "") {
         noFarmRange.value = false;
-        await syncNoRangeGuide();
+        await syncMapRangeVisual();
         return;
     }
     if (zoneId == null || zoneId === "") {
         noFarmRange.value = true;
-        await syncNoRangeGuide();
+        await syncMapRangeVisual();
         return;
     }
     try {
@@ -237,13 +244,14 @@ async function fetchFarmRangeStatus() {
         console.warn("[growth_report] checkZoneRange failed", e);
         noFarmRange.value = true;
     }
-    await syncNoRangeGuide();
+    await syncMapRangeVisual();
 }
 
-/** 无范围时在地图中心点画示意方框 + 下方提示 */
-async function syncNoRangeGuide() {
+/** 农场下有 polygon 的分区都画;当前分区无范围时再叠中心勾画引导 */
+async function syncMapRangeVisual() {
     await nextTick();
     if (!growthReportMap.kmap) return;
+    await syncZoneRangeOnMap();
     if (!noFarmRange.value) {
         growthReportMap.clearNoRangeGuide();
         return;
@@ -255,6 +263,48 @@ async function syncNoRangeGuide() {
     growthReportMap.showNoRangeGuide(coordinate, noRangeTipRef.value);
 }
 
+/** 拉 zone_images:农场下所有有 polygon 的分区都画出来(样式对齐 add_zone) */
+async function syncZoneRangeOnMap() {
+    const farm = getSelectedFarm();
+    const farmId = selectedFarmId.value || farm.farm_id || farm.id;
+    if (farmId == null || farmId === "") {
+        growthReportMap.clearZoneRanges();
+        return;
+    }
+    const token = ++zoneRangeFetchToken;
+    try {
+        const res = await VE_API.questionnaire.getZones({ farm_id: farmId });
+        if (token !== zoneRangeFetchToken) return;
+        const zones = Array.isArray(res?.data?.zones)
+            ? res.data.zones
+            : Array.isArray(res?.data)
+              ? res.data
+              : [];
+        const list = zones
+            .map((z) => {
+                const polygon = typeof z?.polygon === "string" ? z.polygon.trim() : "";
+                if (!polygon) return null;
+                return {
+                    id: z.zone_id,
+                    name: z.zone_name || "",
+                    fill: ZONE_RANGE_STYLE.fill,
+                    stroke: ZONE_RANGE_STYLE.stroke,
+                    polygon,
+                };
+            })
+            .filter(Boolean);
+        if (!list.length) {
+            growthReportMap.clearZoneRanges();
+            return;
+        }
+        growthReportMap.setZoneRanges(list, { fit: true });
+    } catch (e) {
+        if (token !== zoneRangeFetchToken) return;
+        console.warn("[growth_report] getZones for range failed", e);
+        growthReportMap.clearZoneRanges();
+    }
+}
+
 const goAddZone = (type) => {
     router.push({
         path: "/add_zone",
@@ -588,13 +638,13 @@ const initMap = async () => {
         if (coordinate?.length === 2) {
             growthReportMap.setMapPosition(coordinate);
         }
-        await syncNoRangeGuide();
+        await syncMapRangeVisual();
         return;
     }
     const location = currentMapPoint.value || store.state.home.miniUserLocationPoint || DEFAULT_MAP_POINT;
     currentMapPoint.value = location;
     growthReportMap.initMap(location, mapContainer.value);
-    await syncNoRangeGuide();
+    await syncMapRangeVisual();
 };
 
 function applySelectedLocation() {