index.vue 41 KB

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