index.vue 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267
  1. <template>
  2. <div class="create-farm">
  3. <custom-header
  4. :name="paramsType === 'client' ? '新增用户' : paramsType === 'edit' ? '编辑农场' : '创建农场'"
  5. :isGoBack="true"
  6. @goback="backgToHome"
  7. ></custom-header>
  8. <!-- 地图 -->
  9. <div class="map-container" ref="mapContainer"></div>
  10. <div class="farm-content">
  11. <div class="top-mask"></div>
  12. <div class="farm-filter">
  13. <el-select
  14. v-model="locationVal"
  15. filterable
  16. remote
  17. reserve-keyword
  18. placeholder="搜索位置"
  19. :remote-method="remoteMethod"
  20. :loading="loading"
  21. @change="handleSearchRes"
  22. popper-class="location-search-popper"
  23. >
  24. <el-option
  25. v-for="(item, index) in locationOptions.list"
  26. :key="index"
  27. :label="item.title"
  28. :value="{ value: item.point, item }"
  29. >
  30. <span>{{ item.title }}</span>
  31. <span class="sub-title">{{ item.province }}{{ item.city }}{{ item.district }}</span>
  32. </el-option>
  33. </el-select>
  34. </div>
  35. <!-- 创建 -->
  36. <div class="create-wrap">
  37. <div class="create-box">
  38. <div class="box-content">
  39. <div class="create-title">
  40. <img class="title-icon" src="@/assets/img/home/create-icon.png" alt="" />
  41. {{ paramsType === "client" ? "新增用户" : paramsType === "edit" ? "编辑农场" : "创建农场" }}
  42. </div>
  43. <div class="create-content">
  44. <div class="create-from">
  45. <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" class="demo-ruleForm">
  46. <el-form-item label="农场位置" prop="address">
  47. <div class="position-wrap">
  48. <el-input
  49. placeholder="农场位置"
  50. readonly
  51. v-model="ruleForm.address"
  52. autocomplete="off"
  53. />
  54. <div class="draw-btn" @click="toSubPage">
  55. {{ hasDefaultPolygon ? "点击勾选地块" : "新增地块" }}
  56. </div>
  57. </div>
  58. </el-form-item>
  59. <el-form-item label="种植作物" prop="speciesItem">
  60. <div class="select-wrap">
  61. <el-select
  62. @change="changeSpecie"
  63. class="select-item"
  64. v-model="ruleForm.speciesItem"
  65. placeholder="品类"
  66. >
  67. <el-option
  68. v-for="(item, index) in specieList"
  69. :key="index"
  70. :label="item.name"
  71. :value="{ value: item.id, ...item }"
  72. />
  73. </el-select>
  74. <el-select
  75. v-model="ruleForm.typeId"
  76. placeholder="品种"
  77. class="period-select select-item"
  78. >
  79. <el-option
  80. v-for="(item, index) in fruitsList"
  81. :key="index"
  82. :label="item.name"
  83. :value="item.id"
  84. />
  85. </el-select>
  86. </div>
  87. </el-form-item>
  88. <el-form-item label="联系人" prop="fzr">
  89. <div class="area-box">
  90. <el-input
  91. placeholder="请输入联系人姓名"
  92. v-model="ruleForm.fzr"
  93. autocomplete="off"
  94. style="width: fit-content"
  95. />
  96. </div>
  97. </el-form-item>
  98. <el-form-item label="联系电话" prop="tel">
  99. <div class="area-box">
  100. <el-input
  101. placeholder="请输入联系人电话"
  102. v-model="ruleForm.tel"
  103. autocomplete="off"
  104. style="width: fit-content"
  105. />
  106. </div>
  107. </el-form-item>
  108. <el-form-item label="农场面积" prop="mu">
  109. <div class="area-box">
  110. <el-input
  111. :placeholder="
  112. isFromEditMap ? '勾选地块获得农场面积' : '请输入农场的真实面积'
  113. "
  114. v-model="ruleForm.mu"
  115. :readonly="isFromEditMap"
  116. type="text"
  117. autocomplete="off"
  118. style="width: fit-content"
  119. @input="handleMianjiInput"
  120. @keypress="handleMianjiKeypress"
  121. />
  122. <div class="unit">亩</div>
  123. </div>
  124. </el-form-item>
  125. <el-form-item label="客户类型" prop="userType" class="select-wrap client-wrap">
  126. <el-select class="select-item" v-model="ruleForm.userType" placeholder="请选择">
  127. <el-option label="普通用户" :value="1" />
  128. <el-option label="托管用户" :value="2" />
  129. <el-option label="优质客户" :value="3" />
  130. </el-select>
  131. </el-form-item>
  132. <el-form-item label="农场名称" prop="name">
  133. <el-input
  134. placeholder="请输入您的农场名称"
  135. v-model="ruleForm.name"
  136. autocomplete="off"
  137. @input="handleFarmNameInput"
  138. />
  139. </el-form-item>
  140. <!-- <Checkbox
  141. v-if="paramsType !== 'client' && curRole == 0"
  142. class="checkbox"
  143. icon-size="18px"
  144. shape="square"
  145. v-model="ruleForm.defaultFarm"
  146. >是否勾选为默认农场</Checkbox
  147. > -->
  148. </el-form>
  149. </div>
  150. <div class="create-btn">
  151. <div class="btn-item sencond-btn" @click="resetForm(ruleFormRef)">取消</div>
  152. <div class="btn-item primary-btn" @click="submitForm(ruleFormRef)">
  153. {{
  154. paramsType === "client"
  155. ? "添加"
  156. : paramsType === "edit"
  157. ? "确认修改"
  158. : "立即创建"
  159. }}
  160. </div>
  161. </div>
  162. </div>
  163. </div>
  164. </div>
  165. </div>
  166. </div>
  167. </div>
  168. <!-- 农情采集成功弹窗 -->
  169. <tip-popup
  170. v-model:show="showSuccessPopup"
  171. type="success"
  172. text="农情采集成功"
  173. @confirm="handlePopupConfirm"
  174. @handleClickOverlay="handlePopupConfirm"
  175. />
  176. </template>
  177. <script setup>
  178. import customHeader from "@/components/customHeader.vue";
  179. import IndexMap from "./map/index.js";
  180. import { useRoute, useRouter } from "vue-router";
  181. import { mapLocation } from "./map/index.js";
  182. import { onMounted, ref, reactive, watch, onActivated, nextTick } from "vue";
  183. import { useStore } from "vuex";
  184. import { convertPointToArray } from "@/utils/index";
  185. import { ElMessage } from "element-plus";
  186. import { Checkbox } from "vant";
  187. import tipPopup from "@/components/popup/tipPopup.vue";
  188. import wx from "weixin-js-sdk";
  189. import { transformFromGCJToWGS, transformFromWGSToGCJ } from "@/utils/WSCoordinate.js";
  190. const route = useRoute();
  191. const router = useRouter();
  192. const store = useStore();
  193. const indexMap = new IndexMap();
  194. const mapContainer = ref(null);
  195. // 农情采集成功弹窗
  196. const showSuccessPopup = ref(false);
  197. const handlePopupConfirm = () => {
  198. showSuccessPopup.value = false;
  199. router.replace(`/home`);
  200. };
  201. // 标记是否从编辑地图页面确认返回
  202. const isFromEditMap = ref(false);
  203. // 标记是否已创建默认地块
  204. const hasDefaultPolygon = ref(false);
  205. // 标记用户是否手动修改过农场名称
  206. const isFarmNameManuallyModified = ref(false);
  207. /**
  208. * 根据中心点生成指定边长的正方形地块WKT
  209. * @param {Array} center - 中心点坐标 [lng, lat]
  210. * @param {Number} sideLength - 正方形边长(米)
  211. * @returns {Object} 包含WKT字符串和面积(亩)的对象
  212. */
  213. function generateSquarePolygonBySideLength(center, sideLength) {
  214. // 确保输入是数字类型
  215. const lng = parseFloat(center[0]);
  216. const lat = parseFloat(center[1]);
  217. // 半边长(米)
  218. const halfSide = sideLength / 2;
  219. // 纬度方向:1度约等于111000米
  220. const latDelta = halfSide / 111000;
  221. // 经度方向:需要根据纬度调整,1度约等于111000 * cos(lat)米
  222. const lngDelta = halfSide / (111000 * Math.cos((lat * Math.PI) / 180));
  223. // 计算四个顶点(逆时针顺序)
  224. const topLeft = [lng - lngDelta, lat + latDelta];
  225. const topRight = [lng + lngDelta, lat + latDelta];
  226. const bottomRight = [lng + lngDelta, lat - latDelta];
  227. const bottomLeft = [lng - lngDelta, lat - latDelta];
  228. // 生成MULTIPOLYGON格式的WKT(需要闭合,所以第一个点要重复)
  229. // 明确使用join来格式化坐标点
  230. const formatPoint = (point) => `${point[0]} ${point[1]}`;
  231. const coordinates = [topLeft, topRight, bottomRight, bottomLeft, topLeft].map(formatPoint).join(", ");
  232. // 注意:MULTIPOLYGON 和括号之间需要有一个空格
  233. const wkt = `MULTIPOLYGON (((${coordinates})))`;
  234. // 计算面积(亩): 边长200米 = 40,000平方米 ≈ 60亩
  235. const areaInSquareMeters = sideLength * sideLength;
  236. const areaInMu = (areaInSquareMeters / 666.67).toFixed(2);
  237. return { wkt, area: areaInMu };
  238. }
  239. /**
  240. * 根据中心点和亩数生成正方形地块WKT
  241. * @param {Array} center - 中心点坐标 [lng, lat]
  242. * @param {Number} mu - 面积(亩)
  243. * @returns {Object} 包含WKT字符串和面积(亩)的对象
  244. */
  245. function generateSquarePolygonByMu(center, mu) {
  246. // 确保输入是数字类型
  247. const lng = parseFloat(center[0]);
  248. const lat = parseFloat(center[1]);
  249. // 1亩 ≈ 666.67平方米
  250. const areaInSquareMeters = mu * 666.67;
  251. // 正方形边长(米)
  252. const sideLength = Math.sqrt(areaInSquareMeters);
  253. // 半边长(米)
  254. const halfSide = sideLength / 2;
  255. // 纬度方向:1度约等于111000米
  256. const latDelta = halfSide / 111000;
  257. // 经度方向:需要根据纬度调整,1度约等于111000 * cos(lat)米
  258. const lngDelta = halfSide / (111000 * Math.cos((lat * Math.PI) / 180));
  259. // 计算四个顶点(逆时针顺序)
  260. const topLeft = [lng - lngDelta, lat + latDelta];
  261. const topRight = [lng + lngDelta, lat + latDelta];
  262. const bottomRight = [lng + lngDelta, lat - latDelta];
  263. const bottomLeft = [lng - lngDelta, lat - latDelta];
  264. // 生成MULTIPOLYGON格式的WKT(需要闭合,所以第一个点要重复)
  265. const formatPoint = (point) => `${point[0]} ${point[1]}`;
  266. const coordinates = [topLeft, topRight, bottomRight, bottomLeft, topLeft].map(formatPoint).join(", ");
  267. // 注意:MULTIPOLYGON 和括号之间需要有一个空格
  268. const wkt = `MULTIPOLYGON (((${coordinates})))`;
  269. return { wkt, area: parseFloat(mu).toFixed(2) };
  270. }
  271. onMounted(() => {
  272. // 清除上一次的地块数据,确保每次进入都是全新状态
  273. store.commit("home/SET_FARM_POLYGON", null);
  274. isFromEditMap.value = false; // 初始化时可以手动输入
  275. hasDefaultPolygon.value = false; // 初始化时没有默认地块
  276. centerPoint.value = store.state.home.miniUserLocationPoint;
  277. const arr = convertPointToArray(centerPoint.value);
  278. getLocationName(`${arr[1]},${arr[0]}`);
  279. indexMap.initMap(centerPoint.value, mapContainer.value);
  280. // 不再初始化时绘制默认地块,等待用户点击"新增地块"按钮
  281. // 清空地块和面积数据
  282. polygonArr.value = null;
  283. ruleForm.mu = "";
  284. ruleForm.typeId = "";
  285. // 如果是编辑模式,等待品类列表加载完成后再回填数据
  286. if (route.query.type === "edit" && store.state.home.editFarmData) {
  287. getSpecieList().then(() => {
  288. populateEditData();
  289. });
  290. } else {
  291. getSpecieList();
  292. }
  293. });
  294. const polygonArr = ref(null);
  295. const paramsType = ref(null);
  296. onActivated(() => {
  297. paramsType.value = route.query.type;
  298. // 仅在携带 isReload 标记、且不是编辑/小程序回流场景时,认为是一次全新创建,重置表单和地块,
  299. // 避免破坏原有自动生成农场名称等逻辑
  300. if (route.query.isReload && paramsType.value !== "edit" && !route.query.miniJson) {
  301. // 重置表单字段到初始值
  302. ruleFormRef.value && ruleFormRef.value.resetFields();
  303. // 重置与地块绘制相关的内部状态
  304. polygonArr.value = null;
  305. isFromEditMap.value = false;
  306. hasDefaultPolygon.value = false;
  307. // 清空上一次地块缓存
  308. store.commit("home/SET_FARM_POLYGON", null);
  309. }
  310. // 确保地图已初始化,使用 nextTick 等待 DOM 更新
  311. nextTick(() => {
  312. // 检查地图实例是否已初始化
  313. if (!indexMap.kmap) {
  314. // 如果地图未初始化,重新初始化
  315. if (mapContainer.value) {
  316. centerPoint.value = store.state.home.miniUserLocationPoint;
  317. const arr = convertPointToArray(centerPoint.value);
  318. indexMap.initMap(centerPoint.value, mapContainer.value);
  319. }
  320. // 等待地图初始化完成后再继续
  321. setTimeout(() => {
  322. handleMapUpdate();
  323. }, 100);
  324. return;
  325. }
  326. handleMapUpdate();
  327. });
  328. });
  329. // 处理地图更新的逻辑
  330. function handleMapUpdate() {
  331. if (route.query.isReload) {
  332. // 清除旧的地块数据
  333. store.commit("home/SET_FARM_POLYGON", null);
  334. isFromEditMap.value = false; // 从home进入,可以手动输入
  335. hasDefaultPolygon.value = false; // 重置默认地块状态
  336. centerPoint.value = store.state.home.miniUserLocationPoint;
  337. const arr = convertPointToArray(centerPoint.value);
  338. getLocationName(`${arr[1]},${arr[0]}`);
  339. indexMap.setMapPosition(arr);
  340. indexMap.clearLayer();
  341. // 不再自动生成默认地块,等待用户点击"新增地块"
  342. polygonArr.value = null;
  343. ruleForm.mu = "";
  344. ruleForm.typeId = "";
  345. ruleForm.defaultFarm = false;
  346. return; // 直接返回,不执行下面的逻辑
  347. }
  348. indexMap.clearLayer();
  349. // 绘制勾画范围(从edit_map返回的情况)
  350. const polygonData = store.state.home.polygonData;
  351. // 优先处理从编辑地图页面返回的数据
  352. if (polygonData) {
  353. // 检查地块数据是否有效(数组存在且不为空)
  354. const hasValidGeometry =
  355. polygonData.geometryArr && Array.isArray(polygonData.geometryArr) && polygonData.geometryArr.length > 0;
  356. if (hasValidGeometry) {
  357. // 用户从edit_map返回,且有有效的地块数据
  358. // 根据 isConfirmed 判断是否锁定输入框
  359. if (polygonData.isConfirmed) {
  360. // 用户点击了"确认"按钮,锁定输入框并显示精确面积
  361. isFromEditMap.value = true;
  362. ruleForm.mu = polygonData.mianji;
  363. } else {
  364. // 用户点击了"取消",不锁定输入框,面积保持原样
  365. isFromEditMap.value = false;
  366. // 面积输入框保持之前的值,不更新
  367. }
  368. // 使用 nextTick 确保地图渲染完成后再设置地块
  369. nextTick(() => {
  370. indexMap.setAreaGeometry(polygonData.geometryArr);
  371. });
  372. polygonArr.value = polygonData.geometryArr;
  373. // 有地块数据时,标记已创建默认地块
  374. hasDefaultPolygon.value = true;
  375. } else {
  376. // 用户在编辑页面删除了所有地块
  377. // 重置所有状态
  378. polygonArr.value = null;
  379. ruleForm.mu = "";
  380. isFromEditMap.value = false;
  381. hasDefaultPolygon.value = false;
  382. ruleForm.defaultFarm = false;
  383. }
  384. } else if (route.query.type === "edit" && store.state.home.editFarmData) {
  385. // 如果是编辑模式且没有从编辑地图返回的数据,回填原始编辑数据
  386. populateEditData();
  387. } else if (centerPoint.value && polygonArr.value) {
  388. // 没有新的编辑数据,保持当前地块
  389. // 同样需要检查数据有效性
  390. if (Array.isArray(polygonArr.value) && polygonArr.value.length > 0) {
  391. nextTick(() => {
  392. indexMap.setAreaGeometry(polygonArr.value);
  393. });
  394. // 保持 hasDefaultPolygon 状态
  395. }
  396. }
  397. }
  398. // 搜索
  399. const MAP_KEY = "CZLBZ-LJICQ-R4A5J-BN62X-YXCRJ-GNBUT";
  400. const locationVal = ref(null);
  401. const locationOptions = reactive({
  402. list: [],
  403. });
  404. const loading = ref(false);
  405. const remoteMethod = async (keyword) => {
  406. if (keyword) {
  407. locationOptions.list = [];
  408. loading.value = true;
  409. const params = {
  410. key: MAP_KEY,
  411. keyword,
  412. location: route.query.userLocation || "113.61702297075017,23.584863449735067",
  413. };
  414. await VE_API.old_mini_map.getCtiyList({ word: keyword }).then(({ data }) => {
  415. if (data && data.length) {
  416. data.forEach((item) => {
  417. item.point = item.location.lat + "," + item.location.lng;
  418. locationOptions.list.push(item);
  419. });
  420. }
  421. });
  422. VE_API.old_mini_map.search(params).then(({ data }) => {
  423. loading.value = false;
  424. data.forEach((item) => {
  425. item.point = item.location.lat + "," + item.location.lng;
  426. locationOptions.list.push(item);
  427. });
  428. });
  429. } else {
  430. locationOptions.list = [];
  431. }
  432. };
  433. const handleSearchRes = (v) => {
  434. const parts = v.value.split(",");
  435. let { latitude, longitude } = transformFromGCJToWGS(parseFloat(parts[0]), parseFloat(parts[1]));
  436. const coordinateArray = [longitude, latitude];
  437. indexMap.setMapPosition(coordinateArray);
  438. centerPoint.value = `POINT (${coordinateArray[0]} ${coordinateArray[1]})`;
  439. ruleForm.address = v.item?.title || v.item?.address;
  440. pointAddress.value = v.item?.province + v.item?.city + v.item?.district;
  441. // 更新farmCity以便后续更新农场名称
  442. farmCity.value = v.item?.city + v.item?.district || "";
  443. // 地址修改后,如果满足条件则自动更新农场名称
  444. updateFarmNameIfNeeded();
  445. };
  446. // 表单
  447. const ruleFormRef = ref(null);
  448. const ruleForm = reactive({
  449. address: "",
  450. mu: "",
  451. speciesItem: null,
  452. typeId: "",
  453. name: "",
  454. fzr: "",
  455. tel: "",
  456. userType: 1,
  457. defaultFarm: 0, // 0:否 1:是
  458. });
  459. // 自定义验证规则:验证面积必须是大于0的数字
  460. const validateMianji = (rule, value, callback) => {
  461. if (!value) {
  462. callback(new Error("请输入农场面积"));
  463. } else {
  464. const num = parseFloat(value);
  465. if (isNaN(num)) {
  466. callback(new Error("面积必须是数字"));
  467. } else if (num <= 0) {
  468. callback(new Error("面积必须大于0"));
  469. } else {
  470. callback();
  471. }
  472. }
  473. };
  474. const rules = reactive({
  475. address: [{ required: true, message: "请选择农场位置", trigger: "blur" }],
  476. userType: [{ required: true, message: "请选择客户类型", trigger: "blur" }],
  477. mu: [
  478. { required: true, message: "请输入农场面积", trigger: "blur" },
  479. { validator: validateMianji, trigger: ["blur", "change"] },
  480. ],
  481. speciesItem: [{ required: true, message: "请选择品类", trigger: "blur" }],
  482. typeId: [{ required: true, message: "请选择品种", trigger: "blur" }],
  483. name: [{ required: true, message: "请输入您的农场名称", trigger: ["blur", "change"] }],
  484. fzr: [{ required: true, message: "请输入联系人姓名", trigger: ["blur", "change"] }],
  485. tel: [
  486. { required: true, message: "请输入联系人电话", trigger: ["blur"] },
  487. {
  488. pattern: /^1[3-9]\d{9}$/,
  489. message: "请输入正确的手机号码",
  490. trigger: ["blur"],
  491. },
  492. ],
  493. defaultFarm: [{ required: true, message: "请选择是否为默认农场", trigger: "blur" }],
  494. });
  495. const curRole = localStorage.getItem("SET_USER_CUR_ROLE");
  496. const submitForm = (formEl) => {
  497. if (!formEl) return;
  498. formEl.validate((valid) => {
  499. if (valid) {
  500. const params = {
  501. ...ruleForm,
  502. wkt: centerPoint.value,
  503. speciesId: ruleForm.speciesItem?.id,
  504. containerId: ruleForm.speciesItem?.defaultContainerId,
  505. agriculturalCreate: route.query.type === "client" ? 1 : 0,
  506. // 编辑时geom不是数组,新增时是数组
  507. geom:
  508. route.query.type === "edit"
  509. ? polygonArr.value && polygonArr.value.length > 0
  510. ? polygonArr.value[0]
  511. : null
  512. : polygonArr.value,
  513. };
  514. // 如果是编辑模式,添加农场ID
  515. if (route.query.type === "edit" && route.query.farmId) {
  516. params.farmId = route.query.farmId;
  517. }
  518. if (route.query.type === "client") {
  519. // 处理 geom 参数,如果是数组需要序列化
  520. const queryParams = {
  521. ...params,
  522. ...route.query,
  523. };
  524. // 如果 geom 是数组,需要序列化为 JSON 字符串
  525. if (Array.isArray(queryParams.geom)) {
  526. queryParams.geom = JSON.stringify(queryParams.geom);
  527. }
  528. queryParams.speciesName = ruleForm.speciesItem?.name;
  529. router.push({
  530. path: "/prescription",
  531. query: queryParams,
  532. });
  533. return;
  534. }
  535. const apiCall = route.query.type === "edit" ? VE_API.farm.updateFarm(params) : VE_API.farm.saveFarm(params);
  536. apiCall.then((res) => {
  537. if (res.code === 0) {
  538. ElMessage.success(route.query.type === "edit" ? "修改成功" : "创建成功");
  539. // 重置表单和地块数据
  540. ruleFormRef.value.resetFields();
  541. store.commit("home/SET_FARM_POLYGON", null);
  542. store.commit("home/SET_EDIT_FARM_DATA", null); // 清除编辑数据
  543. polygonArr.value = null;
  544. isFromEditMap.value = false;
  545. if (route.query.type !== "edit" && curRole == 0) {
  546. localStorage.setItem("selectedFarmId", res.data.id);
  547. localStorage.setItem("selectedFarmName", res.data.name);
  548. }
  549. // 根据来源页面决定跳转目标
  550. const fromPage = route.query.from;
  551. if (fromPage && fromPage !== "details") {
  552. // 如果是从monitor页面来的
  553. router.replace(`/${fromPage}`);
  554. } else if (fromPage === "details") {
  555. router.go(-1);
  556. } else {
  557. if (route.query.miniJson) {
  558. const json = JSON.parse(route.query.miniJson);
  559. //上传图片
  560. VE_API.ali
  561. .uploadImg({
  562. farmId: res.data.id,
  563. images: json.images,
  564. uploadDate: formatDate(new Date()),
  565. })
  566. .then(({ code, msg }) => {
  567. if (code === 0) {
  568. showSuccessPopup.value = true;
  569. } else {
  570. ElMessage.error(msg);
  571. }
  572. });
  573. } else {
  574. router.replace(`/home`);
  575. }
  576. }
  577. } else {
  578. ElMessage.error(res.msg);
  579. }
  580. });
  581. }
  582. });
  583. };
  584. const resetForm = (formEl) => {
  585. if (!formEl) return;
  586. formEl.resetFields();
  587. // 清除地块数据
  588. store.commit("home/SET_FARM_POLYGON", null);
  589. polygonArr.value = null;
  590. isFromEditMap.value = false;
  591. hasDefaultPolygon.value = false; // 重置默认地块状态
  592. // 根据来源页面决定返回目标
  593. const fromPage = route.query.from;
  594. if (fromPage && fromPage !== "details") {
  595. router.replace(`/${fromPage}`);
  596. return;
  597. }
  598. router.go(-1);
  599. };
  600. const centerPoint = ref(null);
  601. function toSubPage() {
  602. // 如果还没有默认地块,先创建默认地块
  603. if (!hasDefaultPolygon.value) {
  604. if (centerPoint.value) {
  605. const arr = convertPointToArray(centerPoint.value);
  606. const squareData = generateSquarePolygonBySideLength(arr, 200); // 200米边长
  607. const geometryData = {
  608. geometryArr: [squareData.wkt],
  609. mianji: squareData.area,
  610. };
  611. // 绘制默认地块
  612. indexMap.setAreaGeometry(geometryData.geometryArr);
  613. // 保存地块数据
  614. polygonArr.value = geometryData.geometryArr;
  615. // 标记已创建默认地块
  616. hasDefaultPolygon.value = true;
  617. // 不跳转,停留在当前页面
  618. return;
  619. }
  620. }
  621. // 如果已有默认地块,则跳转到编辑页面
  622. // 保存到store中以便在编辑页面回显
  623. if (polygonArr.value) {
  624. const polygonData = {
  625. geometryArr: polygonArr.value,
  626. mianji: ruleForm.mu || "", // 保存用户输入的面积,如果没有输入则为空
  627. isConfirmed: false, // 标记:还未从编辑页面确认返回
  628. };
  629. store.commit("home/SET_FARM_POLYGON", polygonData);
  630. }
  631. router.push(
  632. `/edit_map?mapCenter=${centerPoint.value}&pointName=${ruleForm.address}&pointAddress=${pointAddress.value}&from=${route.query.from}&type=${route.query.type}`
  633. );
  634. }
  635. const pointAddress = ref(null);
  636. const farmCity = ref(null);
  637. function getLocationName(location) {
  638. const params = {
  639. key: MAP_KEY,
  640. location,
  641. };
  642. VE_API.old_mini_map.location(params).then(({ result }) => {
  643. // locationVal.value = result.formatted_addresses.recommend;
  644. const add = result.formatted_addresses?.recommend ? result.formatted_addresses.recommend : result.address + "";
  645. ruleForm.address = add;
  646. pointAddress.value = result.address;
  647. farmCity.value = result.address_component?.city + result.address_component?.district || "";
  648. // 地址修改后,如果满足条件则自动更新农场名称
  649. updateFarmNameIfNeeded();
  650. });
  651. }
  652. watch(
  653. () => mapLocation.data,
  654. (newValue, oldValue) => {
  655. if (newValue) {
  656. let { latitude, longitude } = transformFromWGSToGCJ(newValue[1], newValue[0]);
  657. centerPoint.value = `POINT (${newValue[0]} ${newValue[1]})`;
  658. getLocationName(`${latitude},${longitude}`);
  659. }
  660. }
  661. );
  662. const specieList = ref([]);
  663. function getSpecieList() {
  664. return VE_API.farm.fetchSpecieList({ point: centerPoint.value }).then(({ data }) => {
  665. specieList.value = data;
  666. return data;
  667. });
  668. }
  669. async function changeSpecie(v) {
  670. const data = await checkExistsEnabledScheme(v.defaultContainerId);
  671. if (!data) {
  672. ElMessage.warning("该品类暂无可用方案,请选择其他品类");
  673. ruleForm.speciesItem = "";
  674. ruleForm.typeId = "";
  675. fruitsList.value = [];
  676. return;
  677. }
  678. getFruitsTypeItemList(v.id);
  679. // 清空品种选择
  680. ruleForm.typeId = "";
  681. // 只有在创建模式下且用户没有手动修改过农场名称时,才自动设置农场名称
  682. if (route.query.type !== "edit" && !isFarmNameManuallyModified.value) {
  683. ruleForm.name = farmCity.value + v.name + "农场";
  684. }
  685. }
  686. //判断是否存在可用方案
  687. async function checkExistsEnabledScheme(containerId) {
  688. const { data } = await VE_API.home.existsEnabledScheme({containerId});
  689. return data;
  690. }
  691. const fruitsList = ref([]);
  692. function getFruitsTypeItemList(parentId) {
  693. VE_API.farm.fruitsTypeItemList({ parentId }).then(({ data }) => {
  694. fruitsList.value = data;
  695. });
  696. }
  697. /**
  698. * 格式化日期为 YYYY-MM-DD 格式
  699. * @param {Date} date - 日期对象
  700. * @returns {string} 格式化后的日期字符串
  701. */
  702. function formatDate(date) {
  703. const year = date.getFullYear();
  704. const month = String(date.getMonth() + 1).padStart(2, "0");
  705. const day = String(date.getDate()).padStart(2, "0");
  706. return `${year}-${month}-${day}`;
  707. }
  708. function backgToHome() {
  709. ruleFormRef.value?.resetFields();
  710. // 根据来源页面决定返回目标
  711. const fromPage = route.query.from;
  712. if (route.query.miniJson) {
  713. const json = JSON.parse(route.query.miniJson);
  714. if (json.isMini) {
  715. const dropdownGardenItem = ref({
  716. organId: json.farmId,
  717. periodId: json.periodId,
  718. name: json.name,
  719. page: "create_farm",
  720. showFarmSelect: true,
  721. images: json.images,
  722. });
  723. wx.miniProgram.reLaunch({
  724. url: `/pages/subPages/new_recognize/index?gardenData=${JSON.stringify(dropdownGardenItem.value)}`,
  725. });
  726. }
  727. } else {
  728. if (fromPage && fromPage !== "details") {
  729. router.replace(`/${fromPage}`);
  730. return;
  731. } else {
  732. router.go(-1);
  733. }
  734. }
  735. }
  736. // 处理面积按键输入 - 只允许数字和小数点
  737. function handleMianjiKeypress(event) {
  738. // 如果是从编辑地图返回的,不允许手动修改
  739. if (isFromEditMap.value) {
  740. event.preventDefault();
  741. return;
  742. }
  743. const charCode = event.which ? event.which : event.keyCode;
  744. const char = String.fromCharCode(charCode);
  745. // 允许数字 (0-9) 和小数点 (.)
  746. if (!/^[0-9.]$/.test(char)) {
  747. event.preventDefault();
  748. return;
  749. }
  750. // 如果已经有小数点,不允许再输入小数点
  751. const currentValue = ruleForm.mu || "";
  752. if (char === "." && currentValue.includes(".")) {
  753. event.preventDefault();
  754. return;
  755. }
  756. // 不允许以小数点开头
  757. if (char === "." && !currentValue) {
  758. event.preventDefault();
  759. return;
  760. }
  761. }
  762. // 处理农场名称输入
  763. function handleFarmNameInput() {
  764. // 标记用户已手动修改过农场名称
  765. isFarmNameManuallyModified.value = true;
  766. }
  767. // 根据地址更新农场名称(如果满足条件)
  768. function updateFarmNameIfNeeded() {
  769. // 只有在创建模式下且用户没有手动修改过农场名称且已选择品类时,才自动更新农场名称
  770. if (route.query.type !== "edit" && !isFarmNameManuallyModified.value && ruleForm.speciesItem && farmCity.value) {
  771. ruleForm.name = farmCity.value + ruleForm.speciesItem.name + "农场";
  772. }
  773. }
  774. // 回填编辑数据
  775. function populateEditData() {
  776. const editData = store.state.home.editFarmData;
  777. if (!editData) {
  778. return;
  779. }
  780. // 回填基本信息
  781. ruleForm.name = editData.name || "";
  782. ruleForm.fzr = editData.fzr || "";
  783. ruleForm.tel = editData.tel || "";
  784. ruleForm.defaultFarm = editData.defaultOption || false;
  785. ruleForm.mu = editData.mianji || "";
  786. ruleForm.address = editData.address || "";
  787. // 设置地图中心点
  788. if (editData.pointWkt) {
  789. centerPoint.value = editData.pointWkt;
  790. const arr = convertPointToArray(editData.pointWkt);
  791. indexMap.setMapPosition(arr);
  792. }
  793. // 处理地块数据
  794. if (editData.geomWkt) {
  795. polygonArr.value = [editData.geomWkt];
  796. indexMap.setAreaGeometry([editData.geomWkt]);
  797. hasDefaultPolygon.value = true;
  798. isFromEditMap.value = true; // 编辑模式下锁定面积输入
  799. }
  800. // 处理作物数据
  801. if (editData.speciesId && editData.speciesName) {
  802. // 设置品类 - 需要匹配模板中的数据结构
  803. ruleForm.speciesItem = {
  804. value: editData.speciesId,
  805. id: editData.speciesId,
  806. name: editData.speciesName,
  807. defaultContainerId: editData.containerId,
  808. };
  809. // 获取品种列表
  810. getFruitsTypeItemList(editData.speciesId);
  811. // 设置品种
  812. if (editData.typeId) {
  813. ruleForm.typeId = editData.typeId;
  814. }
  815. }
  816. // 设置地址信息
  817. if (editData.district) {
  818. try {
  819. const districtInfo = JSON.parse(editData.district);
  820. pointAddress.value = districtInfo.province + districtInfo.city + districtInfo.district;
  821. } catch (e) {
  822. console.warn("解析地址信息失败:", e);
  823. }
  824. }
  825. }
  826. // 处理面积输入
  827. let mianjiInputTimer = null;
  828. function handleMianjiInput(value) {
  829. // 如果是从编辑地图返回的,不允许手动修改
  830. if (isFromEditMap.value) {
  831. return;
  832. }
  833. // 过滤非法字符,只保留数字和小数点
  834. let filteredValue = value.replace(/[^\d.]/g, "");
  835. // 确保只有一个小数点
  836. const parts = filteredValue.split(".");
  837. if (parts.length > 2) {
  838. filteredValue = parts[0] + "." + parts.slice(1).join("");
  839. }
  840. // 限制小数点后最多2位
  841. if (parts.length === 2 && parts[1].length > 2) {
  842. filteredValue = parts[0] + "." + parts[1].substring(0, 2);
  843. }
  844. // 更新输入框的值(如果被过滤了)
  845. if (filteredValue !== value) {
  846. ruleForm.mu = filteredValue;
  847. return;
  848. }
  849. // 清除之前的定时器
  850. if (mianjiInputTimer) {
  851. clearTimeout(mianjiInputTimer);
  852. }
  853. // 防抖处理,用户停止输入500ms后再更新地块
  854. mianjiInputTimer = setTimeout(() => {
  855. const mu = parseFloat(filteredValue);
  856. // 验证输入的有效性
  857. if (!mu || isNaN(mu) || mu <= 0) {
  858. return;
  859. }
  860. // 根据亩数重新生成地块
  861. if (centerPoint.value) {
  862. const arr = convertPointToArray(centerPoint.value);
  863. const squareData = generateSquarePolygonByMu(arr, mu);
  864. const geometryData = {
  865. geometryArr: [squareData.wkt],
  866. mianji: squareData.area,
  867. };
  868. // 清除旧地块
  869. indexMap.clearLayer();
  870. // 绘制新地块
  871. indexMap.setAreaGeometry(geometryData.geometryArr);
  872. // 更新状态
  873. polygonArr.value = geometryData.geometryArr;
  874. // 标记已创建默认地块
  875. hasDefaultPolygon.value = true;
  876. }
  877. }, 500);
  878. }
  879. </script>
  880. <style lang="scss" scoped>
  881. ::v-deep {
  882. .el-form-item--default {
  883. margin-bottom: 20px;
  884. }
  885. }
  886. .create-farm {
  887. position: relative;
  888. width: 100%;
  889. height: 100vh;
  890. overflow: hidden;
  891. .map-container {
  892. width: 100%;
  893. height: calc(100% - 320px);
  894. }
  895. .checkbox {
  896. padding: 0 12px 6px;
  897. font-size: 15px;
  898. }
  899. .farm-content {
  900. position: absolute;
  901. top: 40px;
  902. left: 0;
  903. width: 100%;
  904. height: calc(100% - 40px);
  905. pointer-events: none;
  906. z-index: 2;
  907. .top-mask {
  908. height: 100px;
  909. position: absolute;
  910. z-index: 2;
  911. top: 0;
  912. left: 0;
  913. width: 100%;
  914. background: linear-gradient(0deg, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.6) 100%);
  915. }
  916. }
  917. .farm-filter {
  918. pointer-events: all;
  919. margin: 12px;
  920. position: relative;
  921. z-index: 10;
  922. background: rgba(0, 0, 0, 0.3);
  923. border-radius: 20px;
  924. border: 1px solid rgba(255, 255, 255, 0.4);
  925. &::before {
  926. content: "";
  927. position: absolute;
  928. left: 12px;
  929. top: 9px;
  930. width: 14px;
  931. height: 14px;
  932. background: url("@/assets/img/home/search.png") no-repeat center center / 100% 100%;
  933. }
  934. ::v-deep {
  935. .el-select__wrapper {
  936. background: none;
  937. box-shadow: none;
  938. padding-left: 34px;
  939. font-size: 12px;
  940. .el-select__selected-item,
  941. .el-select__placeholder,
  942. .el-select__input {
  943. color: rgba(255, 255, 255, 0.6);
  944. &.is-transparent {
  945. color: #ccc;
  946. font-size: 12px;
  947. }
  948. }
  949. }
  950. .el-select {
  951. transition: all 0.3s;
  952. .el-input.is-focus .el-input__wrapper {
  953. box-shadow: none !important;
  954. }
  955. }
  956. .el-input {
  957. .el-input__wrapper {
  958. background: none;
  959. box-shadow: none;
  960. padding-left: 18px;
  961. font-size: 11px;
  962. .el-input__inner {
  963. color: rgba(255, 255, 255, 0.6);
  964. }
  965. &.is-focus {
  966. .el-input__inner {
  967. color: #ccc;
  968. font-size: 11px;
  969. }
  970. }
  971. }
  972. }
  973. }
  974. }
  975. .create-wrap {
  976. position: absolute;
  977. bottom: 0px;
  978. left: 0;
  979. width: 100%;
  980. background: linear-gradient(180deg, transparent 0%, #f5f7fb 20%);
  981. }
  982. .create-box {
  983. pointer-events: all;
  984. margin: 0 12px 10px 12px;
  985. width: calc(100% - 24px);
  986. background: #e0f1fe;
  987. border-radius: 14px;
  988. .box-content {
  989. position: relative;
  990. &::after {
  991. position: absolute;
  992. right: 10px;
  993. top: 2px;
  994. content: "";
  995. width: 79px;
  996. height: 72px;
  997. background: url("@/assets/img/home/creat-bg.png") no-repeat center / 100% 100%;
  998. }
  999. }
  1000. .create-title {
  1001. display: flex;
  1002. align-items: center;
  1003. padding: 12px 6px 12px 12px;
  1004. color: #0089f5;
  1005. font-size: 18px;
  1006. font-weight: bold;
  1007. .title-icon {
  1008. width: 18px;
  1009. padding-right: 10px;
  1010. }
  1011. }
  1012. .create-content {
  1013. background: #fff;
  1014. border-radius: 14px;
  1015. padding: 12px;
  1016. position: relative;
  1017. z-index: 2;
  1018. .create-from {
  1019. .select-wrap {
  1020. display: flex;
  1021. // width: 86%;
  1022. ::v-deep {
  1023. .el-input__wrapper {
  1024. background: none;
  1025. box-shadow: none;
  1026. }
  1027. .el-input__inner {
  1028. font-size: 14px;
  1029. color: rgba(0, 0, 0, 0.5);
  1030. }
  1031. .el-select__wrapper {
  1032. background: none;
  1033. box-shadow: none;
  1034. gap: 2px;
  1035. padding: 4px 2px;
  1036. justify-content: center;
  1037. }
  1038. .el-select__selection {
  1039. flex: none;
  1040. width: fit-content;
  1041. }
  1042. .el-select__placeholder {
  1043. color: #000;
  1044. position: static;
  1045. transform: none;
  1046. width: fit-content;
  1047. }
  1048. }
  1049. &.client-wrap {
  1050. ::v-deep {
  1051. .el-select__wrapper {
  1052. justify-content: flex-start;
  1053. }
  1054. }
  1055. }
  1056. // .select-item {
  1057. // width: fit-content;
  1058. // }
  1059. .period-select {
  1060. margin-left: 6px;
  1061. }
  1062. .select-item {
  1063. min-width: 76px;
  1064. }
  1065. }
  1066. ::v-deep {
  1067. .el-form-item__label {
  1068. color: #000;
  1069. }
  1070. .el-form-item__error {
  1071. top: 117%;
  1072. }
  1073. .el-form-item {
  1074. position: relative;
  1075. &::after {
  1076. content: "";
  1077. position: absolute;
  1078. left: 60px;
  1079. bottom: -5px;
  1080. width: calc(100% - 60px);
  1081. height: 1px;
  1082. background: rgba(0, 0, 0, 0.08);
  1083. }
  1084. }
  1085. .el-input__wrapper {
  1086. box-shadow: none;
  1087. padding: 1px 6px;
  1088. }
  1089. }
  1090. .area-box {
  1091. display: flex;
  1092. align-items: center;
  1093. width: 100%;
  1094. .unit {
  1095. padding-right: 10px;
  1096. }
  1097. }
  1098. .position-wrap {
  1099. display: flex;
  1100. justify-content: space-between;
  1101. align-items: center;
  1102. .draw-btn {
  1103. flex: none;
  1104. padding: 0 12px;
  1105. height: 30px;
  1106. line-height: 30px;
  1107. box-sizing: border-box;
  1108. color: #2199f8;
  1109. border: 1px solid #2199f8;
  1110. background: rgba(33, 153, 248, 0.1);
  1111. border-radius: 20px;
  1112. font-size: 12px;
  1113. }
  1114. }
  1115. }
  1116. .create-btn {
  1117. display: flex;
  1118. align-items: center;
  1119. width: 100%;
  1120. padding-top: 10px;
  1121. .btn-item {
  1122. flex: 1;
  1123. text-align: center;
  1124. padding: 0 11px;
  1125. height: 40px;
  1126. line-height: 40px;
  1127. border-radius: 34px;
  1128. font-size: 16px;
  1129. box-sizing: border-box;
  1130. &.sencond-btn {
  1131. border: 1px solid rgba(153, 153, 153, 0.5);
  1132. color: #666666;
  1133. }
  1134. &.primary-btn {
  1135. background: linear-gradient(180deg, #76c3ff, #2199f8);
  1136. color: #fff;
  1137. }
  1138. }
  1139. .btn-item + .btn-item {
  1140. margin-left: 5px;
  1141. }
  1142. }
  1143. }
  1144. }
  1145. }
  1146. </style>
  1147. <style lang="scss">
  1148. .location-search-popper {
  1149. .el-select-dropdown__list {
  1150. max-width: 96vw;
  1151. overflow-x: auto;
  1152. }
  1153. .sub-title {
  1154. padding-left: 6px;
  1155. font-size: 12px;
  1156. color: #ccc;
  1157. }
  1158. }
  1159. </style>