drawRegion.vue 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840
  1. <template>
  2. <div class="edit-map">
  3. <custom-header :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. {{ item.name }}
  8. </div>
  9. </div>
  10. <div class="variety-tabs" v-if="varietyTabs.length > 0 && activeRegionType !== 'DORMANCY'">
  11. <div v-for="(v, index) in varietyTabs" :key="index" class="variety-tab"
  12. :class="{ 'variety-tab--active': activeVariety === index }">
  13. {{ v.regionName || v.problemZoneTypeName }}
  14. </div>
  15. </div>
  16. <div class="edit-map-content">
  17. <div class="edit-map-tip" v-if="!viewOnly">{{ t('操作提示:拖动圆点,即可调整地块边界') }}</div>
  18. <div class="map-container" ref="mapContainer"></div>
  19. <div class="edit-map-footer" :style="{ 'bottom': activeRegionType !== 'DORMANCY' ? '85px' : '59px' }">
  20. <div class="footer-back" @click="goBack">
  21. <img class="back-icon" src="@/assets/img/home/go-back.png" alt="" />
  22. </div>
  23. <div class="edit-map-footer-btn" v-if="!viewOnly">
  24. <div class="btn-delete" @click="deletePolygon">{{ t('删除地块') }}</div>
  25. <!-- <div class="btn-cancel" @click="goBack">{{ t('取消') }}</div> -->
  26. <div class="btn-confirm" @click="confirm">{{ t('确认区域') }}</div>
  27. </div>
  28. </div>
  29. </div>
  30. <popup v-model:show="showAbnormalTypePopup" round closeable class="abnormal-popup"
  31. :close-on-click-overlay="true">
  32. <div class="abnormal-popup-content">
  33. <div class="abnormal-popup-title">{{ t('请选择异常类型') }}</div>
  34. <el-select v-model="selectedAbnormalType" class="abnormal-type-select" :placeholder="t('请选择类型')" size="large">
  35. <el-option v-for="item in abnormalTypeOptions" :key="item.value" :label="item.name"
  36. :value="item.value" />
  37. </el-select>
  38. <div class="abnormal-popup-confirm" @click="handleConfirmUpload">{{ t('确认上传') }}</div>
  39. </div>
  40. </popup>
  41. </div>
  42. </template>
  43. <script setup>
  44. import { useI18n } from "@/i18n";
  45. const { t } = useI18n();
  46. import customHeader from "@/components/customHeader.vue";
  47. import { ref, computed, onMounted, onActivated, onDeactivated } from "vue";
  48. import { Popup } from "vant";
  49. import DrawRegionMap from "./map/drawRegionMap.js";
  50. import { Map as KMapMap } from "@/utils/ol-map/KMap";
  51. import { useRouter, useRoute } from "vue-router";
  52. import { convertPointToArray } from "@/utils/index";
  53. import { ElMessage, ElMessageBox } from "element-plus";
  54. import Style from "ol/style/Style";
  55. import { Fill, Stroke, Circle, Text } from "ol/style.js";
  56. import { Point } from "ol/geom";
  57. import * as proj from "ol/proj";
  58. import { getArea } from "ol/sphere.js";
  59. const router = useRouter();
  60. const route = useRoute();
  61. const mapContainer = ref(null);
  62. const drawRegionMap = new DrawRegionMap();
  63. const DEFAULT_MAP_CENTER = "POINT (113.6142086995688 23.585836479509055)";
  64. const type = ref(null);
  65. const viewOnly = computed(() => route.query.viewOnly === "1" || route.query.viewOnly === "true");
  66. const showDataMode = computed(() => route.query.showData === "1" || route.query.showData === "true");
  67. const showAbnormalTypePopup = ref(false);
  68. const selectedAbnormalType = ref("");
  69. const abnormalTypeOptions = [{
  70. name: "病害",
  71. value: "DISEASE"
  72. }, {
  73. name: "虫害",
  74. value: "PEST"
  75. }, {
  76. name: "不确定",
  77. value: "UNCERTAIN"
  78. }];
  79. onMounted(() => {
  80. type.value = route.query.type;
  81. const point = route.query.mapCenter || DEFAULT_MAP_CENTER;
  82. const editable = !viewOnly.value;
  83. const showPoint = !viewOnly.value;
  84. drawRegionMap.initMap(point, mapContainer.value, editable, true, showPoint);
  85. applyRegionStyles();
  86. });
  87. onActivated(async () => {
  88. const point = route.query.mapCenter || DEFAULT_MAP_CENTER;
  89. await fetchRegionInfo();
  90. syncMapEditableState(point);
  91. const polygonData = route.query.polygonData;
  92. const rawRangeWkt = route.query.rangeWkt;
  93. const rangeWkt = rawRangeWkt ? decodeURIComponent(rawRangeWkt) : null;
  94. const shouldRenderFromApi = showDataMode.value && !rangeWkt && !polygonData;
  95. applyRegionStyles();
  96. if (shouldRenderFromApi) {
  97. renderRegionsFromApi();
  98. }
  99. if (rangeWkt) {
  100. renderRegionsFromRouteRangeWkt(rangeWkt);
  101. }
  102. restoreEditablePolygonFromRoute(polygonData);
  103. updateMapCenterForEditMode(point);
  104. applyRegionStyles();
  105. });
  106. const regionTypeTabs = ref([]);
  107. const activeRegionType = ref("variety");
  108. const regionInfo = ref([]);
  109. const formatDateToYmdDash = (raw) => {
  110. const sourceDate = raw ? new Date(raw) : new Date();
  111. const resolvedDate = Number.isNaN(sourceDate.getTime()) ? new Date() : sourceDate;
  112. const y = resolvedDate.getFullYear();
  113. const m = String(resolvedDate.getMonth() + 1).padStart(2, "0");
  114. const d = String(resolvedDate.getDate()).padStart(2, "0");
  115. return `${y}-${m}-${d}`;
  116. };
  117. const isValidGeomWkt = (geom) => {
  118. const text = String(geom || "").trim();
  119. return text.length > 10 && (text.includes("POLYGON") || text.includes("MULTIPOLYGON"));
  120. };
  121. const isTreatmentOrControlledStatus = (status) => {
  122. const normalizedStatus = String(status || "").trim();
  123. return normalizedStatus === "2" || normalizedStatus === "3";
  124. };
  125. /**
  126. * 将不同入口(接口回显/路由透传)的几何数据统一映射为地图组件可消费的数据结构,
  127. * 避免散落在各处拼装导致字段不一致。
  128. */
  129. const buildRegionBasePayload = (
  130. geometry,
  131. regionStyleKind,
  132. reproductiveName,
  133. updatedTime,
  134. handleStatus,
  135. lockStyleType = "",
  136. label = ""
  137. ) => {
  138. if (!isValidGeomWkt(geometry)) return null;
  139. const hasTreatmentStatus = isTreatmentOrControlledStatus(handleStatus);
  140. const shouldUseLockedDiseaseStyle = regionStyleKind === "ABNORMAL" && hasTreatmentStatus && !!lockStyleType;
  141. return {
  142. geometry: String(geometry).trim(),
  143. status: "unresolved",
  144. regionStyleKind,
  145. reproductiveName,
  146. updatedTime,
  147. displayMode: shouldUseLockedDiseaseStyle ? "lockedDisease" : "",
  148. handleStatus: hasTreatmentStatus ? String(handleStatus).trim() : "",
  149. lockStyleType: shouldUseLockedDiseaseStyle ? lockStyleType : "",
  150. label,
  151. };
  152. };
  153. const buildAbnormalLabel = (name, handleStatus) => {
  154. const status = String(handleStatus || "").trim();
  155. const isTreatingOrControlled = isTreatmentOrControlledStatus(status);
  156. const prefix = name.includes("虫害")
  157. ? "虫害"
  158. : name.includes("病害")
  159. ? "病害"
  160. : name.includes("过快")
  161. ? "长势过快"
  162. : name.includes("过慢")
  163. ? "长势过慢"
  164. : "";
  165. if (!prefix) return "";
  166. if (isTreatingOrControlled) {
  167. return status === "3" ? `${prefix}已控制` : `${prefix}治疗中`;
  168. }
  169. return `新增${prefix}`;
  170. };
  171. const buildShowDataRegionsFromApi = () => {
  172. const currentTab = (varietyTabs.value || [])[activeVariety.value] || {};
  173. if (!currentTab) return [];
  174. const styleKind = getCanonicalRegionTypeForStyles();
  175. const reproductiveName = String(currentTab.problemZoneTypeName || currentTab.regionName || "");
  176. const isAbnormal = styleKind === "ABNORMAL";
  177. const geomItems = Array.isArray(currentTab.geomItems) ? currentTab.geomItems : [];
  178. const regions = [];
  179. geomItems.forEach((item) => {
  180. const geometry = String(item?.geomWkt || "").trim();
  181. if (!isValidGeomWkt(geometry)) return;
  182. const handleStatus = String(item?.handleStatus ?? "").trim();
  183. const hasTreatmentStatus = isTreatmentOrControlledStatus(handleStatus);
  184. const isGrowthAbnormal = reproductiveName.includes("过慢") || reproductiveName.includes("过快");
  185. const region = buildRegionBasePayload(
  186. geometry,
  187. styleKind,
  188. reproductiveName,
  189. formatDateToYmdDash(item?.createTime || currentTab?.createTime),
  190. handleStatus,
  191. isAbnormal && hasTreatmentStatus
  192. ? (handleStatus === "3" ? "controlled" : (isGrowthAbnormal ? "growthTreating" : "diseaseTreating"))
  193. : "",
  194. isAbnormal ? buildAbnormalLabel(reproductiveName, handleStatus) : ""
  195. );
  196. if (region) regions.push(region);
  197. });
  198. if (regions.length > 0) return regions;
  199. const fallbackGeom = String(currentTab.geom || "").trim();
  200. if (!isValidGeomWkt(fallbackGeom)) return [];
  201. const fallbackRegion = buildRegionBasePayload(
  202. fallbackGeom,
  203. styleKind,
  204. reproductiveName,
  205. formatDateToYmdDash(currentTab?.createTime),
  206. "",
  207. "",
  208. isAbnormal ? buildAbnormalLabel(reproductiveName, "") : ""
  209. );
  210. return fallbackRegion ? [fallbackRegion] : [];
  211. };
  212. const fitAllRegionsWhenViewOnly = () => {
  213. if (viewOnly.value && drawRegionMap.fitAllRegions) {
  214. drawRegionMap.fitAllRegions();
  215. }
  216. };
  217. const renderRegionsFromApi = () => {
  218. const apiRegions = buildShowDataRegionsFromApi();
  219. if (!apiRegions.length) return;
  220. drawRegionMap.setStatusRegions(apiRegions);
  221. fitAllRegionsWhenViewOnly();
  222. };
  223. /**
  224. * 路由可能传 JSON(geometryArr)或单条 WKT 字符串,这里统一转换为 regions。
  225. * 该函数只负责“解析+映射”,不关心地图渲染,便于后续复用和测试。
  226. */
  227. const buildRegionsFromRouteRangeWkt = (rangeWkt) => {
  228. const regionStyleKind = getCanonicalRegionTypeForStyles();
  229. const currentVarietyTab = (varietyTabs.value || [])[activeVariety.value] || {};
  230. // 异常区名称有时不会从路由透传,补充当前 tab 兜底,避免标签回退为“病害治疗中”
  231. const reproductiveName = String(
  232. route.query.reproductiveName ||
  233. route.query.problemZoneTypeName ||
  234. currentVarietyTab.problemZoneTypeName ||
  235. currentVarietyTab.regionName ||
  236. ""
  237. );
  238. const isAbnormal = regionStyleKind === "ABNORMAL";
  239. const routeHandleStatus = String(route.query.handleStatus || "").trim();
  240. const hasTreatmentStatus = isTreatmentOrControlledStatus(routeHandleStatus);
  241. const isGrowthAbnormal =
  242. isAbnormal && (reproductiveName.includes("长势") || reproductiveName.includes("过慢") || reproductiveName.includes("过快"));
  243. const abnormalLabel =
  244. !isAbnormal
  245. ? ""
  246. : reproductiveName.includes("病害")
  247. ? "新增病害"
  248. : reproductiveName.includes("虫害")
  249. ? "新增虫害"
  250. : reproductiveName.includes("过慢")
  251. ? "新增长势过慢"
  252. : reproductiveName.includes("过快")
  253. ? "新增长势过快"
  254. : "";
  255. const lockStyleType = !isAbnormal || !hasTreatmentStatus
  256. ? ""
  257. : (isGrowthAbnormal ? "growthTreating" : "diseaseTreating");
  258. const toRegionPayload = (geometryText) => buildRegionBasePayload(
  259. geometryText,
  260. regionStyleKind,
  261. reproductiveName,
  262. route.query.updatedTime,
  263. routeHandleStatus,
  264. lockStyleType,
  265. abnormalLabel
  266. );
  267. try {
  268. const parsed = JSON.parse(rangeWkt);
  269. if (parsed && Array.isArray(parsed.geometryArr)) {
  270. return parsed.geometryArr
  271. .map((item) => toRegionPayload(String(item || "").trim()))
  272. .filter(Boolean);
  273. }
  274. } catch (_) {
  275. // 非 JSON 透传时,按单条 WKT 处理
  276. }
  277. if (typeof rangeWkt === "string" && rangeWkt.trim().length > 10) {
  278. const region = toRegionPayload(rangeWkt.trim());
  279. return region ? [region] : [];
  280. }
  281. return [];
  282. };
  283. const renderRegionsFromRouteRangeWkt = (rangeWkt) => {
  284. const regions = buildRegionsFromRouteRangeWkt(rangeWkt);
  285. if (!regions.length) return;
  286. drawRegionMap.setStatusRegions(regions);
  287. fitAllRegionsWhenViewOnly();
  288. };
  289. const restoreEditablePolygonFromRoute = (polygonData) => {
  290. if (viewOnly.value || !polygonData) return;
  291. drawRegionMap.setAreaGeometry(
  292. JSON.parse(polygonData)?.geometryArr,
  293. false,
  294. undefined,
  295. undefined,
  296. getAbnormalGrowthOverlayMeta()
  297. );
  298. };
  299. const updateMapCenterForEditMode = (point) => {
  300. // 查看模式通常会通过 fitAllRegions 自适应,不主动重置中心,避免打断用户缩放视角
  301. if (viewOnly.value) return;
  302. drawRegionMap.setMapPosition(convertPointToArray(point));
  303. };
  304. /**
  305. * 页面从 keep-alive 恢复时,如果查看态和编辑态发生切换,需要重建地图实例。
  306. * 仅在状态不一致时重建,避免每次激活都销毁重建带来的闪烁和性能开销。
  307. */
  308. const syncMapEditableState = (point) => {
  309. if (!drawRegionMap.kmap) return;
  310. const shouldEditable = !viewOnly.value;
  311. if (drawRegionMap.editable === shouldEditable) return;
  312. drawRegionMap.destroyMap();
  313. drawRegionMap.initMap(point, mapContainer.value, shouldEditable, true, shouldEditable);
  314. };
  315. async function fetchRegionInfo() {
  316. const subjectId = route.query.subjectId || localStorage.getItem('selectedFarmId');
  317. const { data } = await VE_API.basic_farm.fetchRegionInfo({ subjectId });
  318. if (data && data.length > 0) {
  319. regionInfo.value = data[0] || [];
  320. regionTypeTabs.value = regionInfo.value.problemZoneList || [];
  321. regionTypeTabs.value.unshift({ name: "品种区", code: "variety" });
  322. varietyTabs.value = regionInfo.value.regionList || [];
  323. activeVariety.value = 0;
  324. if (route.query.firstAct) {
  325. activeRegionType.value = route.query.firstAct;
  326. if (route.query.firstAct === "variety") {
  327. varietyTabs.value = regionInfo.value.regionList || [];
  328. const index = Number(route.query.secondAct);
  329. activeVariety.value = Number.isInteger(index) && index >= 0 ? index : 0;
  330. return;
  331. }
  332. const matchedGroup = (regionInfo.value.problemZoneList || []).find(
  333. (item) => String(item?.code) === String(route.query.firstAct)
  334. );
  335. if (matchedGroup) {
  336. varietyTabs.value = matchedGroup.children || [];
  337. const index = Number(route.query.secondAct);
  338. activeVariety.value = Number.isInteger(index) && index >= 0 ? index : 0;
  339. }
  340. }
  341. if (activeVariety.value >= varietyTabs.value.length) {
  342. activeVariety.value = 0;
  343. }
  344. }
  345. }
  346. const varietyTabs = ref([]);
  347. const activeVariety = ref(0);
  348. /** 样式用的大类:与接口 tab.code 解耦(避免 ABNORMAL / 数字 code 等导致勾画色落到默认灰) */
  349. const getCanonicalRegionTypeForStyles = () => {
  350. const raw = activeRegionType.value;
  351. if (raw === "variety") return "variety";
  352. const tabs = regionTypeTabs.value || [];
  353. const item = tabs.find((t) => String(t?.code) === String(raw));
  354. if (item) {
  355. const kind = item.code;
  356. if (kind) return kind;
  357. }
  358. return "SLEEP";
  359. };
  360. const ABNORMAL_BADGE_BG_DISEASE_PEST = "#E32A28";
  361. const ABNORMAL_BADGE_BG_GROWTH = "#F76F00";
  362. /** 异常区小类(长势/病害/虫害等)闭合地块后在多边形内展示标签与发现日期 */
  363. const getAbnormalGrowthOverlayMeta = () => {
  364. if (getCanonicalRegionTypeForStyles() !== "ABNORMAL") return null;
  365. const tab = varietyTabs.value?.[activeVariety.value];
  366. if (!tab) return null;
  367. const name = (tab.problemZoneTypeName || tab.regionName || "").toString();
  368. let badgeText = "";
  369. let badgeBackground = ABNORMAL_BADGE_BG_GROWTH;
  370. if (name.includes("病害")) {
  371. badgeText = "新增病害";
  372. badgeBackground = ABNORMAL_BADGE_BG_DISEASE_PEST;
  373. } else if (name.includes("虫害")) {
  374. badgeText = "新增虫害";
  375. badgeBackground = ABNORMAL_BADGE_BG_DISEASE_PEST;
  376. } else if (name.includes("过慢")) {
  377. badgeText = "新增长势过慢";
  378. } else if (name.includes("过快")) {
  379. badgeText = "新增长势过快";
  380. } else {
  381. return null;
  382. }
  383. const now = new Date();
  384. const y = now.getFullYear();
  385. const m = String(now.getMonth() + 1).padStart(2, "0");
  386. const d = String(now.getDate()).padStart(2, "0");
  387. return { badgeText, discoveryDate: `${y}.${m}.${d}`, badgeBackground };
  388. };
  389. const createPolygonStyleFunc = (fillColor, strokeColor) => {
  390. return (feature) => {
  391. const styles = [];
  392. const coord = feature.getGeometry().getCoordinates()[0];
  393. for (let i = 0; i < coord[0].length - 1; i++) {
  394. if (i % 2) {
  395. styles.push(
  396. new Style({
  397. geometry: new Point(coord[0][i]),
  398. image: new Circle({
  399. radius: 4,
  400. fill: new Fill({
  401. color: strokeColor,
  402. }),
  403. stroke: new Stroke({
  404. color: "#fff",
  405. width: 1,
  406. }),
  407. }),
  408. })
  409. );
  410. } else {
  411. styles.push(
  412. new Style({
  413. geometry: new Point(coord[0][i]),
  414. image: new Circle({
  415. radius: 6,
  416. fill: new Fill({
  417. color: "#fff",
  418. }),
  419. }),
  420. })
  421. );
  422. }
  423. }
  424. const fillStyle = new Style({
  425. fill: new Fill({
  426. color: fillColor,
  427. }),
  428. stroke: new Stroke({
  429. color: strokeColor,
  430. width: 2,
  431. }),
  432. });
  433. let geom = feature.getGeometry().clone();
  434. geom.transform(proj.get("EPSG:4326"), proj.get("EPSG:38572"));
  435. let area = getArea(geom);
  436. area = (area + area / 2) / 1000;
  437. const growth = getAbnormalGrowthOverlayMeta();
  438. if (growth) {
  439. styles.push(
  440. new Style({
  441. text: new Text({
  442. text: growth.badgeText,
  443. font: "bold 13px sans-serif",
  444. fill: new Fill({ color: "#ffffff" }),
  445. backgroundFill: new Fill({ color: growth.badgeBackground || ABNORMAL_BADGE_BG_GROWTH }),
  446. padding: [4, 10, 4, 10],
  447. offsetY: -40,
  448. }),
  449. }),
  450. new Style({
  451. text: new Text({
  452. text: `发现时间:${growth.discoveryDate}`,
  453. font: "12px sans-serif",
  454. fill: new Fill({ color: "#ffffff" }),
  455. offsetY: -16,
  456. }),
  457. })
  458. );
  459. }
  460. const areaValStyle = new Style({
  461. text: new Text({
  462. font: "16px sans-serif",
  463. text: area.toFixed(2) + "亩",
  464. fill: new Fill({ color: "#fff" }),
  465. offsetY: growth ? 14 : 0,
  466. }),
  467. });
  468. styles.push(fillStyle, areaValStyle);
  469. return styles;
  470. };
  471. };
  472. const applyRegionStyles = () => {
  473. const kmap = drawRegionMap.kmap;
  474. if (!kmap) return;
  475. let lineColor = "#2199F8";
  476. let vertexColor = "#2199F8";
  477. let fillColor = [0, 0, 0, 0.5];
  478. let strokeColor = "#2199F8";
  479. const styleKind = getCanonicalRegionTypeForStyles();
  480. if (styleKind === "variety") {
  481. lineColor = "#18AA8B";
  482. vertexColor = "#18AA8B";
  483. fillColor = [0, 57, 44, 0.5];
  484. strokeColor = "#18AA8B";
  485. } else if (styleKind === "ABNORMAL") {
  486. if (activeVariety.value < 2) {
  487. lineColor = "#E03131";
  488. vertexColor = "#E03131";
  489. fillColor = [100, 0, 0, 0.5];
  490. strokeColor = "#E03131";
  491. } else {
  492. lineColor = "#FF7300";
  493. vertexColor = "#FF7300";
  494. fillColor = [124, 46, 0, 0.5];
  495. strokeColor = "#FF7300";
  496. }
  497. } else if (styleKind === "ENVIRONMENT") {
  498. lineColor = "#FDCF7F";
  499. vertexColor = "#FDCF7F";
  500. fillColor = [151, 96, 0, 0.5];
  501. strokeColor = "#FDCF7F";
  502. } else {
  503. lineColor = "#A6A6A6";
  504. vertexColor = "#A6A6A6";
  505. fillColor = [166, 166, 166, 0.25];
  506. strokeColor = "#A6A6A6";
  507. }
  508. KMapMap.drawStyleColors = {
  509. line: lineColor,
  510. vertex: vertexColor,
  511. fill: fillColor,
  512. stroke: strokeColor,
  513. };
  514. kmap.polygonStyle = createPolygonStyleFunc(fillColor, strokeColor);
  515. if (kmap.polygonLayer?.layer && typeof kmap.polygonLayer.layer.setStyle === "function") {
  516. kmap.polygonLayer.layer.setStyle(kmap.polygonStyle);
  517. }
  518. };
  519. onDeactivated(() => {
  520. drawRegionMap.clearLayer()
  521. })
  522. const goBack = () => {
  523. // drawRegionMap.clearLayer()
  524. router.back()
  525. };
  526. const deletePolygon = () => {
  527. ElMessageBox.confirm(
  528. '确认要删除当前地块吗?删除后可以重新勾画。',
  529. '删除确认',
  530. {
  531. confirmButtonText: '确认删除',
  532. cancelButtonText: '取消',
  533. type: 'warning',
  534. }
  535. ).then(() => {
  536. drawRegionMap.abortOngoingDrawSketch();
  537. if (drawRegionMap.kmap && drawRegionMap.kmap.polygonLayer && drawRegionMap.kmap.polygonLayer.source) {
  538. drawRegionMap.kmap.polygonLayer.source.clear();
  539. }
  540. ElMessage.success({ message: t('地块已删除'), type: 'success' });
  541. }).catch(() => {
  542. // 用户取消删除,不做任何操作
  543. });
  544. };
  545. const saveAndBack = () => {
  546. const polygonData = drawRegionMap.getAreaGeometry();
  547. const subjectId = route.query.subjectId || localStorage.getItem("selectedFarmId") || "";
  548. const geometryArr = Array.isArray(polygonData?.geometryArr)
  549. ? polygonData.geometryArr
  550. .map((g) => (g == null ? "" : String(g).trim()))
  551. .filter((g) => g.length > 10)
  552. : [];
  553. const geom = geometryArr[0] || "";
  554. const currentGroup = (regionTypeTabs.value || []).find(
  555. (item) => String(item?.code) === String(activeRegionType.value)
  556. );
  557. const currentTab = (varietyTabs.value || [])[activeVariety.value] || {};
  558. const regionList =
  559. activeRegionType.value === "variety" && geom
  560. ? [
  561. {
  562. regionId: currentTab.regionId ?? currentTab.id ?? "",
  563. typeId: currentTab.typeId ?? "",
  564. regionName: currentTab.regionName ?? currentTab.problemZoneTypeName ?? "",
  565. geom,
  566. },
  567. ]
  568. : [];
  569. const problemZoneList =
  570. activeRegionType.value !== "variety" && geom
  571. ? [
  572. {
  573. name: currentGroup?.name ?? "",
  574. code: currentGroup?.code ?? activeRegionType.value,
  575. children: [
  576. {
  577. farmSubjectId: subjectId,
  578. handleStatus: 1,
  579. createTime: new Date().toISOString(),
  580. problemZoneTypeId: currentTab.problemZoneTypeId ?? currentTab.typeId ?? "",
  581. problemZoneTypeName: currentTab.problemZoneTypeName ?? currentTab.regionName ?? "",
  582. parentName: currentGroup?.name ?? "",
  583. parentCode: currentGroup?.code ?? activeRegionType.value,
  584. geomItems: [{ geomWkt: geom, remark: "" }],
  585. },
  586. ],
  587. },
  588. ]
  589. : [];
  590. const params = {
  591. subjectId,
  592. regionList,
  593. problemZoneList,
  594. };
  595. sessionStorage.setItem("drawRegionPolygonData", JSON.stringify(polygonData));
  596. sessionStorage.setItem("drawRegionSubmitParams", JSON.stringify(params));
  597. if (selectedAbnormalType.value) {
  598. sessionStorage.setItem("drawRegionAbnormalType", selectedAbnormalType.value);
  599. } else {
  600. sessionStorage.removeItem("drawRegionAbnormalType");
  601. }
  602. router.back();
  603. };
  604. const handleConfirmUpload = () => {
  605. if (!selectedAbnormalType.value) {
  606. ElMessage.warning({ message: t('请选择异常类型'), type: 'warning' });
  607. return;
  608. }
  609. showAbnormalTypePopup.value = false;
  610. saveAndBack();
  611. };
  612. const confirm = () => {
  613. if (getCanonicalRegionTypeForStyles() === "ABNORMAL") {
  614. showAbnormalTypePopup.value = true;
  615. return;
  616. }
  617. saveAndBack();
  618. };
  619. </script>
  620. <style lang="scss" scoped>
  621. .edit-map {
  622. width: 100%;
  623. height: 100vh;
  624. overflow: hidden;
  625. .region-type-tabs {
  626. display: flex;
  627. align-items: center;
  628. background: #f4f4f4;
  629. margin: 10px 10px 0;
  630. padding: 3px;
  631. border-radius: 4px;
  632. box-sizing: border-box;
  633. .region-type-tab {
  634. flex: 1;
  635. text-align: center;
  636. padding: 5px 0;
  637. color: #767676;
  638. }
  639. .region-type-tab--active {
  640. background: #ffffff;
  641. border-radius: 4px;
  642. color: #0D0D0D;
  643. }
  644. }
  645. .variety-tabs {
  646. display: flex;
  647. align-items: center;
  648. gap: 8px;
  649. padding: 10px 12px 0;
  650. overflow-x: auto;
  651. overflow-y: hidden;
  652. flex-wrap: nowrap;
  653. -webkit-overflow-scrolling: touch;
  654. .variety-tab {
  655. padding: 4px 12px;
  656. border-radius: 2px;
  657. color: #575757;
  658. background: #F4F4F4;
  659. border: 1px solid transparent;
  660. white-space: nowrap;
  661. }
  662. .variety-tab--active {
  663. background: rgba(33, 153, 248, 0.1);
  664. color: #2199F8;
  665. border: 1px solid #2199F8;
  666. }
  667. }
  668. .edit-map-content {
  669. width: 100%;
  670. height: calc(100% - 96px);
  671. margin-top: 10px;
  672. position: relative;
  673. .edit-map-tip {
  674. position: absolute;
  675. top: 23px;
  676. left: calc(50% - 256px / 2);
  677. z-index: 1;
  678. font-size: 12px;
  679. color: #fff;
  680. padding: 9px 20px;
  681. background: rgba(0, 0, 0, 0.5);
  682. border-radius: 20px;
  683. }
  684. .map-container {
  685. width: 100%;
  686. height: 100%;
  687. }
  688. .edit-map-footer {
  689. position: absolute;
  690. bottom: 85px;
  691. left: 12px;
  692. width: calc(100% - 24px);
  693. display: flex;
  694. flex-direction: column;
  695. align-items: flex-end;
  696. .footer-back {
  697. padding: 6px 7px 9px;
  698. background: #fff;
  699. border-radius: 8px;
  700. margin-bottom: 30px;
  701. .back-icon {
  702. width: 20px;
  703. height: 18px;
  704. }
  705. }
  706. .edit-map-footer-btn {
  707. display: flex;
  708. justify-content: center;
  709. align-items: center;
  710. width: 100%;
  711. gap: 8px;
  712. div {
  713. flex: 1;
  714. max-width: 100px;
  715. text-align: center;
  716. color: #666666;
  717. font-size: 14px;
  718. padding: 8px 0;
  719. border-radius: 25px;
  720. background: #fff;
  721. }
  722. .btn-delete {
  723. background: #ff4d4f;
  724. color: #fff;
  725. }
  726. .btn-confirm {
  727. background: #000;
  728. background-image: linear-gradient(180deg, #76c3ff 0%, #2199f8 100%);
  729. color: #fff;
  730. }
  731. }
  732. }
  733. }
  734. }
  735. .abnormal-popup {
  736. width: 100%;
  737. ::v-deep {
  738. .van-popup__close-icon {
  739. color: #000;
  740. }
  741. }
  742. .abnormal-popup-content {
  743. background: linear-gradient(180deg, #d9ecff 0%, #ffffff 60%);
  744. border-radius: 18px;
  745. padding: 24px 16px;
  746. box-sizing: border-box;
  747. position: relative;
  748. .abnormal-popup-title {
  749. font-size: 16px;
  750. margin-bottom: 12px;
  751. }
  752. .abnormal-type-select {
  753. width: 100%;
  754. }
  755. .abnormal-popup-confirm {
  756. margin-top: 24px;
  757. border-radius: 25px;
  758. padding: 8px;
  759. background: #2199F8;
  760. color: #fff;
  761. font-size: 16px;
  762. display: flex;
  763. align-items: center;
  764. justify-content: center;
  765. }
  766. }
  767. }
  768. </style>