index.vue 45 KB

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