darwArea.vue 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916
  1. <template>
  2. <div class="edit-map">
  3. <custom-header @goback="goBack" :isGoBack="true" :name="viewOnly ? '查看区域' : '勾选地块'"></custom-header>
  4. <div class="region-type-tabs">
  5. <div v-for="item in regionTypeTabs" :key="item.code" class="region-type-tab"
  6. :class="{ 'region-type-tab--active': activeRegionType === item.code }"
  7. @click="handleRegionTypeClick(item)">
  8. {{ item.name }}
  9. </div>
  10. </div>
  11. <div class="variety-tabs" v-if="varietyTabs.length > 0 && activeRegionType !== 'DORMANCY'">
  12. <div v-for="(v, index) in varietyTabs" :key="index" class="variety-tab"
  13. :class="{ 'variety-tab--active': activeVariety === index }" @click="handleVarietyClick(v, index)">
  14. {{ v.regionName || v.problemZoneTypeName }}
  15. </div>
  16. </div>
  17. <div class="edit-map-content">
  18. <div class="edit-map-tip" v-if="!viewOnly">操作提示:拖动圆点,即可调整地块边界</div>
  19. <div class="map-container" ref="mapContainer"></div>
  20. <div class="edit-map-footer">
  21. <div v-if="viewOnly" class="footer-back" @click="deletePolygon">
  22. <img class="back-icon" src="@/assets/img/map/delete.png" alt="" />
  23. </div>
  24. <div class="edit-map-footer-btn" :class="{ 'confirm-btn-box': viewOnly }">
  25. <template v-if="!viewOnly">
  26. <div class="btn-reset" @click="resetPolygon">重置区域</div>
  27. <div class="btn-confirm" @click="openConfirmDrawTypePopup">确认区域</div>
  28. </template>
  29. <div v-else class="btn-confirm" @click="handleEditRegion">编辑区域</div>
  30. </div>
  31. </div>
  32. </div>
  33. <tip-popup v-model:show="showTipPopup" type="success" text="您的农情报告已生成" text2="请查看" buttonText="点击查看"
  34. @confirm="handleTipConfirm" />
  35. <confirm-draw-type-popup ref="confirmDrawTypePopupRef" @confirm="handleConfirmDrawType" />
  36. </div>
  37. </template>
  38. <script setup>
  39. import customHeader from "@/components/customHeader.vue";
  40. import { ref, computed, watch, onActivated, onDeactivated, nextTick } from "vue";
  41. import DrawRegionMap from "../../interactionList/map/drawRegionMap.js";
  42. import { Map as KMapMap } from "@/utils/ol-map/KMap";
  43. import { useRouter, useRoute } from "vue-router";
  44. import { convertPointToArray } from "@/utils/index";
  45. import { ElMessage, ElMessageBox } from "element-plus";
  46. import TipPopup from "@/components/popup/tipPopup.vue";
  47. import ConfirmDrawTypePopup from "@/components/popup/confirmDrawTypePopup.vue";
  48. import Style from "ol/style/Style";
  49. import { Fill, Stroke, Circle, Text } from "ol/style.js";
  50. import { Point, Polygon, MultiPolygon } from "ol/geom";
  51. import WKT from "ol/format/WKT.js";
  52. import { unByKey } from "ol/Observable.js";
  53. import * as proj from "ol/proj";
  54. import { getArea } from "ol/sphere.js";
  55. const router = useRouter();
  56. const route = useRoute();
  57. const mapContainer = ref(null);
  58. const drawRegionMap = new DrawRegionMap();
  59. /** OpenLayers 地图在容器尺寸变化后不会自动重算 canvas,需手动 updateSize */
  60. const resizeMapToContainer = () => {
  61. nextTick(() => {
  62. requestAnimationFrame(() => {
  63. drawRegionMap.kmap?.map?.updateSize?.();
  64. });
  65. });
  66. };
  67. // handleVarietyClick 内部有延迟渲染(setTimeout),切换查看/编辑或重建地图时必须取消,避免旧回调在新实例上再次 addFeature 造成叠加
  68. const pendingGeomRenderTimer = ref(null);
  69. const clearPendingGeomRenderTimer = () => {
  70. if (pendingGeomRenderTimer.value) {
  71. clearTimeout(pendingGeomRenderTimer.value);
  72. pendingGeomRenderTimer.value = null;
  73. }
  74. };
  75. const confirmDrawTypePopupRef = ref(null);
  76. const selectedDrawTypeMeta = ref({
  77. type: "",
  78. category: "",
  79. remark: "",
  80. });
  81. // 每个品种(tab)对应的地块数据草稿:key 为 tab index,value 为 { geomArr, geom }(与当前大类 Tab 一致时同步)
  82. const regionsDraftByIndex = ref({});
  83. /** 按弹窗确认的「大类 + 小类」存几何与备注,避免与地图当前选中 Tab 不一致 */
  84. const regionsDraftByKey = ref({});
  85. const submitting = ref(false);
  86. // 仅在首次进入页面时根据路由 varietyId 定位一次,避免后续刷新覆盖当前流程进度
  87. const hasAppliedInitialVariety = ref(false);
  88. const selectedDeleteFeature = ref(null);
  89. const deleteSelectClickKey = ref(null);
  90. const selectedDeleteFeatureUid = ref("");
  91. const selectedDeleteFeatureOriginalStyle = ref(null);
  92. const type = ref(null);
  93. const varietyTabs = ref([]);
  94. const activeVariety = ref(0);
  95. const regionGeom = ref(null);
  96. /** 切换「大类」Tab 时子类列表完全替换,regionsDraftByIndex 按下标缓存会与新区块列表错位;保存成功后也应以接口为准 */
  97. const clearDraftIndexOnly = () => {
  98. regionsDraftByIndex.value = {};
  99. };
  100. const clearAllRegionDrafts = () => {
  101. regionsDraftByKey.value = {};
  102. regionsDraftByIndex.value = {};
  103. };
  104. const clearDeleteSelectionState = () => {
  105. if (selectedDeleteFeature.value) {
  106. selectedDeleteFeature.value.setStyle(selectedDeleteFeatureOriginalStyle.value ?? undefined);
  107. selectedDeleteFeature.value = null;
  108. }
  109. selectedDeleteFeatureUid.value = "";
  110. selectedDeleteFeatureOriginalStyle.value = null;
  111. if (deleteSelectClickKey.value) {
  112. unByKey(deleteSelectClickKey.value);
  113. deleteSelectClickKey.value = null;
  114. }
  115. };
  116. const getDeleteHighlightStyle = () => {
  117. const styleKind = getCanonicalRegionTypeForStyles();
  118. if (styleKind === "variety") {
  119. return {
  120. fillColor: "rgba(24, 170, 139, 0.5)",
  121. strokeColor: "#18AA8B",
  122. };
  123. }
  124. if (styleKind === "ABNORMAL") {
  125. if (activeVariety.value < 2) {
  126. return {
  127. fillColor: "rgba(224, 49, 49, 0.5)",
  128. strokeColor: "#E03131",
  129. }
  130. } else {
  131. return {
  132. fillColor: "rgba(255, 115, 0, 0.5)",
  133. strokeColor: "#FF7300",
  134. };
  135. }
  136. }
  137. if (styleKind === "ENVIRONMENT") {
  138. return {
  139. fillColor: "rgba(255, 199, 102, 0.5)",
  140. strokeColor: "#FDCF7F",
  141. };
  142. }
  143. // 其余类型先给默认占位色,后续可按产品视觉再调整
  144. return {
  145. fillColor: "rgba(229, 229, 229, 0.5)",
  146. strokeColor: "#A6A6A6",
  147. };
  148. };
  149. const highlightDeleteSelectedFeature = (feature) => {
  150. if (!feature) return;
  151. if (selectedDeleteFeature.value === feature) return;
  152. if (selectedDeleteFeature.value && selectedDeleteFeature.value !== feature) {
  153. selectedDeleteFeature.value.setStyle(selectedDeleteFeatureOriginalStyle.value ?? undefined);
  154. }
  155. selectedDeleteFeatureOriginalStyle.value = feature.getStyle ? feature.getStyle() : null;
  156. selectedDeleteFeature.value = feature;
  157. selectedDeleteFeatureUid.value = String(feature?.ol_uid || feature?.getId?.() || "");
  158. const { fillColor, strokeColor } = getDeleteHighlightStyle();
  159. // 删除选择态:按当前类型动态高亮(单选)
  160. feature.setStyle(
  161. new Style({
  162. fill: new Fill({ color: fillColor }),
  163. stroke: new Stroke({ color: strokeColor, width: 2 }),
  164. })
  165. );
  166. };
  167. const isFeatureLockedForDelete = (feature) => {
  168. if (activeRegionType.value === "variety") return false;
  169. const growth = getAbnormalGrowthOverlayMeta(feature);
  170. const status = String(growth?.handleStatus || "");
  171. return status === "2" || status === "3";
  172. };
  173. const enableDeleteSelectionMode = () => {
  174. const map = drawRegionMap.kmap?.map;
  175. const polygonLayer = drawRegionMap.kmap?.polygonLayer?.layer;
  176. if (!map || !polygonLayer || deleteSelectClickKey.value) return;
  177. deleteSelectClickKey.value = map.on("singleclick", (evt) => {
  178. let hitFeature = null;
  179. map.forEachFeatureAtPixel(
  180. evt.pixel,
  181. (feature) => {
  182. hitFeature = feature;
  183. return true;
  184. },
  185. {
  186. layerFilter: (layer) => layer === polygonLayer,
  187. }
  188. );
  189. if (hitFeature) {
  190. if (isFeatureLockedForDelete(hitFeature)) {
  191. ElMessage.warning("该地块不可删除");
  192. return;
  193. }
  194. highlightDeleteSelectedFeature(hitFeature);
  195. }
  196. });
  197. };
  198. const handleRegionTypeClick = (item) => {
  199. clearDeleteSelectionState();
  200. const prevMajor = activeRegionType.value;
  201. if (item.code !== prevMajor) {
  202. clearDraftIndexOnly();
  203. }
  204. activeRegionType.value = item.code;
  205. activeVariety.value = 0;
  206. if (item.code === "variety") {
  207. varietyTabs.value = regionInfo.value.regionList || [];
  208. } else {
  209. varietyTabs.value = item.children;
  210. }
  211. handleVarietyClick(varietyTabs.value[activeVariety.value], activeVariety.value);
  212. if (drawRegionMap.kmap) {
  213. applyRegionStyles();
  214. }
  215. };
  216. // 删除当前地块
  217. const deletePolygon = () => {
  218. const features = drawRegionMap.kmap?.polygonLayer?.source?.getFeatures?.() || [];
  219. const deletableFeatures = features.filter((f) => !isFeatureLockedForDelete(f));
  220. let matchedFeature = null;
  221. if (features.length === 0) {
  222. clearDeleteSelectionState();
  223. ElMessage.warning("当前没有可删除的地块");
  224. return;
  225. }
  226. if (features.length === 1 && deletableFeatures.length === 0) {
  227. clearDeleteSelectionState();
  228. ElMessage.warning("当前地块不可删除");
  229. return;
  230. }
  231. if (features.length > 1) {
  232. if (deletableFeatures.length === 0) {
  233. clearDeleteSelectionState();
  234. ElMessage.warning("当前地块不可删除");
  235. return;
  236. }
  237. if (!selectedDeleteFeature.value) {
  238. enableDeleteSelectionMode();
  239. ElMessage.warning("当前有多个地块,请先选择地块");
  240. return;
  241. }
  242. matchedFeature = features.find((f) => {
  243. if (f === selectedDeleteFeature.value) return true;
  244. const uid = String(f?.ol_uid || f?.getId?.() || "");
  245. return uid && uid === selectedDeleteFeatureUid.value;
  246. });
  247. if (!matchedFeature) {
  248. selectedDeleteFeature.value = null;
  249. selectedDeleteFeatureUid.value = "";
  250. ElMessage.warning("请选择地块后再删除");
  251. return;
  252. }
  253. if (isFeatureLockedForDelete(matchedFeature)) {
  254. clearDeleteSelectionState();
  255. ElMessage.warning("该地块不可删除");
  256. return;
  257. }
  258. } else {
  259. clearDeleteSelectionState();
  260. }
  261. ElMessageBox.confirm(
  262. "确认删除当前地块吗?删除后可以重新勾画。",
  263. "删除确认",
  264. {
  265. confirmButtonText: "确认删除",
  266. cancelButtonText: "取消",
  267. type: "warning",
  268. }
  269. ).then(async () => {
  270. if (selectedDeleteFeature.value && features.length > 1) {
  271. drawRegionMap.kmap?.polygonLayer?.source?.removeFeature?.(matchedFeature || selectedDeleteFeature.value);
  272. clearDeleteSelectionState();
  273. } else {
  274. drawRegionMap.deleteCurrentPolygon();
  275. }
  276. const polygonData = drawRegionMap.getAreaGeometry?.();
  277. const geometryArr = polygonData?.geometryArr || [];
  278. try {
  279. const ok = await submitCurrentTabGeometryChange(geometryArr);
  280. if (!ok) {
  281. ElMessage.error("删除后保存失败");
  282. return;
  283. }
  284. await fetchRegionInfo();
  285. clearAllRegionDrafts();
  286. if (activeRegionType.value === "variety") {
  287. varietyTabs.value = regionInfo.value?.regionList || [];
  288. } else {
  289. const group = (regionTypeTabs.value || []).find(
  290. (x) => String(x?.code) === String(activeRegionType.value)
  291. );
  292. varietyTabs.value = group?.children || [];
  293. }
  294. const nextIndex = Math.min(activeVariety.value, Math.max(varietyTabs.value.length - 1, 0));
  295. activeVariety.value = nextIndex;
  296. if (varietyTabs.value.length > 0 && varietyTabs.value[nextIndex]) {
  297. handleVarietyClick(varietyTabs.value[nextIndex], nextIndex);
  298. } else {
  299. drawRegionMap.kmap?.polygonLayer?.source?.clear?.();
  300. drawRegionMap.fitAllRegions?.();
  301. }
  302. ElMessage.success("地块已删除");
  303. } catch (_) {
  304. ElMessage.error("删除后保存失败");
  305. }
  306. });
  307. };
  308. /** 取 Polygon / MultiPolygon 的外环坐标(地图投影),用于顶点样式 */
  309. const getOuterRingCoordinates = (geometry) => {
  310. if (!geometry || typeof geometry.getType !== "function") return [];
  311. const type = geometry.getType();
  312. const c = geometry.getCoordinates();
  313. if (!c || !c.length) return [];
  314. if (type === "Polygon") return c[0] || [];
  315. if (type === "MultiPolygon") return c[0]?.[0] || [];
  316. return [];
  317. };
  318. const createPolygonStyleFunc = (fillColor, strokeColor) => {
  319. return (feature) => {
  320. const growth = getAbnormalGrowthOverlayMeta(feature);
  321. const isTreatingDisease =
  322. String(growth?.handleStatus || "") === "2" && !String(growth?.badgeText || "").includes("长势");
  323. const isTreatingGrowth =
  324. String(growth?.handleStatus || "") === "2" && String(growth?.badgeText || "").includes("长势");
  325. const isControlledDisease = String(growth?.handleStatus || "") === "3";
  326. const currentFillColor = isControlledDisease
  327. ? SLEEP_ZONE_FILL_COLOR
  328. : isTreatingGrowth
  329. ? "rgba(255, 159, 102, 0.3)"
  330. : isTreatingDisease
  331. ? DISEASE_TREATING_FILL_COLOR
  332. : fillColor;
  333. const currentStrokeColor = isControlledDisease
  334. ? SLEEP_ZONE_STROKE_COLOR
  335. : isTreatingGrowth
  336. ? "rgba(255, 94, 0, 0.3)"
  337. : isTreatingDisease
  338. ? DISEASE_TREATING_STROKE_COLOR
  339. : strokeColor;
  340. const styles = [];
  341. const ring = getOuterRingCoordinates(feature.getGeometry());
  342. const ringLen = ring.length;
  343. const vertexCount = ringLen > 1 ? ringLen - 1 : ringLen;
  344. for (let i = 0; i < vertexCount; i++) {
  345. if (i % 2) {
  346. styles.push(
  347. new Style({
  348. geometry: new Point(ring[i]),
  349. image: new Circle({
  350. radius: 4,
  351. fill: new Fill({
  352. color: currentStrokeColor,
  353. }),
  354. stroke: new Stroke({
  355. color: "#fff",
  356. width: 1,
  357. }),
  358. }),
  359. })
  360. );
  361. } else {
  362. styles.push(
  363. new Style({
  364. geometry: new Point(ring[i]),
  365. image: new Circle({
  366. radius: 6,
  367. fill: new Fill({
  368. color: "#fff",
  369. }),
  370. }),
  371. })
  372. );
  373. }
  374. }
  375. const fillStyle = new Style({
  376. fill: new Fill({
  377. color: currentFillColor,
  378. }),
  379. stroke: new Stroke({
  380. color: currentStrokeColor,
  381. width: 2,
  382. }),
  383. });
  384. let geom = feature.getGeometry().clone();
  385. geom.transform(proj.get("EPSG:4326"), proj.get("EPSG:38572"));
  386. let area = getArea(geom);
  387. area = (area + area / 2) / 1000;
  388. if (growth) {
  389. styles.push(
  390. new Style({
  391. text: new Text({
  392. text: growth.badgeText,
  393. font: "bold 13px sans-serif",
  394. fill: new Fill({ color: growth.badgeTextColor || "#ffffff" }),
  395. backgroundFill: new Fill({ color: growth.badgeBackground || ABNORMAL_BADGE_BG_GROWTH }),
  396. backgroundStroke: growth.badgeBorderColor
  397. ? new Stroke({ color: growth.badgeBorderColor, width: 1 })
  398. : undefined,
  399. padding: [4, 10, 4, 10],
  400. offsetY: -40,
  401. }),
  402. }),
  403. new Style({
  404. text: new Text({
  405. text: `发现时间:${growth.discoveryDate}`,
  406. font: "12px sans-serif",
  407. fill: new Fill({ color: "#ffffff" }),
  408. offsetY: -16,
  409. }),
  410. })
  411. );
  412. }
  413. const areaValStyle = new Style({
  414. text: new Text({
  415. font: "16px sans-serif",
  416. text: area.toFixed(2) + "亩",
  417. fill: new Fill({ color: "#fff" }),
  418. offsetY: growth ? 14 : 0,
  419. }),
  420. });
  421. styles.push(fillStyle, areaValStyle);
  422. return styles;
  423. };
  424. };
  425. const applyRegionStyles = () => {
  426. const kmap = drawRegionMap.kmap;
  427. if (!kmap) return;
  428. let lineColor = "#2199F8";
  429. let vertexColor = "#2199F8";
  430. let fillColor = [0, 0, 0, 0.5];
  431. let strokeColor = "#2199F8";
  432. const styleKind = getCanonicalRegionTypeForStyles();
  433. if (styleKind === "variety") {
  434. lineColor = "#18AA8B";
  435. vertexColor = "#18AA8B";
  436. fillColor = [0, 57, 44, 0.5];
  437. strokeColor = "#18AA8B";
  438. } else if (styleKind === "ABNORMAL") {
  439. if (activeVariety.value < 2) {
  440. lineColor = "#E03131";
  441. vertexColor = "#E03131";
  442. fillColor = [100, 0, 0, 0.5];
  443. strokeColor = "#E03131";
  444. } else {
  445. lineColor = "#FF7300";
  446. vertexColor = "#FF7300";
  447. fillColor = [124, 46, 0, 0.5];
  448. strokeColor = "#FF7300";
  449. }
  450. } else if (styleKind === "ENVIRONMENT") {
  451. lineColor = "#FDCF7F";
  452. vertexColor = "#FDCF7F";
  453. fillColor = [151, 96, 0, 0.5];
  454. strokeColor = "#FDCF7F";
  455. } else {
  456. lineColor = "#A6A6A6";
  457. vertexColor = "#A6A6A6";
  458. fillColor = [166, 166, 166, 0.25];
  459. strokeColor = "#A6A6A6";
  460. }
  461. // 勾画进行中:通过 Map.drawStyleColors 影响底层 drawStyleFunc 颜色
  462. KMapMap.drawStyleColors = {
  463. line: lineColor,
  464. vertex: vertexColor,
  465. // 只读回显时也复用当前大类颜色(避免查看态全部变绿)
  466. fill: fillColor,
  467. stroke: strokeColor,
  468. };
  469. kmap.polygonStyle = createPolygonStyleFunc(fillColor, strokeColor);
  470. if (kmap.polygonLayer?.layer && typeof kmap.polygonLayer.layer.setStyle === "function") {
  471. kmap.polygonLayer.layer.setStyle(kmap.polygonStyle);
  472. }
  473. };
  474. const isValidGeom = (geom) => {
  475. if (typeof geom !== "string") return false;
  476. const normalized = geom.trim();
  477. if (!normalized) return false;
  478. if (["[]", "{}", "null", "undefined", '""'].includes(normalized)) return false;
  479. return true;
  480. };
  481. /** 与 drawRegionMap / setAreaGeometry 一致:WKT 按 WGS84 解析 */
  482. const WGS84_WKT_OPTS = Object.freeze({
  483. dataProjection: "EPSG:4326",
  484. featureProjection: "EPSG:4326",
  485. });
  486. const wktGeomFormat = new WKT();
  487. /** Polygon / MultiPolygon 各自对应一组环坐标(MultiPolygon 为多块) */
  488. const polygonCoordSetsFromGeometry = (geometry) => {
  489. if (!geometry || typeof geometry.getType !== "function") return [];
  490. const type = geometry.getType();
  491. if (type === "Polygon") return [geometry.getCoordinates()];
  492. if (type === "MultiPolygon") return geometry.getCoordinates();
  493. return [];
  494. };
  495. const mergePolygonWktsForApi = (wktArr) => {
  496. if (!Array.isArray(wktArr) || wktArr.length === 0) return "";
  497. const trimmed = wktArr.map((x) => String(x).trim()).filter(isValidGeom);
  498. if (trimmed.length === 0) return "";
  499. if (trimmed.length === 1) return trimmed[0];
  500. const coordSets = [];
  501. for (const w of trimmed) {
  502. try {
  503. const g = wktGeomFormat.readGeometry(w, WGS84_WKT_OPTS);
  504. coordSets.push(...polygonCoordSetsFromGeometry(g));
  505. } catch (_) {
  506. /* 单条解析失败则跳过 */
  507. }
  508. }
  509. if (coordSets.length === 0) return trimmed[0];
  510. if (coordSets.length === 1) {
  511. try {
  512. return wktGeomFormat.writeGeometry(new Polygon(coordSets[0]), WGS84_WKT_OPTS);
  513. } catch (_) {
  514. return trimmed[0];
  515. }
  516. }
  517. return wktGeomFormat.writeGeometry(new MultiPolygon(coordSets), WGS84_WKT_OPTS);
  518. };
  519. const flattenWktToPolygonWktArray = (wkt) => {
  520. if (!isValidGeom(wkt)) return [];
  521. const s = String(wkt).trim();
  522. try {
  523. const g = wktGeomFormat.readGeometry(s, WGS84_WKT_OPTS);
  524. const sets = polygonCoordSetsFromGeometry(g);
  525. if (sets.length === 0) return [s];
  526. return sets.map((rings) => wktGeomFormat.writeGeometry(new Polygon(rings), WGS84_WKT_OPTS));
  527. } catch (_) {
  528. return [s];
  529. }
  530. };
  531. const flattenGeomWktList = (arr) => {
  532. if (!Array.isArray(arr)) return [];
  533. const out = [];
  534. for (const item of arr) {
  535. if (!isValidGeom(item)) continue;
  536. out.push(...flattenWktToPolygonWktArray(String(item).trim()));
  537. }
  538. return out;
  539. };
  540. /** 地图回显:展开 MULTIPOLYGON 为多个 POLYGON WKT,并去掉无效项 */
  541. const flattenGeomWktListForMap = (arr) => flattenGeomWktList(arr).filter(isValidGeom);
  542. const formatAreaTextFromGeomArr = (geomWktArr) => {
  543. if (!Array.isArray(geomWktArr) || geomWktArr.length === 0) return "";
  544. let totalArea = 0;
  545. for (const wkt of geomWktArr) {
  546. if (!isValidGeom(wkt)) continue;
  547. try {
  548. const geometry = wktGeomFormat.readGeometry(String(wkt).trim(), WGS84_WKT_OPTS);
  549. geometry.transform(proj.get("EPSG:4326"), proj.get("EPSG:38572"));
  550. let area = getArea(geometry);
  551. area = (area + area / 2) / 1000;
  552. totalArea += Number(area) || 0;
  553. } catch (_) {
  554. /* 单条解析失败则跳过 */
  555. }
  556. }
  557. return totalArea > 0 ? `${totalArea.toFixed(2)}亩` : "";
  558. };
  559. // 从 tab.geomItems[{geomWkt}] 中提取 WKT 数组(兼容单块/多块)
  560. const getGeomArrFromGeomItems = (tab) => {
  561. const items = tab?.geomItems;
  562. if (!Array.isArray(items) || items.length === 0) return [];
  563. return items
  564. .map((x) => x?.geomWkt)
  565. .filter((x) => x !== undefined && x !== null)
  566. .map((x) => String(x).trim())
  567. .filter((x) => isValidGeom(x));
  568. };
  569. const isDiseaseAbnormalTab = (tab) => {
  570. const name = (tab?.problemZoneTypeName || tab?.regionName || "").toString();
  571. return name.includes("病害") || name.includes("虫害");
  572. };
  573. const isGrowthAbnormalTab = (tab) => {
  574. const name = (tab?.problemZoneTypeName || tab?.regionName || "").toString();
  575. return name.includes("过慢") || name.includes("过快");
  576. };
  577. const hasLockedStatusItems = (tab) => {
  578. const items = Array.isArray(tab?.geomItems) ? tab.geomItems : [];
  579. return items.some((item) => {
  580. const status = String(item?.handleStatus ?? "");
  581. return status === "2" || status === "3";
  582. });
  583. };
  584. const isLockedAbnormalTab = (tab) =>
  585. isDiseaseAbnormalTab(tab) || isGrowthAbnormalTab(tab) || hasLockedStatusItems(tab);
  586. const isLockedAbnormalItem = (tab, item) => {
  587. const status = String(item?.handleStatus ?? "");
  588. if (!isLockedAbnormalTab(tab)) return false;
  589. return status === "2" || status === "3";
  590. };
  591. const formatDateToYmdDot = (raw) => {
  592. const sourceDate = raw ? new Date(raw) : new Date();
  593. const resolvedDate = Number.isNaN(sourceDate.getTime()) ? new Date() : sourceDate;
  594. const y = resolvedDate.getFullYear();
  595. const m = String(resolvedDate.getMonth() + 1).padStart(2, "0");
  596. const d = String(resolvedDate.getDate()).padStart(2, "0");
  597. return `${y}.${m}.${d}`;
  598. };
  599. const formatDateToYmdDash = (raw) => {
  600. const sourceDate = raw ? new Date(raw) : new Date();
  601. const resolvedDate = Number.isNaN(sourceDate.getTime()) ? new Date() : sourceDate;
  602. const y = resolvedDate.getFullYear();
  603. const m = String(resolvedDate.getMonth() + 1).padStart(2, "0");
  604. const d = String(resolvedDate.getDate()).padStart(2, "0");
  605. return `${y}-${m}-${d}`;
  606. };
  607. const getLockedDiseaseRegions = (tab) => {
  608. if (!isLockedAbnormalTab(tab)) return [];
  609. const items = Array.isArray(tab?.geomItems) ? tab.geomItems : [];
  610. const out = [];
  611. items.forEach((item) => {
  612. if (!isLockedAbnormalItem(tab, item)) return;
  613. const status = String(item?.handleStatus ?? "");
  614. const polygons = flattenWktToPolygonWktArray(item?.geomWkt).filter(isValidGeom);
  615. polygons.forEach((geometry) => {
  616. const name = (tab?.problemZoneTypeName || tab?.regionName || "").toString();
  617. const isGrowth = name.includes("过慢") || name.includes("过快");
  618. const prefix = name.includes("虫害")
  619. ? "虫害"
  620. : name.includes("病害")
  621. ? "病害"
  622. : name.includes("过快")
  623. ? "长势过快"
  624. : "长势过慢";
  625. out.push({
  626. geometry,
  627. displayMode: "lockedDisease",
  628. handleStatus: status,
  629. lockStyleType: isGrowth ? "growthTreating" : status === "3" ? "controlled" : "diseaseTreating",
  630. label: status === "3" ? `${prefix}已控制` : `${prefix}治疗中`,
  631. updatedTime: formatDateToYmdDot(item?.createTime),
  632. });
  633. });
  634. });
  635. return out;
  636. };
  637. const getEditableGeomArrForCurrentTab = (tab, rawGeomArr) => {
  638. if (
  639. !tab ||
  640. !isLockedAbnormalTab(tab) ||
  641. viewOnly.value ||
  642. activeRegionType.value === "variety"
  643. ) {
  644. return flattenGeomWktListForMap(rawGeomArr);
  645. }
  646. const key = draftKeyFromParts(activeRegionType.value, tab);
  647. const draft = key ? regionsDraftByKey.value[key] : null;
  648. const draftItems = Array.isArray(draft?.geomItems) ? draft.geomItems : [];
  649. const items = draftItems.length > 0 ? draftItems : Array.isArray(tab?.geomItems) ? tab.geomItems : [];
  650. const editable = [];
  651. items.forEach((item) => {
  652. if (isLockedAbnormalItem(tab, item)) return;
  653. editable.push(...flattenWktToPolygonWktArray(item?.geomWkt));
  654. });
  655. const editableGeomArr = flattenGeomWktListForMap(editable);
  656. if (editableGeomArr.length > 0) return editableGeomArr;
  657. // 当前小类存在 2/3 锁定地块时,编辑图层保持空,避免把锁定地块误加到可编辑层
  658. const hasLockedItems = items.some((item) => isLockedAbnormalItem(tab, item));
  659. if (hasLockedItems) return [];
  660. // 仅当无锁定地块且没有 geomItems 时,兜底使用纯几何草稿(例如新勾画未落库)
  661. const draftGeom = getDraftGeomForTab(activeRegionType.value, tab, activeVariety.value);
  662. if (isValidGeom(draftGeom)) {
  663. return flattenGeomWktListForMap([String(draftGeom).trim()]);
  664. }
  665. return editableGeomArr;
  666. };
  667. // 兜底防线:若锁定地块意外进入可编辑图层,按 handleStatus(2/3) 强制移除,避免只读层与可编辑层叠加
  668. const purgeLockedFeaturesFromEditableLayer = (tab) => {
  669. if (!isLockedAbnormalTab(tab)) return;
  670. const source = drawRegionMap.kmap?.polygonLayer?.source;
  671. if (!source) return;
  672. const features = source.getFeatures?.() || [];
  673. features.forEach((feature) => {
  674. const geomItem = getGeomItemByFeature(tab, feature);
  675. const status = String(geomItem?.handleStatus ?? "");
  676. if (status === "2" || status === "3") {
  677. source.removeFeature?.(feature);
  678. }
  679. });
  680. };
  681. /** 非品种区提交:按当前地块顺序生成 geomItems(已有项更新,新项追加) */
  682. const buildGeomItemsFromGeometryArr = (tab, geometryArr, remarkOverride) => {
  683. const geomArr = flattenGeomWktListForMap(geometryArr || []);
  684. const existingItems = Array.isArray(tab?.geomItems) ? tab.geomItems : [];
  685. const nowDate = new Date();
  686. const y = nowDate.getFullYear();
  687. const m = String(nowDate.getMonth() + 1).padStart(2, "0");
  688. const d = String(nowDate.getDate()).padStart(2, "0");
  689. const defaultCreateTime = `${y}-${m}-${d}`;
  690. return geomArr.map((geomWkt, idx) => {
  691. const base = existingItems[idx] && typeof existingItems[idx] === "object" ? existingItems[idx] : {};
  692. const baseRemark = base?.remark != null ? String(base.remark) : "";
  693. const finalRemark = remarkOverride != null ? String(remarkOverride) : baseRemark;
  694. const createTime =
  695. base?.createTime != null && String(base.createTime).trim() !== ""
  696. ? String(base.createTime)
  697. : defaultCreateTime;
  698. const handleStatus =
  699. base?.handleStatus != null && String(base.handleStatus).trim() !== ""
  700. ? base.handleStatus
  701. : 1;
  702. return {
  703. ...base,
  704. geomWkt,
  705. remark: finalRemark,
  706. createTime,
  707. handleStatus,
  708. };
  709. });
  710. };
  711. /** 病害编辑态提交:2/3 保持只读原样,1 与新勾画项按当前可编辑地块更新/追加 */
  712. const buildDiseaseGeomItemsForSubmit = (tab, editableGeometryArr, remarkOverride) => {
  713. const items = Array.isArray(tab?.geomItems) ? tab.geomItems : [];
  714. const lockedItems = items
  715. .filter((item) => {
  716. const status = String(item?.handleStatus ?? "");
  717. return status === "2" || status === "3";
  718. })
  719. .map((item) => ({
  720. ...item,
  721. geomWkt: isValidGeom(item?.geomWkt) ? String(item.geomWkt).trim() : "",
  722. remark: item?.remark != null ? String(item.remark) : "",
  723. }))
  724. .filter((item) => isValidGeom(item.geomWkt));
  725. const editableBaseItems = items.filter((item) => {
  726. const status = String(item?.handleStatus ?? "");
  727. return status === "1" || status === "";
  728. });
  729. const geomArr = flattenGeomWktListForMap(editableGeometryArr || []);
  730. const editableItems = geomArr.map((geomWkt, idx) => {
  731. const base =
  732. editableBaseItems[idx] && typeof editableBaseItems[idx] === "object"
  733. ? editableBaseItems[idx]
  734. : {};
  735. const baseRemark = base?.remark != null ? String(base.remark) : "";
  736. const finalRemark = remarkOverride != null ? String(remarkOverride) : baseRemark;
  737. const createTime =
  738. base?.createTime != null && String(base.createTime).trim() !== ""
  739. ? String(base.createTime)
  740. : formatDateToYmdDot();
  741. const handleStatus =
  742. base?.handleStatus != null && String(base.handleStatus).trim() !== ""
  743. ? String(base.handleStatus)
  744. : 1;
  745. return {
  746. ...base,
  747. geomWkt,
  748. remark: finalRemark,
  749. createTime: formatDateToYmdDash(createTime),
  750. handleStatus,
  751. };
  752. });
  753. return [...lockedItems, ...editableItems];
  754. };
  755. const draftKeyFromParts = (majorType, tabLike) => {
  756. if (!majorType || !tabLike || typeof tabLike !== "object") return "";
  757. const t = tabLike;
  758. const id = t.regionId ?? t.problemZoneTypeId ?? t.typeId ?? t.id;
  759. if (id != null && String(id).trim() !== "") {
  760. return `${majorType}:${String(id).trim()}`;
  761. }
  762. const nm = (t.regionName || t.problemZoneTypeName || "").toString().trim();
  763. return nm ? `${majorType}:name:${nm}` : "";
  764. };
  765. const getDraftGeomForTab = (majorType, tab, index) => {
  766. const k = draftKeyFromParts(majorType, tab);
  767. const byKey = k ? regionsDraftByKey.value[k] : null;
  768. if (byKey?.geom) return byKey.geom;
  769. return regionsDraftByIndex.value[index]?.geom;
  770. };
  771. const resolveInitialVarietyIndex = (regionList) => {
  772. const queryVarietyId = route.query?.varietyId;
  773. if (!queryVarietyId || !Array.isArray(regionList) || regionList.length === 0) return 0;
  774. const queryId = String(queryVarietyId).trim();
  775. const matchedIndex = regionList.findIndex((item) => {
  776. const candidateIds = [item?.typeId, item?.varietyId, item?.id]
  777. .filter((v) => v !== undefined && v !== null)
  778. .map((v) => String(v).trim());
  779. return candidateIds.includes(queryId);
  780. });
  781. return matchedIndex >= 0 ? matchedIndex : 0;
  782. };
  783. const getReadonlyVarietyRegions = (activeIndex) => {
  784. if (!Array.isArray(varietyTabs.value) || varietyTabs.value.length === 0) return [];
  785. const readonlyRegions = [];
  786. for (let i = 0; i < varietyTabs.value.length; i++) {
  787. if (i === activeIndex) continue;
  788. const tab = varietyTabs.value[i];
  789. if (!tab) continue;
  790. const draftGeom = getDraftGeomForTab(activeRegionType.value, tab, i);
  791. const geometry = draftGeom || tab.geom;
  792. if (!isValidGeom(geometry)) continue;
  793. readonlyRegions.push({
  794. geometry,
  795. label: tab.regionName || "",
  796. displayMode: "readonlyVariety",
  797. });
  798. }
  799. return readonlyRegions;
  800. };
  801. const getAllVarietyReadonlyRegions = () => {
  802. const list = regionInfo.value?.regionList || [];
  803. if (!Array.isArray(list) || list.length === 0) return [];
  804. const regions = [];
  805. for (let i = 0; i < list.length; i++) {
  806. const tab = list[i];
  807. if (!tab) continue;
  808. const draftGeom = getDraftGeomForTab("variety", tab, i);
  809. const geometry = draftGeom || tab.geom;
  810. if (!isValidGeom(geometry)) continue;
  811. regions.push({
  812. geometry,
  813. label: tab.regionName || "",
  814. displayMode: "readonlyVariety",
  815. });
  816. }
  817. return regions;
  818. };
  819. const renderReadonlyVarietyRegions = (activeIndex) => {
  820. if (drawRegionMap && typeof drawRegionMap.setStatusRegions === "function") {
  821. drawRegionMap.setStatusRegions(getReadonlyVarietyRegions(activeIndex));
  822. }
  823. };
  824. /**
  825. * 仅渲染「品种区」所有已有地块(只读),用于在其它问题区查看/编辑时作为底图参考。
  826. * 需求:只显示品种区地块,其它问题区地块不显示,且不可编辑。
  827. */
  828. const renderAllVarietyRegionsReadonlyOnly = () => {
  829. if (!drawRegionMap || typeof drawRegionMap.setStatusRegions !== "function") return;
  830. const regions = getAllVarietyReadonlyRegions();
  831. if (regions.length === 0) {
  832. drawRegionMap.setStatusRegions([]);
  833. return;
  834. }
  835. drawRegionMap.setStatusRegions(regions);
  836. };
  837. /**
  838. * 用户“闭环(drawend)”后,把当前绘制结果自动写入草稿,避免切换 tab 时被清掉。
  839. * 注意:getAreaGeometry 可能包含多块,这里以“最新一块”为准(最后一个 feature)
  840. */
  841. const syncClosedDrawToDraft = () => {
  842. const tab = varietyTabs.value?.[activeVariety.value];
  843. if (!tab) return;
  844. const polygonData = drawRegionMap.getAreaGeometry?.();
  845. const geometryArr = polygonData?.geometryArr;
  846. if (!Array.isArray(geometryArr) || geometryArr.length === 0) return;
  847. const geom = String(geometryArr[geometryArr.length - 1] || "").trim();
  848. if (!isValidGeom(geom)) return;
  849. const key = draftKeyFromParts(activeRegionType.value, tab);
  850. if (key) {
  851. const prev = regionsDraftByKey.value[key] || {};
  852. regionsDraftByKey.value[key] = {
  853. ...prev,
  854. geomArr: [geom],
  855. geom,
  856. };
  857. }
  858. regionsDraftByIndex.value[activeVariety.value] = { geomArr: [geom], geom };
  859. regionGeom.value = geom;
  860. };
  861. const handleVarietyClick = (tab, index) => {
  862. clearDeleteSelectionState();
  863. // 取消上一次延迟渲染,避免快速切换 tab / 切换编辑态时重复追加要素
  864. clearPendingGeomRenderTimer();
  865. // 若存在“未闭环”的绘制草图(Draw 的 sketch 在 overlay 上),切换时需要清掉;已闭环的要素会走 drawend 写入草稿
  866. const draw = drawRegionMap.kmap?.draw;
  867. const hasUnclosedSketch = !!(draw && (draw.sketchFeature_ || draw.sketchCoords_ || draw.sketchLine_));
  868. if (hasUnclosedSketch) {
  869. drawRegionMap.abortOngoingDrawSketch?.();
  870. }
  871. activeVariety.value = index;
  872. // 取值优先级:
  873. // 1) 草稿(regionsDraftByKey / regionsDraftByIndex)
  874. // 2) 接口返回的 tab.geomItems[].geomWkt(你给的结构)
  875. // 3) 兜底 tab.geom(兼容旧结构)
  876. const draftGeom = getDraftGeomForTab(activeRegionType.value, tab, index);
  877. const rawGeomArr =
  878. isValidGeom(draftGeom)
  879. ? [String(draftGeom).trim()]
  880. : (() => {
  881. const fromItems = getGeomArrFromGeomItems(tab);
  882. if (fromItems.length) return fromItems;
  883. return isValidGeom(tab?.geom) ? [String(tab.geom).trim()] : [];
  884. })();
  885. const geomArr = getEditableGeomArrForCurrentTab(tab, rawGeomArr);
  886. // 保留一份“当前选中地块”的原始字符串形态给其它逻辑使用
  887. regionGeom.value = geomArr.length > 1 ? JSON.stringify(geomArr) : geomArr[0] || "";
  888. // 地图尚未初始化时,仅更新状态,不做图层绘制,避免首次进入重复叠加
  889. if (!drawRegionMap.kmap) return;
  890. // 确保当前大类颜色样式生效(非品种区:黄色/红色/灰色;品种区:绿色)
  891. applyRegionStyles();
  892. // 非品种区:底图显示品种区(只读绿色)+ 当前小类(按当前大类颜色渲染)
  893. // 品种区:显示其他品种只读 + 当前品种可编辑
  894. if (activeRegionType.value !== "variety") {
  895. if (isLockedAbnormalTab(tab)) {
  896. drawRegionMap.setStatusRegions([
  897. ...getAllVarietyReadonlyRegions(),
  898. ...getLockedDiseaseRegions(tab),
  899. ]);
  900. // 查看态也需要继续渲染当前小类地块(handleStatus=1),
  901. // 2/3 锁定地块仍由 setStatusRegions 只读层承载,避免被遗漏
  902. } else {
  903. renderAllVarietyRegionsReadonlyOnly();
  904. }
  905. } else {
  906. renderReadonlyVarietyRegions(index);
  907. }
  908. // 切换时先清空当前可编辑图层,避免叠加
  909. drawRegionMap.kmap?.polygonLayer?.source?.clear?.();
  910. if (geomArr.length > 0) {
  911. pendingGeomRenderTimer.value = setTimeout(() => {
  912. // 再兜底清一次,避免异步回调在 destroy/init 后仍执行导致重复追加
  913. drawRegionMap.kmap?.polygonLayer?.source?.clear?.();
  914. const viewOnlySubCategoryLabel =
  915. route.query.type === "viewOnly" && getCanonicalRegionTypeForStyles() !== "ABNORMAL"
  916. ? (tab.regionName || tab.problemZoneTypeName || "").toString().trim()
  917. : "";
  918. const currentAreaText = formatAreaTextFromGeomArr(geomArr);
  919. const viewOnlySubCategoryLabelWithArea =
  920. viewOnlySubCategoryLabel && currentAreaText
  921. ? `${viewOnlySubCategoryLabel}\n${currentAreaText}`
  922. : viewOnlySubCategoryLabel;
  923. drawRegionMap.setAreaGeometry(
  924. geomArr,
  925. false,
  926. undefined,
  927. undefined,
  928. getAbnormalGrowthOverlayMeta,
  929. viewOnlySubCategoryLabelWithArea || undefined
  930. );
  931. if (!viewOnly.value && activeRegionType.value !== "variety") {
  932. purgeLockedFeaturesFromEditableLayer(tab);
  933. }
  934. // 有当前小类地块:仅 fit 当前可编辑层,避免被其它只读参考地块拉远
  935. drawRegionMap.fitView?.();
  936. }, 50);
  937. } else {
  938. // 当前小类无地块:视野包含品种区只读底图(与其它参考地块联合范围)
  939. pendingGeomRenderTimer.value = setTimeout(() => {
  940. drawRegionMap.kmap?.polygonLayer?.source?.clear?.();
  941. drawRegionMap.fitAllRegions?.();
  942. }, 50);
  943. }
  944. };
  945. const viewOnly = computed(() => route.query.type === "viewOnly");
  946. const point = ref(null);
  947. const regionTypeTabs = ref([]);
  948. const activeRegionType = ref("variety");
  949. const regionInfo = ref([]);
  950. async function fetchRegionInfo() {
  951. const { data } = await VE_API.basic_farm.fetchRegionInfo({ subjectId: route.query.subjectId });
  952. if (data && data.length > 0) {
  953. regionInfo.value = data[0] || [];
  954. regionTypeTabs.value = regionInfo.value.problemZoneList || [];
  955. regionTypeTabs.value.unshift({ name: "品种区", code: "variety" });
  956. if (data[0]?.regionList?.length) {
  957. if (!hasAppliedInitialVariety.value && route.query?.varietyId) {
  958. activeVariety.value = resolveInitialVarietyIndex(data[0]?.regionList);
  959. hasAppliedInitialVariety.value = true;
  960. }
  961. point.value = data[0].point;
  962. varietyTabs.value = regionInfo.value.regionList || [];
  963. }
  964. }
  965. }
  966. /** 样式用的大类:与接口 tab.code 解耦(避免 ABNORMAL / 数字 code 等导致勾画色落到默认灰) */
  967. const getCanonicalRegionTypeForStyles = () => {
  968. const raw = activeRegionType.value;
  969. if (raw === "variety") return "variety";
  970. const tabs = regionTypeTabs.value || [];
  971. const item = tabs.find((t) => String(t?.code) === String(raw));
  972. if (item) {
  973. const kind = item.code;
  974. if (kind) return kind;
  975. }
  976. return "SLEEP";
  977. };
  978. const ABNORMAL_BADGE_BG_DISEASE_PEST = "#E32A28";
  979. const ABNORMAL_BADGE_BG_GROWTH = "#F76F00";
  980. const DISEASE_TREATING_FILL_COLOR = "rgba(191, 91, 91, 0.36)";
  981. const DISEASE_TREATING_STROKE_COLOR = "rgba(224, 49, 49, 0.3)";
  982. const SLEEP_ZONE_STROKE_COLOR = "#A6A6A6";
  983. const SLEEP_ZONE_FILL_COLOR = [166, 166, 166, 0.25];
  984. const getGeomItemByFeature = (tab, feature) => {
  985. if (!tab || !feature) return null;
  986. const items = Array.isArray(tab.geomItems) ? tab.geomItems : [];
  987. if (!items.length) return null;
  988. let featureWkt = "";
  989. try {
  990. featureWkt = wktGeomFormat.writeGeometry(feature.getGeometry(), WGS84_WKT_OPTS);
  991. } catch (_) {
  992. featureWkt = "";
  993. }
  994. if (!isValidGeom(featureWkt)) return null;
  995. const normalizeWktKey = (wkt) => String(wkt || "").replace(/\s+/g, "").trim();
  996. const normalizedFeatureWkt = normalizeWktKey(featureWkt);
  997. for (const item of items) {
  998. const polygons = flattenWktToPolygonWktArray(item?.geomWkt);
  999. if (polygons.some((w) => normalizeWktKey(w) === normalizedFeatureWkt)) {
  1000. return item;
  1001. }
  1002. }
  1003. // 兜底:仅在要素数量与 geomItems 数量一致时按索引映射,避免病害锁定态错位
  1004. const features = drawRegionMap.kmap?.polygonLayer?.source?.getFeatures?.() || [];
  1005. if (features.length === items.length) {
  1006. const featureIndex = features.findIndex((f) => f === feature);
  1007. if (featureIndex >= 0 && featureIndex < items.length) {
  1008. return items[featureIndex];
  1009. }
  1010. }
  1011. return null;
  1012. };
  1013. /** 异常区小类(长势/病害/虫害等)闭合地块后在多边形内展示标签与发现日期(查看态 setAreaGeometry 同步使用) */
  1014. const getAbnormalGrowthOverlayMeta = (feature) => {
  1015. if (getCanonicalRegionTypeForStyles() !== "ABNORMAL") return null;
  1016. const tab = varietyTabs.value?.[activeVariety.value];
  1017. if (!tab) return null;
  1018. const geomItem = getGeomItemByFeature(tab, feature);
  1019. const name = (tab.problemZoneTypeName || tab.regionName || "").toString();
  1020. const handleStatus = String(geomItem?.handleStatus || "");
  1021. let badgeText = "";
  1022. let badgeBackground = ABNORMAL_BADGE_BG_GROWTH;
  1023. let badgeTextColor = "#ffffff";
  1024. let badgeBorderColor = "";
  1025. if (name.includes("病害") || name.includes("虫害")) {
  1026. // 病害/虫害:严格按当前地块对应 geomItem;未命中(新勾画)按“新增”展示,避免误用旧地块状态
  1027. const currentGeomItem = geomItem || null;
  1028. const currentHandleStatus = String(currentGeomItem?.handleStatus || "");
  1029. const currentCreateTime = currentGeomItem?.createTime;
  1030. const prefix = name.includes("虫害") ? "虫害" : "病害";
  1031. if (!currentGeomItem) {
  1032. badgeText = `新增${prefix}`;
  1033. badgeBackground = ABNORMAL_BADGE_BG_DISEASE_PEST;
  1034. } else if (currentHandleStatus === "2") {
  1035. badgeText = `${prefix}治疗中`;
  1036. badgeTextColor = ABNORMAL_BADGE_BG_DISEASE_PEST;
  1037. badgeBackground = "#fff";
  1038. badgeBorderColor = ABNORMAL_BADGE_BG_DISEASE_PEST;
  1039. } else if (currentHandleStatus == "3") {
  1040. badgeText = `${prefix}已控制`;
  1041. // 已控制态与休眠区视觉保持一致
  1042. badgeBackground = SLEEP_ZONE_STROKE_COLOR;
  1043. } else {
  1044. badgeText = `新增${prefix}`;
  1045. badgeBackground = ABNORMAL_BADGE_BG_DISEASE_PEST;
  1046. }
  1047. const rawCreateTime = currentCreateTime || tab?.createTime;
  1048. const sourceDate = rawCreateTime ? new Date(rawCreateTime) : new Date();
  1049. const resolvedDate = Number.isNaN(sourceDate.getTime()) ? new Date() : sourceDate;
  1050. const y = resolvedDate.getFullYear();
  1051. const m = String(resolvedDate.getMonth() + 1).padStart(2, "0");
  1052. const d = String(resolvedDate.getDate()).padStart(2, "0");
  1053. return {
  1054. badgeText,
  1055. discoveryDate: `${y}.${m}.${d}`,
  1056. badgeBackground,
  1057. badgeTextColor,
  1058. badgeBorderColor,
  1059. handleStatus: currentHandleStatus,
  1060. };
  1061. } else if (name.includes("过慢")) {
  1062. if (handleStatus === "2") {
  1063. badgeText = "长势过慢治疗中";
  1064. badgeTextColor = ABNORMAL_BADGE_BG_GROWTH;
  1065. badgeBackground = "#fff";
  1066. badgeBorderColor = ABNORMAL_BADGE_BG_GROWTH;
  1067. } else {
  1068. badgeText = "新增长势过慢";
  1069. }
  1070. } else if (name.includes("过快")) {
  1071. if (handleStatus === "2") {
  1072. badgeText = "长势过快治疗中";
  1073. badgeTextColor = ABNORMAL_BADGE_BG_GROWTH;
  1074. badgeBackground = "#fff";
  1075. badgeBorderColor = ABNORMAL_BADGE_BG_GROWTH;
  1076. } else {
  1077. badgeText = "新增长势过快";
  1078. }
  1079. } else {
  1080. return null;
  1081. }
  1082. const rawCreateTime = geomItem?.createTime || tab?.createTime;
  1083. const sourceDate = rawCreateTime ? new Date(rawCreateTime) : new Date();
  1084. const resolvedDate = Number.isNaN(sourceDate.getTime()) ? new Date() : sourceDate;
  1085. const y = resolvedDate.getFullYear();
  1086. const m = String(resolvedDate.getMonth() + 1).padStart(2, "0");
  1087. const d = String(resolvedDate.getDate()).padStart(2, "0");
  1088. return {
  1089. badgeText,
  1090. discoveryDate: `${y}.${m}.${d}`,
  1091. badgeBackground,
  1092. badgeTextColor,
  1093. badgeBorderColor,
  1094. handleStatus,
  1095. };
  1096. };
  1097. const findProblemZoneGroupByDrawType = (majorType) => {
  1098. if (!majorType || majorType === "variety") return null;
  1099. const list = regionInfo.value?.problemZoneList || [];
  1100. return (
  1101. list.find((x) => x.code === majorType) ||
  1102. list.find((x) => String(x?.code) === String(majorType))
  1103. );
  1104. };
  1105. const getTabsForMajorType = (majorType) => {
  1106. if (majorType === "variety") {
  1107. return regionInfo.value?.regionList || [];
  1108. }
  1109. const g = findProblemZoneGroupByDrawType(majorType);
  1110. return g?.children || [];
  1111. };
  1112. const findTabIndexForCategory = (tabs, category) => {
  1113. if (!Array.isArray(tabs) || !category || typeof category !== "object") return -1;
  1114. const fields = ["regionId", "problemZoneTypeId", "typeId", "id"];
  1115. for (let i = 0; i < tabs.length; i++) {
  1116. const t = tabs[i];
  1117. for (const f of fields) {
  1118. const cv = category[f];
  1119. const tv = t[f];
  1120. if (cv != null && cv !== "" && tv != null && String(cv) === String(tv)) return i;
  1121. }
  1122. }
  1123. const cname = (category.regionName || category.problemZoneTypeName || "").toString().trim();
  1124. if (cname) {
  1125. const idx = tabs.findIndex((t) => {
  1126. const tn = (t.regionName || t.problemZoneTypeName || "").toString().trim();
  1127. return tn === cname;
  1128. });
  1129. if (idx >= 0) return idx;
  1130. }
  1131. return -1;
  1132. };
  1133. /** 仅提交本次有勾画草稿(regionsDraftByKey)的品种区,不带未勾画项 */
  1134. const buildRegionListForSubmit = () => {
  1135. const list = regionInfo.value?.regionList || [];
  1136. const out = [];
  1137. list.forEach((tab) => {
  1138. const k = draftKeyFromParts("variety", tab);
  1139. const d = k ? regionsDraftByKey.value[k] : null;
  1140. const geom = d?.geom != null ? String(d.geom).trim() : "";
  1141. if (!isValidGeom(geom)) return;
  1142. out.push({
  1143. regionId: tab.regionId,
  1144. typeId: tab.typeId,
  1145. regionName: tab.regionName,
  1146. geom,
  1147. });
  1148. });
  1149. return out;
  1150. };
  1151. /** 仅包含有勾画草稿的问题分区子项;无任何子项勾画的分组整组不传 */
  1152. const buildProblemZoneListForSubmit = () => {
  1153. const raw = regionInfo.value?.problemZoneList || [];
  1154. const subjectId = route.query.subjectId;
  1155. const groups = [];
  1156. raw.forEach((group) => {
  1157. const canonical = group.code;
  1158. const children = (group.children || [])
  1159. .map((child) => {
  1160. if (!canonical) return null;
  1161. const k = draftKeyFromParts(canonical, child);
  1162. const d = k ? regionsDraftByKey.value[k] : null;
  1163. let geomItems = Array.isArray(d?.geomItems)
  1164. ? d.geomItems
  1165. : [];
  1166. geomItems = geomItems
  1167. .map((x) => {
  1168. const geomWkt = x?.geomWkt != null ? String(x.geomWkt).trim() : "";
  1169. if (!isValidGeom(geomWkt)) return null;
  1170. return {
  1171. ...x,
  1172. geomWkt,
  1173. remark: x?.remark != null ? String(x.remark) : "",
  1174. };
  1175. })
  1176. .filter(Boolean);
  1177. if (geomItems.length === 0) {
  1178. const geomWkt = d?.geom != null ? String(d.geom).trim() : "";
  1179. if (!isValidGeom(geomWkt)) return null;
  1180. const remark =
  1181. d && "remark" in d && d.remark != null ? String(d.remark) : "";
  1182. geomItems = [{ geomWkt, remark }];
  1183. }
  1184. return {
  1185. farmSubjectId: subjectId,
  1186. problemZoneTypeId: child.problemZoneTypeId ?? child.typeId ?? "",
  1187. problemZoneTypeName: child.problemZoneTypeName ?? child.regionName ?? "",
  1188. parentName: group.name ?? "",
  1189. parentCode: group.code ?? "",
  1190. geomItems,
  1191. };
  1192. })
  1193. .filter(Boolean);
  1194. if (children.length === 0) return;
  1195. groups.push({
  1196. name: group.name,
  1197. code: group.code,
  1198. children,
  1199. });
  1200. });
  1201. return groups;
  1202. };
  1203. onActivated(async () => {
  1204. activeVariety.value = 0;
  1205. hasAppliedInitialVariety.value = false;
  1206. clearPendingGeomRenderTimer();
  1207. // keep-alive 场景下再次进入前先销毁旧地图实例,避免重复 init 导致图层状态错位
  1208. if (drawRegionMap.kmap) {
  1209. drawRegionMap.abortOngoingDrawSketch?.();
  1210. drawRegionMap.destroyMap?.();
  1211. }
  1212. type.value = route.query.type;
  1213. const editable = !viewOnly.value;
  1214. await fetchRegionInfo();
  1215. drawRegionMap.initMap(point.value, mapContainer.value, editable, true, true, syncClosedDrawToDraft);
  1216. applyRegionStyles();
  1217. // 首次进入时,fetch 阶段可能先于地图初始化触发了 tab 渲染;
  1218. // 这里在地图可用后再补渲一次,确保“其他品种只读地块”能显示出来
  1219. if (varietyTabs.value.length > 0 && varietyTabs.value[activeVariety.value]) {
  1220. handleVarietyClick(varietyTabs.value[activeVariety.value], activeVariety.value);
  1221. }
  1222. // 从编辑态进入仅查看时,需重新初始化为不可编辑
  1223. if (viewOnly.value && drawRegionMap.kmap && drawRegionMap.editable) {
  1224. drawRegionMap.destroyMap();
  1225. drawRegionMap.initMap(point.value, mapContainer.value, false, true, false, syncClosedDrawToDraft);
  1226. applyRegionStyles();
  1227. if (varietyTabs.value.length > 0 && varietyTabs.value[activeVariety.value]) {
  1228. handleVarietyClick(varietyTabs.value[activeVariety.value], activeVariety.value);
  1229. }
  1230. }
  1231. // 从仅查看进入勾画(编辑)时,需重新初始化为可编辑
  1232. if (!viewOnly.value && drawRegionMap.kmap && !drawRegionMap.editable) {
  1233. drawRegionMap.destroyMap();
  1234. drawRegionMap.initMap(point.value, mapContainer.value, true, true, true, syncClosedDrawToDraft);
  1235. applyRegionStyles();
  1236. if (varietyTabs.value.length > 0 && varietyTabs.value[activeVariety.value]) {
  1237. handleVarietyClick(varietyTabs.value[activeVariety.value], activeVariety.value);
  1238. }
  1239. }
  1240. // 查看模式下已通过 fitAllRegions 适配;编辑模式再设置地图中心
  1241. if (!viewOnly.value) {
  1242. drawRegionMap.setMapPosition(convertPointToArray(point.value));
  1243. }
  1244. resizeMapToContainer();
  1245. });
  1246. watch(
  1247. () => [varietyTabs.value.length, activeRegionType.value, activeVariety.value],
  1248. () => {
  1249. if (drawRegionMap.kmap?.map) resizeMapToContainer();
  1250. }
  1251. );
  1252. onDeactivated(() => {
  1253. clearDeleteSelectionState();
  1254. activeVariety.value = 0;
  1255. activeRegionType.value = "variety";
  1256. clearPendingGeomRenderTimer();
  1257. // 离开页面时中止未完成绘制并销毁地图,确保下次进入是干净实例
  1258. drawRegionMap.abortOngoingDrawSketch?.();
  1259. drawRegionMap.destroyMap?.();
  1260. })
  1261. const goBack = () => {
  1262. if (route.query.targetUrl) {
  1263. router.replace(route.query.targetUrl);
  1264. return;
  1265. }
  1266. router.go(-1);
  1267. };
  1268. const resetPolygon = () => {
  1269. clearDeleteSelectionState();
  1270. ElMessageBox.confirm(
  1271. "确认重置当前地块吗?重置后将恢复为初始状态",
  1272. "重置确认",
  1273. {
  1274. confirmButtonText: "确认重置",
  1275. cancelButtonText: "取消",
  1276. type: "warning",
  1277. }
  1278. )
  1279. .then(() => {
  1280. // 先取消进行中的勾画草图(未完成时线条在 Draw 的 overlay 上,清 source 去不掉)
  1281. drawRegionMap.abortOngoingDrawSketch();
  1282. // 只清空当前可编辑多边形,不影响只读状态图层
  1283. if (drawRegionMap.kmap && drawRegionMap.kmap.polygonLayer && drawRegionMap.kmap.polygonLayer.source) {
  1284. drawRegionMap.kmap.polygonLayer.source.clear();
  1285. }
  1286. // 清空当前 tab 草稿,重置应回到“进入时初始化值”
  1287. const currentTab = varietyTabs.value?.[activeVariety.value];
  1288. const currentKey = draftKeyFromParts(activeRegionType.value, currentTab);
  1289. if (currentKey && regionsDraftByKey.value[currentKey]) {
  1290. delete regionsDraftByKey.value[currentKey];
  1291. }
  1292. if (regionsDraftByIndex.value[activeVariety.value]) {
  1293. delete regionsDraftByIndex.value[activeVariety.value];
  1294. }
  1295. // 当前品类有初始化地块则回显;没有则保持空地图
  1296. const initialGeomArrRaw = (() => {
  1297. const fromItems = getGeomArrFromGeomItems(currentTab);
  1298. if (fromItems.length) return fromItems;
  1299. return isValidGeom(currentTab?.geom) ? [String(currentTab.geom).trim()] : [];
  1300. })();
  1301. const initialGeomArr = getEditableGeomArrForCurrentTab(currentTab, initialGeomArrRaw);
  1302. if (
  1303. !viewOnly.value &&
  1304. activeRegionType.value !== "variety" &&
  1305. isLockedAbnormalTab(currentTab)
  1306. ) {
  1307. drawRegionMap.setStatusRegions([
  1308. ...getAllVarietyReadonlyRegions(),
  1309. ...getLockedDiseaseRegions(currentTab),
  1310. ]);
  1311. }
  1312. if (initialGeomArr.length > 0) {
  1313. drawRegionMap.setAreaGeometry(
  1314. initialGeomArr,
  1315. false,
  1316. undefined,
  1317. undefined,
  1318. getAbnormalGrowthOverlayMeta
  1319. );
  1320. regionGeom.value =
  1321. initialGeomArr.length > 1 ? JSON.stringify(initialGeomArr) : initialGeomArr[0];
  1322. } else {
  1323. regionGeom.value = "";
  1324. drawRegionMap.fitAllRegions?.();
  1325. }
  1326. ElMessage.success("地块已重置");
  1327. })
  1328. .catch(() => {
  1329. // 用户取消重置,不做任何操作
  1330. });
  1331. };
  1332. const submitRegions = async () => {
  1333. if (submitting.value) return;
  1334. const regionList = buildRegionListForSubmit();
  1335. const problemZoneList = buildProblemZoneListForSubmit();
  1336. if (regionList.length === 0 && problemZoneList.length === 0) {
  1337. ElMessage.warning("请先勾画地块后再确认");
  1338. return false;
  1339. }
  1340. submitting.value = true;
  1341. try {
  1342. const params = {
  1343. subjectId: route.query.subjectId,
  1344. regionList,
  1345. problemZoneList,
  1346. };
  1347. const res = await VE_API.basic_farm.ediRegionZone(params);
  1348. if (res?.code === 0) {
  1349. if (selectedDrawTypeMeta.value.type === 'ABNORMAL') {
  1350. let problemZoneId = null;
  1351. if (params.problemZoneList.length) {
  1352. res.data[0].problemZoneList.forEach(element => {
  1353. if (element.code === selectedDrawTypeMeta.value.type) {
  1354. element.children.forEach(item => {
  1355. if (item.problemZoneTypeName === selectedDrawTypeMeta.value.category.problemZoneTypeName) {
  1356. problemZoneId = item.id;
  1357. }
  1358. });
  1359. }
  1360. });
  1361. }
  1362. VE_API.basic_farm.saveProblemZoneImage({
  1363. problemZoneId,
  1364. imagePathList: selectedDrawTypeMeta.value.images,
  1365. })
  1366. }
  1367. return true;
  1368. }
  1369. ElMessage.error(res?.msg || "保存失败");
  1370. return false;
  1371. } catch (e) {
  1372. ElMessage.error("保存失败");
  1373. return false;
  1374. } finally {
  1375. submitting.value = false;
  1376. }
  1377. };
  1378. const submitCurrentTabGeometryChange = async (geomWktOrArr) => {
  1379. const tab = varietyTabs.value?.[activeVariety.value];
  1380. if (!tab) return false;
  1381. const geometryArr = Array.isArray(geomWktOrArr)
  1382. ? geomWktOrArr
  1383. : isValidGeom(geomWktOrArr)
  1384. ? [String(geomWktOrArr).trim()]
  1385. : [];
  1386. const normalizedGeom = mergePolygonWktsForApi(geometryArr);
  1387. const params = {
  1388. subjectId: route.query.subjectId,
  1389. regionList: [],
  1390. problemZoneList: [],
  1391. };
  1392. if (activeRegionType.value === "variety") {
  1393. params.regionList = [
  1394. {
  1395. regionId: tab.regionId,
  1396. typeId: tab.typeId,
  1397. regionName: tab.regionName,
  1398. geom: normalizedGeom,
  1399. },
  1400. ];
  1401. } else {
  1402. const group = findProblemZoneGroupByDrawType(activeRegionType.value);
  1403. if (!group) return false;
  1404. const geomItems = isLockedAbnormalTab(tab)
  1405. ? buildDiseaseGeomItemsForSubmit(tab, geometryArr)
  1406. : buildGeomItemsFromGeometryArr(tab, geometryArr);
  1407. params.problemZoneList = [
  1408. {
  1409. name: group.name,
  1410. code: group.code,
  1411. children: [
  1412. {
  1413. farmSubjectId: route.query.subjectId,
  1414. problemZoneTypeId: tab.problemZoneTypeId ?? tab.typeId ?? "",
  1415. problemZoneTypeName: tab.problemZoneTypeName ?? tab.regionName ?? "",
  1416. parentName: group.name ?? "",
  1417. parentCode: group.code ?? "",
  1418. geomItems,
  1419. },
  1420. ],
  1421. },
  1422. ];
  1423. }
  1424. const res = await VE_API.basic_farm.ediRegionZone(params);
  1425. return res?.code === 0;
  1426. };
  1427. /** 以弹窗 confirm 传入的 drawMeta(大类 type + 小类 category + remark)为准写入草稿并提交 */
  1428. const confirmArea = async (drawMeta) => {
  1429. const meta =
  1430. drawMeta && drawMeta.type != null
  1431. ? drawMeta
  1432. : selectedDrawTypeMeta.value;
  1433. if (!meta?.type || meta.category == null) {
  1434. ElMessage.warning("请先在弹窗中选择勾画类型与类别");
  1435. return;
  1436. }
  1437. const polygonData = drawRegionMap.getAreaGeometry?.();
  1438. const geometryArr = polygonData?.geometryArr;
  1439. if (!Array.isArray(geometryArr) || geometryArr.length === 0) {
  1440. ElMessage.warning("请先勾画地块后再确认");
  1441. return;
  1442. }
  1443. const normalizedGeomArr = flattenGeomWktListForMap(geometryArr);
  1444. if (!Array.isArray(normalizedGeomArr) || normalizedGeomArr.length === 0) {
  1445. ElMessage.warning("地块几何无效,请重新勾画");
  1446. return;
  1447. }
  1448. const key = draftKeyFromParts(meta.type, meta.category);
  1449. if (!key) {
  1450. ElMessage.warning("无法识别勾画类别,请重新选择");
  1451. return;
  1452. }
  1453. const geom = mergePolygonWktsForApi(normalizedGeomArr);
  1454. const currentTab = varietyTabs.value?.[activeVariety.value];
  1455. const nextDraft = {
  1456. geomArr: normalizedGeomArr,
  1457. geom,
  1458. remark: meta.remark != null ? String(meta.remark) : "",
  1459. };
  1460. if (meta.type !== "variety") {
  1461. nextDraft.geomItems = isLockedAbnormalTab(currentTab)
  1462. ? buildDiseaseGeomItemsForSubmit(currentTab, normalizedGeomArr, meta.remark)
  1463. : buildGeomItemsFromGeometryArr(currentTab, normalizedGeomArr, meta.remark);
  1464. }
  1465. regionsDraftByKey.value[key] = nextDraft;
  1466. const tabList = getTabsForMajorType(meta.type);
  1467. const idx = findTabIndexForCategory(tabList, meta.category);
  1468. if (activeRegionType.value === meta.type && idx >= 0) {
  1469. regionsDraftByIndex.value[idx] = { geomArr: normalizedGeomArr, geom };
  1470. }
  1471. const ok = await submitRegions();
  1472. const rid = meta.category?.regionId;
  1473. if (rid != null && rid !== "") {
  1474. try {
  1475. await VE_API.basic_farm.updateLastViewTime({ regionId: rid });
  1476. } catch (_) {
  1477. /* 非品种区可能无 regionId,忽略 */
  1478. }
  1479. }
  1480. if (!ok) return;
  1481. // 保存成功后:不跳走,刷新当前页并回显最新数据,并切换为查看态
  1482. try {
  1483. await fetchRegionInfo();
  1484. // 接口已是最新几何与 id,清空草稿避免旧 key/下标回退遮挡 geomItems
  1485. clearAllRegionDrafts();
  1486. // 恢复当前大类下的子类 tab(fetchRegionInfo 默认会填充品种区)
  1487. if (activeRegionType.value === "variety") {
  1488. varietyTabs.value = regionInfo.value?.regionList || [];
  1489. } else {
  1490. const group = (regionTypeTabs.value || []).find(
  1491. (x) => x?.code === activeRegionType.value
  1492. );
  1493. varietyTabs.value = group?.children || [];
  1494. }
  1495. // 更新路由为查看态,确保按钮/头部状态同步
  1496. try {
  1497. router.replace({ query: { ...route.query, type: "viewOnly" } });
  1498. } catch (_) {
  1499. // 路由更新失败不影响回显
  1500. }
  1501. // 重新初始化地图(非编辑/查看模式),确保回显形状正确
  1502. if (drawRegionMap.kmap) {
  1503. drawRegionMap.destroyMap?.();
  1504. }
  1505. drawRegionMap.initMap(point.value, mapContainer.value, false, true, false);
  1506. applyRegionStyles();
  1507. if (varietyTabs.value.length > 0 && varietyTabs.value[activeVariety.value]) {
  1508. handleVarietyClick(varietyTabs.value[activeVariety.value], activeVariety.value);
  1509. }
  1510. drawRegionMap.fitAllRegions?.();
  1511. } catch (_) {
  1512. // 刷新失败不阻断用户继续操作,保持当前页面状态
  1513. }
  1514. if (route.query.showTipPopup) {
  1515. showTipPopup.value = true;
  1516. return;
  1517. }
  1518. };
  1519. const openConfirmDrawTypePopup = () => {
  1520. const polygonData = drawRegionMap.getAreaGeometry?.();
  1521. const geometryArr = polygonData?.geometryArr;
  1522. if (!Array.isArray(geometryArr) || geometryArr.length === 0) {
  1523. ElMessage.warning("请先勾画地块后再确认");
  1524. return;
  1525. }
  1526. const remark = varietyTabs?.value?.[activeVariety.value]?.geomItems?.[0]?.remark;
  1527. confirmDrawTypePopupRef.value.openPopup({
  1528. regionInfo: regionInfo.value,
  1529. activeRegionType: activeRegionType.value,
  1530. activeVarietyIndex: activeVariety.value,
  1531. remark: activeRegionType.value === 'variety' ? '' : remark,
  1532. });
  1533. };
  1534. const handleConfirmDrawType = async (payload) => {
  1535. selectedDrawTypeMeta.value = payload;
  1536. await confirmArea(payload);
  1537. };
  1538. const handleEditRegion = async () => {
  1539. clearDeleteSelectionState();
  1540. // 从查看态切换到可勾画编辑态:移除查看标记(所有大类共用)
  1541. const nextQuery = { ...route.query };
  1542. delete nextQuery.type;
  1543. delete nextQuery.viewOnly;
  1544. clearPendingGeomRenderTimer();
  1545. await router.replace({ query: nextQuery });
  1546. nextTick(() => {
  1547. if (drawRegionMap.kmap) {
  1548. drawRegionMap.abortOngoingDrawSketch?.();
  1549. drawRegionMap.destroyMap();
  1550. }
  1551. // 若当前不在品种区(如环境/异常/休眠),点击“编辑”进入当前问题区的编辑态:
  1552. // - 地图可编辑(仅编辑当前选中的问题区子项)
  1553. // - 只显示「品种区」地块作为底图参考(只读)
  1554. // - 不显示其它问题区地块
  1555. if (activeRegionType.value !== "variety") {
  1556. drawRegionMap.initMap(point.value, mapContainer.value, true, true, true, syncClosedDrawToDraft);
  1557. applyRegionStyles();
  1558. // 清空当前可编辑图层,避免残留
  1559. drawRegionMap.kmap?.polygonLayer?.source?.clear?.();
  1560. const tab = varietyTabs.value?.[activeVariety.value];
  1561. if (isLockedAbnormalTab(tab)) {
  1562. drawRegionMap.setStatusRegions([
  1563. ...getAllVarietyReadonlyRegions(),
  1564. ...getLockedDiseaseRegions(tab),
  1565. ]);
  1566. } else {
  1567. renderAllVarietyRegionsReadonlyOnly();
  1568. }
  1569. // 进入编辑时:缩放到当前要编辑的地块
  1570. // 异常锁定小类(2/3)进入编辑态时,禁止从 tab.geom / draftGeom 回填到可编辑层,避免与只读层重叠
  1571. const currentGeomArrRaw = isLockedAbnormalTab(tab)
  1572. ? getGeomArrFromGeomItems(tab)
  1573. : (() => {
  1574. const currentGeomStr = tab
  1575. ? (getDraftGeomForTab(activeRegionType.value, tab, activeVariety.value) || tab.geom)
  1576. : "";
  1577. return isValidGeom(currentGeomStr)
  1578. ? [String(currentGeomStr).trim()]
  1579. : getGeomArrFromGeomItems(tab);
  1580. })();
  1581. const currentGeomArr = getEditableGeomArrForCurrentTab(tab, currentGeomArrRaw);
  1582. regionGeom.value =
  1583. currentGeomArr.length > 1 ? JSON.stringify(currentGeomArr) : currentGeomArr[0] || "";
  1584. if (currentGeomArr.length > 0) {
  1585. drawRegionMap.kmap?.polygonLayer?.source?.clear?.();
  1586. drawRegionMap.setAreaGeometry(
  1587. currentGeomArr,
  1588. true,
  1589. undefined,
  1590. undefined,
  1591. getAbnormalGrowthOverlayMeta
  1592. );
  1593. purgeLockedFeaturesFromEditableLayer(tab);
  1594. } else {
  1595. // 仍自适应到品种区底图
  1596. drawRegionMap.fitAllRegions?.();
  1597. }
  1598. return;
  1599. }
  1600. drawRegionMap.initMap(point.value, mapContainer.value, true, true, true, syncClosedDrawToDraft);
  1601. applyRegionStyles();
  1602. // 切到编辑态后:统一走一遍当前 tab 的点击逻辑,确保所有有地块的品种都能显示
  1603. if (varietyTabs.value.length && varietyTabs.value[activeVariety.value]) {
  1604. // 进入编辑时:让当前品种地块显示且缩放到当前编辑地块
  1605. handleVarietyClick(varietyTabs.value[activeVariety.value], activeVariety.value);
  1606. const tab = varietyTabs.value[activeVariety.value];
  1607. const draftGeom = getDraftGeomForTab(activeRegionType.value, tab, activeVariety.value);
  1608. const rawGeomArr =
  1609. isValidGeom(draftGeom)
  1610. ? [String(draftGeom).trim()]
  1611. : (() => {
  1612. const fromItems = getGeomArrFromGeomItems(tab);
  1613. if (fromItems.length) return fromItems;
  1614. return isValidGeom(tab?.geom) ? [String(tab.geom).trim()] : [];
  1615. })();
  1616. const geomArr = flattenGeomWktListForMap(rawGeomArr);
  1617. drawRegionMap.kmap?.polygonLayer?.source?.clear?.();
  1618. if (geomArr.length > 0) {
  1619. drawRegionMap.setAreaGeometry(
  1620. geomArr,
  1621. true,
  1622. undefined,
  1623. undefined,
  1624. getAbnormalGrowthOverlayMeta
  1625. );
  1626. }
  1627. } else {
  1628. renderReadonlyVarietyRegions(activeVariety.value);
  1629. const fallbackGeom = regionGeom.value;
  1630. if (isValidGeom(fallbackGeom)) {
  1631. drawRegionMap.kmap?.polygonLayer?.source?.clear?.();
  1632. drawRegionMap.setAreaGeometry(
  1633. [fallbackGeom],
  1634. true,
  1635. undefined,
  1636. undefined,
  1637. getAbnormalGrowthOverlayMeta
  1638. );
  1639. }
  1640. }
  1641. // 编辑态下:保持缩放在当前要编辑地块,不再强制 fitAllRegions 覆盖
  1642. });
  1643. };
  1644. const showTipPopup = ref(false);
  1645. const handleTipConfirm = () => {
  1646. const query = {
  1647. hideInteraction: "true",
  1648. };
  1649. if (route.query.addVarietyCount) {
  1650. query.addVarietyCount = String(route.query.addVarietyCount);
  1651. }
  1652. router.push({ path: "/growth_report", query });
  1653. }
  1654. </script>
  1655. <style lang="scss" scoped>
  1656. .edit-map {
  1657. width: 100%;
  1658. height: 100vh;
  1659. overflow: hidden;
  1660. display: flex;
  1661. flex-direction: column;
  1662. box-sizing: border-box;
  1663. &> :first-child {
  1664. flex-shrink: 0;
  1665. }
  1666. .region-type-tabs {
  1667. flex-shrink: 0;
  1668. display: flex;
  1669. align-items: center;
  1670. background: #f4f4f4;
  1671. margin: 10px 10px 0;
  1672. padding: 3px;
  1673. border-radius: 4px;
  1674. box-sizing: border-box;
  1675. .region-type-tab {
  1676. flex: 1;
  1677. text-align: center;
  1678. padding: 5px 0;
  1679. color: #767676;
  1680. }
  1681. .region-type-tab--active {
  1682. background: #ffffff;
  1683. border-radius: 4px;
  1684. color: #0D0D0D;
  1685. }
  1686. }
  1687. .variety-tabs {
  1688. flex-shrink: 0;
  1689. display: flex;
  1690. align-items: center;
  1691. gap: 8px;
  1692. padding: 10px 12px 0;
  1693. overflow-x: auto;
  1694. overflow-y: hidden;
  1695. flex-wrap: nowrap;
  1696. -webkit-overflow-scrolling: touch;
  1697. .variety-tab {
  1698. padding: 4px 12px;
  1699. border-radius: 2px;
  1700. color: #575757;
  1701. background: #F4F4F4;
  1702. border: 1px solid transparent;
  1703. white-space: nowrap;
  1704. }
  1705. .variety-tab--active {
  1706. background: rgba(33, 153, 248, 0.1);
  1707. color: #2199F8;
  1708. border: 1px solid #2199F8;
  1709. }
  1710. }
  1711. .edit-map-content {
  1712. width: 100%;
  1713. margin-top: 10px;
  1714. flex: 1;
  1715. min-height: 0;
  1716. position: relative;
  1717. box-sizing: border-box;
  1718. /* 底部「重置 / 确认」等为 position:fixed,占高约 68px,地图区域需预留避免被盖住 */
  1719. padding-bottom: 68px;
  1720. .edit-map-tip {
  1721. position: absolute;
  1722. top: 23px;
  1723. left: calc(50% - 256px / 2);
  1724. z-index: 1;
  1725. font-size: 12px;
  1726. color: #fff;
  1727. padding: 9px 20px;
  1728. background: rgba(0, 0, 0, 0.5);
  1729. border-radius: 20px;
  1730. }
  1731. .map-container {
  1732. width: 100%;
  1733. height: 100%;
  1734. }
  1735. .edit-map-footer {
  1736. position: absolute;
  1737. bottom: 85px;
  1738. left: 12px;
  1739. width: calc(100% - 24px);
  1740. display: flex;
  1741. flex-direction: column;
  1742. align-items: flex-end;
  1743. .footer-back {
  1744. padding: 4px 5px 7px;
  1745. background: #fff;
  1746. border-radius: 8px;
  1747. margin-bottom: 12px;
  1748. .back-icon {
  1749. width: 23px;
  1750. height: 23px;
  1751. }
  1752. }
  1753. .edit-map-footer-btn {
  1754. display: flex;
  1755. justify-content: space-between;
  1756. align-items: center;
  1757. width: 100%;
  1758. position: fixed;
  1759. bottom: 0;
  1760. left: 0;
  1761. background: #fff;
  1762. padding: 10px 12px 20px 12px;
  1763. box-sizing: border-box;
  1764. &.confirm-btn-box {
  1765. justify-content: center;
  1766. }
  1767. div {
  1768. width: 100px;
  1769. text-align: center;
  1770. color: #666666;
  1771. font-size: 14px;
  1772. padding: 8px 0;
  1773. border-radius: 25px;
  1774. border: 0.5px solid rgba(153, 153, 153, 0.5);
  1775. }
  1776. .btn-confirm {
  1777. background: #2199F8;
  1778. color: #fff;
  1779. border: 1px solid #2199F8;
  1780. }
  1781. }
  1782. }
  1783. }
  1784. }
  1785. </style>