index.vue 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043
  1. <template>
  2. <div class="create-farm">
  3. <custom-header :name="paramsType === 'client' ? '新增用户' : paramsType === 'edit' ? '编辑农场' : '创建农场'"
  4. :isGoBack="true" @goback="backgToHome"></custom-header>
  5. <!-- 地图 -->
  6. <div class="map-container" ref="mapContainer"></div>
  7. <div class="farm-content">
  8. <div class="top-mask"></div>
  9. <div class="farm-filter">
  10. <el-select v-model="locationVal" filterable remote reserve-keyword :placeholder="t('搜索位置')"
  11. :remote-method="remoteMethod" :loading="loading" @change="handleSearchRes"
  12. popper-class="location-search-popper">
  13. <el-option v-for="(item, index) in locationOptions.list" :key="index" :label="item.title"
  14. :value="{ value: item.point, item }">
  15. <span>{{ item.title }}</span>
  16. <span class="sub-title">{{ item.province }}{{ item.city }}{{ item.district || '' }}</span>
  17. </el-option>
  18. </el-select>
  19. </div>
  20. <!-- 创建 -->
  21. <div class="create-wrap">
  22. <div class="create-box">
  23. <div class="box-content">
  24. <div class="create-title">
  25. <img class="title-icon" src="@/assets/img/home/create-icon.png" alt="" />
  26. {{ paramsType === "client" ? "新增用户" : paramsType === "edit" ? "编辑农场" : "创建农场" }}
  27. </div>
  28. <div class="create-content">
  29. <div class="create-from">
  30. <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" class="demo-ruleForm">
  31. <el-form-item :label="t('农场位置')" prop="farm_address">
  32. <div class="position-wrap">
  33. <el-input :placeholder="t('农场位置')" readonly v-model="ruleForm.farm_address"
  34. autocomplete="off" />
  35. </div>
  36. </el-form-item>
  37. <el-form-item :label="t('种植作物')" required>
  38. <div class="select-wrap">
  39. <div class="species-entry" @click="handleGoSelectCrop">
  40. <span class="species-entry__text">{{ selectedCropSummaryText || "点击选择作物" }}</span>
  41. </div>
  42. </div>
  43. </el-form-item>
  44. <el-form-item :label="t('农场面积')" prop="farm_area">
  45. <div class="area-box">
  46. <el-input :placeholder="isFromEditMap ? '勾选地块获得农场面积' : '请输入农场的真实面积'
  47. " v-model="ruleForm.farm_area" :readonly="isFromEditMap" type="text"
  48. autocomplete="off" style="width: fit-content" @input="handleMianjiInput"
  49. @keypress="handleMianjiKeypress" />
  50. <div class="unit">{{ t('亩') }}</div>
  51. </div>
  52. </el-form-item>
  53. <el-form-item :label="t('农场名称')" prop="farm_name">
  54. <el-input :placeholder="t('请输入您的农场名称')" v-model="ruleForm.farm_name"
  55. autocomplete="off" @input="handleFarmNameInput" />
  56. </el-form-item>
  57. </el-form>
  58. </div>
  59. <div class="create-btn">
  60. <div class="btn-item sencond-btn" @click="resetForm(ruleFormRef)">{{ t('取消') }}</div>
  61. <div
  62. class="btn-item primary-btn"
  63. :class="{ 'is-disabled': isSubmitting }"
  64. @click="submitForm(ruleFormRef)"
  65. >
  66. {{
  67. isSubmitting
  68. ? t('提交中...')
  69. : paramsType === "client"
  70. ? "添加"
  71. : paramsType === "edit"
  72. ? "确认修改"
  73. : "立即创建"
  74. }}
  75. </div>
  76. </div>
  77. </div>
  78. </div>
  79. </div>
  80. </div>
  81. </div>
  82. <!-- 四大种植报告生成成功 -->
  83. <Popup v-model:show="showPlantingReportPopup" round class="planting-report-popup"
  84. :close-on-click-overlay="false">
  85. <div class="planting-report-popup__inner">
  86. <img class="icon" src="@/assets/img/home/right.png" alt="" />
  87. <div class="title">{{ t('您的四大种植报告') }}<br />{{ t('已全部生成') }}</div>
  88. <div class="links">
  89. <span class="link">{{ t('(作物长势报告)') }}</span>
  90. <span class="link">{{ t('(土壤改良报告)') }}</span>
  91. <span class="link">{{ t('(种植建议报告)') }}</span>
  92. </div>
  93. <div class="btn" @click="handlePlantingReportView">{{ t('点击查看') }}</div>
  94. </div>
  95. </Popup>
  96. </div>
  97. </template>
  98. <script setup>
  99. import { useI18n } from "@/i18n";
  100. const { t } = useI18n();
  101. import customHeader from "@/components/customHeader.vue";
  102. import IndexMap from "./map/index.js";
  103. import { useRoute, useRouter } from "vue-router";
  104. import { mapLocation } from "./map/index.js";
  105. import { onMounted, ref, reactive, watch, onActivated, nextTick, onDeactivated } from "vue";
  106. import { useStore } from "vuex";
  107. import { convertPointToArray } from "@/utils/index";
  108. import wx from "weixin-js-sdk";
  109. import { Popup } from "vant";
  110. import { ElMessage } from "element-plus";
  111. import { transformFromGCJToWGS, transformFromWGSToGCJ } from "@/utils/WSCoordinate.js";
  112. import { selectNewlyCreatedFarm } from "@/utils/selectedFarm";
  113. /** 与 selectCrop.vue 写入的 sessionStorage 键一致 */
  114. const SESSION_SELECT_CROP_KEY = "selectedCrop";
  115. /** @returns {Array<object>|null} 已选作物品类列表,未选择或数据无效时为 null */
  116. function parseSelectedCropItems() {
  117. try {
  118. const raw = sessionStorage.getItem(SESSION_SELECT_CROP_KEY);
  119. if (!raw || raw === "null") return null;
  120. const data = JSON.parse(raw);
  121. if (!Array.isArray(data) || data.length === 0) return null;
  122. return data;
  123. } catch {
  124. return null;
  125. }
  126. }
  127. /** 入口展示:无选中为「点击选择作物」,有则 variety_name 去重后用顿号连接 */
  128. const selectedCropSummaryText = ref("");
  129. function refreshSelectedCropSummary() {
  130. const items = parseSelectedCropItems();
  131. if (!items?.length) {
  132. selectedCropSummaryText.value = "";
  133. return;
  134. }
  135. const seen = new Set();
  136. const ordered = [];
  137. for (const item of items) {
  138. const name = String(item.variety_name ?? "").trim();
  139. if (!name || seen.has(name)) continue;
  140. seen.add(name);
  141. ordered.push(name);
  142. }
  143. selectedCropSummaryText.value = ordered.join("、");
  144. }
  145. const route = useRoute();
  146. const router = useRouter();
  147. const store = useStore();
  148. const indexMap = new IndexMap();
  149. const mapContainer = ref(null);
  150. /** 创建成功后「四大种植报告」提示弹窗 */
  151. const showPlantingReportPopup = ref(false);
  152. function handlePlantingReportView() {
  153. showPlantingReportPopup.value = false;
  154. backgToHome();
  155. }
  156. // 标记是否从编辑地图页面确认返回
  157. const isFromEditMap = ref(false);
  158. // 标记用户是否手动修改过农场名称
  159. const isFarmNameManuallyModified = ref(false);
  160. /** 创建/提交接口请求中,防止重复点击 */
  161. const isSubmitting = ref(false);
  162. /**
  163. * 根据中心点和亩数生成正方形地块WKT
  164. * @param {Array} center - 中心点坐标 [lng, lat]
  165. * @param {Number} mu - 面积(亩)
  166. * @returns {Object} 包含WKT字符串和面积(亩)的对象
  167. */
  168. function generateSquarePolygonByMu(center, mu) {
  169. // 确保输入是数字类型
  170. const lng = parseFloat(center[0]);
  171. const lat = parseFloat(center[1]);
  172. // 1亩 ≈ 666.67平方米
  173. const areaInSquareMeters = mu * 666.67;
  174. // 正方形边长(米)
  175. const sideLength = Math.sqrt(areaInSquareMeters);
  176. // 半边长(米)
  177. const halfSide = sideLength / 2;
  178. // 纬度方向:1度约等于111000米
  179. const latDelta = halfSide / 111000;
  180. // 经度方向:需要根据纬度调整,1度约等于111000 * cos(lat)米
  181. const lngDelta = halfSide / (111000 * Math.cos((lat * Math.PI) / 180));
  182. // 计算四个顶点(逆时针顺序)
  183. const topLeft = [lng - lngDelta, lat + latDelta];
  184. const topRight = [lng + lngDelta, lat + latDelta];
  185. const bottomRight = [lng + lngDelta, lat - latDelta];
  186. const bottomLeft = [lng - lngDelta, lat - latDelta];
  187. // 生成MULTIPOLYGON格式的WKT(需要闭合,所以第一个点要重复)
  188. const formatPoint = (point) => `${point[0]} ${point[1]}`;
  189. const coordinates = [topLeft, topRight, bottomRight, bottomLeft, topLeft].map(formatPoint).join(", ");
  190. // 注意:MULTIPOLYGON 和括号之间需要有一个空格
  191. const wkt = `MULTIPOLYGON (((${coordinates})))`;
  192. return { wkt, area: parseFloat(mu).toFixed(2) };
  193. }
  194. onMounted(() => {
  195. // 清除上一次的地块数据,确保每次进入都是全新状态
  196. store.commit("home/SET_FARM_POLYGON", null);
  197. isFromEditMap.value = false; // 初始化时可以手动输入
  198. centerPoint.value = store.state.home.miniUserLocationPoint;
  199. indexMap.initMap(centerPoint.value, mapContainer.value);
  200. // 不再初始化时绘制默认地块,等待用户点击"新增地块"按钮
  201. // 清空地块和面积数据
  202. polygonArr.value = null;
  203. ruleForm.farm_area = "";
  204. if (route.query.type === "edit" && store.state.home.editFarmData) {
  205. populateEditData();
  206. }
  207. refreshSelectedCropSummary();
  208. });
  209. const polygonArr = ref(null);
  210. const paramsType = ref(null);
  211. /** 全新创建:带 isReload,且非编辑/小程序回流 */
  212. function isCreateFarmFullReload() {
  213. return (
  214. route.query.isReload &&
  215. route.query.type !== "edit" &&
  216. !route.query.miniJson
  217. );
  218. }
  219. onActivated(() => {
  220. paramsType.value = route.query.type;
  221. if (isCreateFarmFullReload()) {
  222. // 先清缓存与位置状态,避免沿用上次搜索的 centerPoint / 地址
  223. sessionStorage.removeItem("centerPoint");
  224. centerPoint.value = store.state.home.miniUserLocationPoint;
  225. locationVal.value = null;
  226. locationOptions.list = [];
  227. pointAddress.value = null;
  228. farmCity.value = null;
  229. polygonArr.value = null;
  230. isFromEditMap.value = false;
  231. isFarmNameManuallyModified.value = false;
  232. ruleForm.farm_address = "";
  233. ruleForm.farm_area = "";
  234. ruleForm.farm_name = "";
  235. ruleFormRef.value?.resetFields();
  236. store.commit("home/SET_FARM_POLYGON", null);
  237. isSubmitting.value = false;
  238. } else {
  239. const centerPointVal = sessionStorage.getItem("centerPoint")
  240. ? JSON.parse(sessionStorage.getItem("centerPoint"))
  241. : null;
  242. centerPoint.value = centerPointVal || store.state.home.miniUserLocationPoint;
  243. const arr = convertPointToArray(centerPoint.value);
  244. getLocationName(`${arr[1]},${arr[0]}`);
  245. }
  246. // 确保地图已初始化,使用 nextTick 等待 DOM 更新
  247. nextTick(() => {
  248. // 检查地图实例是否已初始化
  249. if (!indexMap.kmap) {
  250. // 如果地图未初始化,重新初始化
  251. if (mapContainer.value) {
  252. centerPoint.value = store.state.home.miniUserLocationPoint;
  253. const arr = convertPointToArray(centerPoint.value);
  254. indexMap.initMap(centerPoint.value, mapContainer.value);
  255. }
  256. // 等待地图初始化完成后再继续
  257. setTimeout(() => {
  258. handleMapUpdate();
  259. }, 100);
  260. return;
  261. }
  262. handleMapUpdate();
  263. });
  264. refreshSelectedCropSummary();
  265. });
  266. onDeactivated(() => {
  267. sessionStorage.setItem('centerPoint', JSON.stringify(centerPoint.value));
  268. });
  269. // 处理地图更新的逻辑
  270. function handleMapUpdate() {
  271. if (isCreateFarmFullReload()) {
  272. // 清除旧的地块数据
  273. store.commit("home/SET_FARM_POLYGON", null);
  274. isFromEditMap.value = false; // 从home进入,可以手动输入
  275. locationVal.value = null;
  276. centerPoint.value = store.state.home.miniUserLocationPoint;
  277. const arr = convertPointToArray(centerPoint.value);
  278. getLocationName(`${arr[1]},${arr[0]}`);
  279. indexMap.setMapPosition(arr);
  280. indexMap.clearLayer();
  281. // 不再自动生成默认地块,等待用户点击"新增地块"
  282. polygonArr.value = null;
  283. ruleForm.farm_area = "";
  284. return; // 直接返回,不执行下面的逻辑
  285. }
  286. indexMap.clearLayer();
  287. // 绘制勾画范围(从edit_map返回的情况)
  288. const polygonData = store.state.home.polygonData;
  289. // 优先处理从编辑地图页面返回的数据
  290. if (polygonData) {
  291. // 检查地块数据是否有效(数组存在且不为空)
  292. const hasValidGeometry =
  293. polygonData.geometryArr && Array.isArray(polygonData.geometryArr) && polygonData.geometryArr.length > 0;
  294. if (hasValidGeometry) {
  295. // 用户从edit_map返回,且有有效的地块数据
  296. // 根据 isConfirmed 判断是否锁定输入框
  297. if (polygonData.isConfirmed) {
  298. // 用户点击了"确认"按钮,锁定输入框并显示精确面积
  299. isFromEditMap.value = true;
  300. ruleForm.farm_area = polygonData.mianji;
  301. } else {
  302. // 用户点击了"取消",不锁定输入框,面积保持原样
  303. isFromEditMap.value = false;
  304. // 面积输入框保持之前的值,不更新
  305. }
  306. // 使用 nextTick 确保地图渲染完成后再设置地块
  307. nextTick(() => {
  308. indexMap.setAreaGeometry(polygonData.geometryArr);
  309. });
  310. polygonArr.value = polygonData.geometryArr;
  311. } else {
  312. // 用户在编辑页面删除了所有地块
  313. // 重置所有状态
  314. polygonArr.value = null;
  315. ruleForm.farm_area = "";
  316. isFromEditMap.value = false;
  317. }
  318. } else if (route.query.type === "edit" && store.state.home.editFarmData) {
  319. // 如果是编辑模式且没有从编辑地图返回的数据,回填原始编辑数据
  320. populateEditData();
  321. } else if (centerPoint.value && polygonArr.value) {
  322. // 没有新的编辑数据,保持当前地块
  323. // 同样需要检查数据有效性
  324. if (Array.isArray(polygonArr.value) && polygonArr.value.length > 0) {
  325. nextTick(() => {
  326. indexMap.setAreaGeometry(polygonArr.value);
  327. });
  328. }
  329. }
  330. }
  331. // 搜索
  332. const MAP_KEY = "CZLBZ-LJICQ-R4A5J-BN62X-YXCRJ-GNBUT";
  333. const locationVal = ref(null);
  334. const locationOptions = reactive({
  335. list: [],
  336. });
  337. const loading = ref(false);
  338. const remoteMethod = async (keyword) => {
  339. if (keyword) {
  340. locationOptions.list = [];
  341. loading.value = true;
  342. const params = {
  343. key: MAP_KEY,
  344. keyword,
  345. location: route.query.userLocation || "113.61702297075017,23.584863449735067",
  346. };
  347. await VE_API.old_mini_map.getCtiyList({ word: keyword }).then(({ data }) => {
  348. if (data && data.length) {
  349. data.forEach((item) => {
  350. item.point = item.location.lat + "," + item.location.lng;
  351. locationOptions.list.push(item);
  352. });
  353. }
  354. });
  355. VE_API.old_mini_map.search(params).then(({ data }) => {
  356. loading.value = false;
  357. data.forEach((item) => {
  358. item.point = item.location.lat + "," + item.location.lng;
  359. locationOptions.list.push(item);
  360. });
  361. });
  362. } else {
  363. locationOptions.list = [];
  364. }
  365. };
  366. const handleSearchRes = (v) => {
  367. const parts = v.value.split(",");
  368. let { latitude, longitude } = transformFromGCJToWGS(parseFloat(parts[0]), parseFloat(parts[1]));
  369. const coordinateArray = [longitude, latitude];
  370. indexMap.setMapPosition(coordinateArray);
  371. centerPoint.value = `POINT (${coordinateArray[0]} ${coordinateArray[1]})`;
  372. ruleForm.farm_address = v.item?.title || v.item?.address;
  373. pointAddress.value = v.item?.province + v.item?.city + (v.item?.district || '');
  374. // 更新farmCity以便后续更新农场名称
  375. farmCity.value = v.item?.city + (v.item?.district || "");
  376. // 地址修改后,如果满足条件则自动更新农场名称
  377. updateFarmNameIfNeeded();
  378. };
  379. // 表单
  380. const ruleFormRef = ref(null);
  381. const ruleForm = reactive({
  382. farm_address: "",
  383. farm_area: "",
  384. farm_name: "",
  385. });
  386. // 自定义验证规则:验证面积必须是大于0的数字
  387. const validateMianji = (rule, value, callback) => {
  388. if (!value) {
  389. callback(new Error("请输入农场面积"));
  390. } else {
  391. const num = parseFloat(value);
  392. if (isNaN(num)) {
  393. callback(new Error("面积必须是数字"));
  394. } else if (num <= 0) {
  395. callback(new Error("面积必须大于0"));
  396. } else {
  397. callback();
  398. }
  399. }
  400. };
  401. const rules = reactive({
  402. farm_address: [{ required: true, message: "请选择农场位置", trigger: "blur" }],
  403. farm_area: [
  404. { required: true, message: "请输入农场面积", trigger: "blur" },
  405. { validator: validateMianji, trigger: ["blur", "change"] },
  406. ],
  407. farm_name: [{ required: true, message: "请输入您的农场名称", trigger: ["blur", "change"] }],
  408. });
  409. const submitForm = (formEl) => {
  410. if (!formEl || isSubmitting.value) return;
  411. formEl.validate((valid) => {
  412. if (!valid) return;
  413. const cropItems = parseSelectedCropItems();
  414. if (!cropItems) {
  415. ElMessage.warning({ message: t('请先点击「种植作物」选择作物品类'), type: 'warning' });
  416. return;
  417. }
  418. const params = {
  419. ...ruleForm,
  420. farm_location: centerPoint.value,
  421. varieties: cropItems.map(
  422. (item) => `${item.variety_code}-${item.categorycode}`,
  423. ),
  424. farm_polygon:
  425. polygonArr.value && polygonArr.value.length > 0
  426. ? polygonArr.value[0]
  427. : null,
  428. };
  429. if (route.query.type === "edit" && route.query.farmId) {
  430. params.id = route.query.farmId;
  431. }
  432. if (route.query.type !== "edit") {
  433. const queryParams = { ...params };
  434. if (Array.isArray(queryParams.geom)) {
  435. queryParams.geom = JSON.stringify(queryParams.geom);
  436. }
  437. isSubmitting.value = true;
  438. VE_API.farm.createFarm(queryParams)
  439. .then(async (res) => {
  440. if (res?.code === 200) {
  441. // 创建成功后拉列表,选中最后一项(新建农场)
  442. await selectNewlyCreatedFarm();
  443. showPlantingReportPopup.value = true;
  444. sessionStorage.removeItem(SESSION_SELECT_CROP_KEY);
  445. }
  446. })
  447. .finally(() => {
  448. isSubmitting.value = false;
  449. });
  450. }
  451. });
  452. };
  453. const resetForm = (formEl) => {
  454. if (!formEl) return;
  455. formEl.resetFields();
  456. // 清除地块数据
  457. store.commit("home/SET_FARM_POLYGON", null);
  458. polygonArr.value = null;
  459. isFromEditMap.value = false;
  460. // 根据来源页面决定返回目标
  461. if (route.query.from && route.query.from !== "details") {
  462. router.replace(`/${route.query.from}`);
  463. return;
  464. }
  465. router.go(-1);
  466. };
  467. const centerPoint = ref(null);
  468. function handleGoSelectCrop() {
  469. router.push(`/select_crop`);
  470. }
  471. const pointAddress = ref(null);
  472. const farmCity = ref(null);
  473. function getLocationName(location) {
  474. const params = {
  475. key: MAP_KEY,
  476. location,
  477. };
  478. VE_API.old_mini_map.location(params).then(({ result }) => {
  479. const add = result.formatted_addresses?.recommend ? result.formatted_addresses.recommend : result.address + "";
  480. ruleForm.farm_address = add;
  481. pointAddress.value = result.address;
  482. farmCity.value = result.address_component?.city + (result.address_component?.district || "");
  483. // 地址修改后,如果满足条件则自动更新农场名称
  484. updateFarmNameIfNeeded();
  485. });
  486. }
  487. watch(() => mapLocation.data, (newValue) => {
  488. if (newValue) {
  489. let { latitude, longitude } = transformFromWGSToGCJ(newValue[1], newValue[0]);
  490. centerPoint.value = `POINT (${newValue[0]} ${newValue[1]})`;
  491. getLocationName(`${latitude},${longitude}`);
  492. }
  493. });
  494. function backgToHome() {
  495. ruleFormRef.value?.resetFields();
  496. sessionStorage.removeItem(SESSION_SELECT_CROP_KEY);
  497. // 根据来源页面决定返回目标
  498. const fromPage = route.query?.from;
  499. if (route.query.miniJson) {
  500. const json = JSON.parse(route.query.miniJson);
  501. if (json.isMini) {
  502. const dropdownGardenItem = ref({
  503. organId: json.farmId,
  504. periodId: json.periodId,
  505. name: json.name,
  506. page: "create_farm",
  507. showFarmSelect: true,
  508. images: json.images,
  509. });
  510. wx.miniProgram.reLaunch({
  511. url: `/pages/subPages/new_recognize/index?gardenData=${JSON.stringify(dropdownGardenItem.value)}`,
  512. });
  513. }
  514. json?.from && router.replace(`/${json.from}`);
  515. } else {
  516. if (fromPage && fromPage !== "details") {
  517. if (route.query?.type === "farmer") {
  518. router.go(-1);
  519. } else {
  520. router.replace(`/${fromPage}`);
  521. }
  522. return;
  523. } else {
  524. router.go(-1);
  525. }
  526. }
  527. }
  528. // 处理面积按键输入 - 只允许数字和小数点
  529. function handleMianjiKeypress(event) {
  530. // 如果是从编辑地图返回的,不允许手动修改
  531. if (isFromEditMap.value) {
  532. event.preventDefault();
  533. return;
  534. }
  535. const charCode = event.which ? event.which : event.keyCode;
  536. const char = String.fromCharCode(charCode);
  537. // 允许数字 (0-9) 和小数点 (.)
  538. if (!/^[0-9.]$/.test(char)) {
  539. event.preventDefault();
  540. return;
  541. }
  542. // 如果已经有小数点,不允许再输入小数点
  543. const currentValue = ruleForm.farm_area || "";
  544. if (char === "." && currentValue.includes(".")) {
  545. event.preventDefault();
  546. return;
  547. }
  548. // 不允许以小数点开头
  549. if (char === "." && !currentValue) {
  550. event.preventDefault();
  551. return;
  552. }
  553. }
  554. // 处理农场名称输入
  555. function handleFarmNameInput() {
  556. // 标记用户已手动修改过农场名称
  557. isFarmNameManuallyModified.value = true;
  558. }
  559. // 根据地址更新农场名称(如果满足条件)
  560. function updateFarmNameIfNeeded() {
  561. // 创建模式且未手动改过名称时,地址变化后同步更新(含已有自动名称的场景)
  562. if (route.query.type !== "edit" && !isFarmNameManuallyModified.value && farmCity.value) {
  563. ruleForm.farm_name = farmCity.value + "农场";
  564. }
  565. }
  566. // 回填编辑数据
  567. function populateEditData() {
  568. const editData = store.state.home.editFarmData;
  569. if (!editData) {
  570. return;
  571. }
  572. // 回填基本信息
  573. ruleForm.farm_name = editData.name || "";
  574. ruleForm.farm_area = editData.mianji || "";
  575. ruleForm.farm_address = editData.address || "";
  576. // 设置地图中心点
  577. if (editData.pointWkt) {
  578. centerPoint.value = editData.pointWkt;
  579. const arr = convertPointToArray(editData.pointWkt);
  580. indexMap.setMapPosition(arr);
  581. }
  582. // 处理地块数据
  583. if (editData.geomWkt) {
  584. polygonArr.value = [editData.geomWkt];
  585. indexMap.setAreaGeometry([editData.geomWkt]);
  586. isFromEditMap.value = true; // 编辑模式下锁定面积输入
  587. }
  588. // 设置地址信息
  589. if (editData.district) {
  590. try {
  591. const districtInfo = JSON.parse(editData.district);
  592. pointAddress.value = districtInfo.province + districtInfo.city + (districtInfo?.district || '');
  593. } catch (e) {
  594. console.warn("解析地址信息失败:", e);
  595. }
  596. }
  597. }
  598. // 处理面积输入
  599. let mianjiInputTimer = null;
  600. function handleMianjiInput(value) {
  601. // 如果是从编辑地图返回的,不允许手动修改
  602. if (isFromEditMap.value) {
  603. return;
  604. }
  605. // 过滤非法字符,只保留数字和小数点
  606. let filteredValue = value.replace(/[^\d.]/g, "");
  607. // 确保只有一个小数点
  608. const parts = filteredValue.split(".");
  609. if (parts.length > 2) {
  610. filteredValue = parts[0] + "." + parts.slice(1).join("");
  611. }
  612. // 限制小数点后最多2位
  613. if (parts.length === 2 && parts[1].length > 2) {
  614. filteredValue = parts[0] + "." + parts[1].substring(0, 2);
  615. }
  616. // 更新输入框的值(如果被过滤了)
  617. if (filteredValue !== value) {
  618. ruleForm.farm_area = filteredValue;
  619. return;
  620. }
  621. // 清除之前的定时器
  622. if (mianjiInputTimer) {
  623. clearTimeout(mianjiInputTimer);
  624. }
  625. // 防抖处理,用户停止输入500ms后再更新地块
  626. mianjiInputTimer = setTimeout(() => {
  627. const mu = parseFloat(filteredValue);
  628. // 验证输入的有效性
  629. if (!mu || isNaN(mu) || mu <= 0) {
  630. return;
  631. }
  632. // 根据亩数重新生成地块
  633. if (centerPoint.value) {
  634. const arr = convertPointToArray(centerPoint.value);
  635. const squareData = generateSquarePolygonByMu(arr, mu);
  636. const geometryData = {
  637. geometryArr: [squareData.wkt],
  638. mianji: squareData.area,
  639. };
  640. // 清除旧地块
  641. indexMap.clearLayer();
  642. // 绘制新地块
  643. indexMap.setAreaGeometry(geometryData.geometryArr);
  644. // 更新状态
  645. polygonArr.value = geometryData.geometryArr;
  646. }
  647. }, 500);
  648. }
  649. </script>
  650. <style lang="scss" scoped>
  651. ::v-deep {
  652. .el-form-item--default {
  653. margin-bottom: 20px;
  654. }
  655. }
  656. .create-farm {
  657. position: relative;
  658. width: 100%;
  659. height: 100vh;
  660. overflow: hidden;
  661. .map-container {
  662. width: 100%;
  663. height: calc(100% - 320px);
  664. }
  665. .farm-content {
  666. position: absolute;
  667. top: 40px;
  668. left: 0;
  669. width: 100%;
  670. height: calc(100% - 40px);
  671. pointer-events: none;
  672. z-index: 2;
  673. .top-mask {
  674. height: 100px;
  675. position: absolute;
  676. z-index: 2;
  677. top: 0;
  678. left: 0;
  679. width: 100%;
  680. background: linear-gradient(0deg, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.6) 100%);
  681. }
  682. }
  683. .farm-filter {
  684. pointer-events: all;
  685. margin: 12px;
  686. position: relative;
  687. z-index: 10;
  688. background: rgba(0, 0, 0, 0.3);
  689. border-radius: 20px;
  690. border: 1px solid rgba(255, 255, 255, 0.4);
  691. &::before {
  692. content: "";
  693. position: absolute;
  694. left: 12px;
  695. top: 9px;
  696. width: 14px;
  697. height: 14px;
  698. background: url("@/assets/img/home/search.png") no-repeat center center / 100% 100%;
  699. }
  700. ::v-deep {
  701. .el-select__wrapper {
  702. background: none;
  703. box-shadow: none;
  704. padding-left: 34px;
  705. font-size: 12px;
  706. .el-select__selected-item,
  707. .el-select__placeholder,
  708. .el-select__input {
  709. color: rgba(255, 255, 255, 0.6);
  710. &.is-transparent {
  711. color: #ccc;
  712. font-size: 12px;
  713. }
  714. }
  715. }
  716. .el-select {
  717. transition: all 0.3s;
  718. .el-input.is-focus .el-input__wrapper {
  719. box-shadow: none !important;
  720. }
  721. }
  722. .el-input {
  723. .el-input__wrapper {
  724. background: none;
  725. box-shadow: none;
  726. padding-left: 18px;
  727. font-size: 11px;
  728. .el-input__inner {
  729. color: rgba(255, 255, 255, 0.6);
  730. }
  731. &.is-focus {
  732. .el-input__inner {
  733. color: #ccc;
  734. font-size: 11px;
  735. }
  736. }
  737. }
  738. }
  739. }
  740. }
  741. .create-wrap {
  742. position: absolute;
  743. bottom: 0px;
  744. left: 0;
  745. width: 100%;
  746. background: linear-gradient(180deg, transparent 0%, #f5f7fb 20%);
  747. }
  748. .create-box {
  749. pointer-events: all;
  750. margin: 0 12px 10px 12px;
  751. width: calc(100% - 24px);
  752. background: #e0f1fe;
  753. border-radius: 14px;
  754. .box-content {
  755. position: relative;
  756. &::after {
  757. position: absolute;
  758. right: 10px;
  759. top: 2px;
  760. content: "";
  761. width: 79px;
  762. height: 72px;
  763. background: url("@/assets/img/home/creat-bg.png") no-repeat center / 100% 100%;
  764. }
  765. }
  766. .create-title {
  767. display: flex;
  768. align-items: center;
  769. padding: 12px 6px 12px 12px;
  770. color: #0089f5;
  771. font-size: 18px;
  772. font-weight: bold;
  773. .title-icon {
  774. width: 18px;
  775. padding-right: 10px;
  776. }
  777. }
  778. .create-content {
  779. background: #fff;
  780. border-radius: 14px;
  781. padding: 12px;
  782. position: relative;
  783. z-index: 2;
  784. .create-from {
  785. .select-wrap {
  786. display: flex;
  787. width: 100%;
  788. .species-entry {
  789. display: inline-flex;
  790. align-items: center;
  791. color: #000;
  792. cursor: pointer;
  793. }
  794. }
  795. ::v-deep {
  796. .el-form-item__label {
  797. color: #000;
  798. }
  799. .el-form-item__error {
  800. top: 117%;
  801. }
  802. .el-form-item {
  803. position: relative;
  804. &::after {
  805. content: "";
  806. position: absolute;
  807. left: 60px;
  808. bottom: -5px;
  809. width: calc(100% - 60px);
  810. height: 1px;
  811. background: rgba(0, 0, 0, 0.08);
  812. }
  813. }
  814. .el-input__wrapper {
  815. box-shadow: none;
  816. padding: 1px 6px;
  817. }
  818. }
  819. .area-box {
  820. display: flex;
  821. align-items: center;
  822. width: 100%;
  823. .unit {
  824. padding-right: 10px;
  825. }
  826. }
  827. .position-wrap {
  828. width: 100%;
  829. display: flex;
  830. justify-content: space-between;
  831. align-items: center;
  832. }
  833. }
  834. .create-btn {
  835. display: flex;
  836. align-items: center;
  837. width: 100%;
  838. padding-top: 10px;
  839. .btn-item {
  840. flex: 1;
  841. text-align: center;
  842. padding: 0 11px;
  843. height: 40px;
  844. line-height: 40px;
  845. border-radius: 34px;
  846. font-size: 16px;
  847. box-sizing: border-box;
  848. &.sencond-btn {
  849. border: 1px solid rgba(153, 153, 153, 0.5);
  850. color: #666666;
  851. }
  852. &.primary-btn {
  853. background: linear-gradient(180deg, #76c3ff, #2199f8);
  854. color: #fff;
  855. &.is-disabled {
  856. opacity: 0.6;
  857. pointer-events: none;
  858. }
  859. }
  860. }
  861. .btn-item+.btn-item {
  862. margin-left: 5px;
  863. }
  864. }
  865. }
  866. }
  867. }
  868. .planting-report-popup {
  869. width: 82%;
  870. padding: 28px 20px 20px;
  871. .planting-report-popup__inner {
  872. text-align: center;
  873. .icon {
  874. width: 68px;
  875. height: 68px;
  876. margin-bottom: 16px;
  877. }
  878. .title {
  879. font-size: 24px;
  880. }
  881. .links {
  882. display: flex;
  883. flex-wrap: wrap;
  884. justify-content: center;
  885. gap: 10px 16px;
  886. margin: 18px 0 22px;
  887. .link {
  888. font-size: 18px;
  889. color: #2199f8;
  890. }
  891. }
  892. .btn {
  893. padding: 8px;
  894. border-radius: 25px;
  895. font-size: 16px;
  896. color: #fff;
  897. background: #2199F8;
  898. }
  899. }
  900. }
  901. </style>
  902. <style lang="scss">
  903. .location-search-popper {
  904. .el-select-dropdown__list {
  905. max-width: 96vw;
  906. overflow-x: auto;
  907. }
  908. .sub-title {
  909. padding-left: 6px;
  910. font-size: 12px;
  911. color: #ccc;
  912. }
  913. }
  914. </style>