index.vue 47 KB

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