baInformation.vue 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  1. <template>
  2. <div class="ba-information">
  3. <div class="ba-information__content">
  4. <div class="page-header">
  5. <div class="page-title">请完善农场信息</div>
  6. </div>
  7. <div class="info-card">
  8. <div class="section-title">
  9. <img class="title-icon" src="@/assets/img/home/label-icon.png" alt="" />
  10. <span>基本信息</span>
  11. </div>
  12. <el-form
  13. ref="formRef"
  14. :model="form"
  15. :rules="rules"
  16. label-position="left"
  17. label-width="72px"
  18. class="info-form"
  19. require-asterisk-position="right"
  20. >
  21. <el-form-item label="姓名" prop="name">
  22. <el-input
  23. v-model="form.name"
  24. placeholder="请输入名字"
  25. maxlength="20"
  26. clearable
  27. />
  28. </el-form-item>
  29. <el-form-item label="手机号" prop="phone">
  30. <el-input
  31. v-model="form.phone"
  32. placeholder="请输入手机号"
  33. maxlength="11"
  34. clearable
  35. type="tel"
  36. />
  37. </el-form-item>
  38. <el-form-item label="种植品类" prop="crop">
  39. <el-select
  40. v-model="form.crop"
  41. class="crop-select"
  42. placeholder="选择品类"
  43. placement="bottom-end"
  44. popper-class="crop-select-popper"
  45. teleported
  46. :loading="cropLoading"
  47. >
  48. <el-option
  49. v-for="item in cropOptions"
  50. :key="item.name"
  51. :label="item.name"
  52. :value="item.name"
  53. />
  54. </el-select>
  55. </el-form-item>
  56. <el-form-item label="种植点位" prop="location" class="location-form-item">
  57. <div class="location-block" @click="goSelectLocation">
  58. <div class="map-preview">
  59. <div class="map-preview__map" ref="previewMapRef"></div>
  60. <div v-if="!form.location" class="map-preview__mask">点击地图选择种植点位</div>
  61. </div>
  62. </div>
  63. </el-form-item>
  64. </el-form>
  65. </div>
  66. </div>
  67. <div class="custom-bottom-fixed-btns">
  68. <div
  69. class="bottom-btn primary-btn"
  70. :class="{ disabled: submitting }"
  71. @click="handleNext"
  72. >
  73. {{ submitting ? "提交中..." : "确认信息" }}
  74. </div>
  75. </div>
  76. </div>
  77. </template>
  78. <script setup>
  79. import { nextTick, onActivated, onBeforeUnmount, onMounted, reactive, ref } from "vue";
  80. import { useRoute, useRouter } from "vue-router";
  81. import { useStore } from "vuex";
  82. import { ElMessage } from "element-plus";
  83. import SelectLocationMap from "../map/selectLocationMap.js";
  84. const LOCATION_KEY = "ENTRY_RESIDENT_LOCATION";
  85. const FORM_KEY = "ENTRY_BA_FORM";
  86. const STEP_KEY = "ENTRY_INFORMATION_STEP";
  87. const EQUIPMENT_KEY = "ENTRY_SELECTED_EQUIPMENT";
  88. /** 本地标记:用户已新增农场 */
  89. const HAS_FARM_KEY = "HAS_ENTRY_FARM";
  90. /** 新增农场信息(点位、品类等) */
  91. const ENTRY_FARM_DATA_KEY = "ENTRY_FARM_DATA";
  92. /** 默认定位:河北宁晋县 */
  93. const DEFAULT_POINT = "POINT(114.91863572509733 37.67702031436258)";
  94. /** 默认区县:河北宁晋县 */
  95. const DEFAULT_COUNTY_CODE = "130528";
  96. const MAP_KEY = "CZLBZ-LJICQ-R4A5J-BN62X-YXCRJ-GNBUT";
  97. const router = useRouter();
  98. const route = useRoute();
  99. const store = useStore();
  100. const formRef = ref(null);
  101. const previewMapRef = ref(null);
  102. let previewMap = null;
  103. const cropOptions = ref([]);
  104. const cropLoading = ref(false);
  105. const submitting = ref(false);
  106. /** 区县接口附带的气象预警 / 胁迫,确认时写入 ENTRY_FARM_DATA */
  107. const weatherMeta = reactive({
  108. weatherRisk: "",
  109. weatherStress: "",
  110. });
  111. const form = reactive({
  112. name: "",
  113. phone: "",
  114. crop: undefined,
  115. location: "",
  116. });
  117. const rules = {
  118. name: [
  119. { required: true, message: "请输入名字", trigger: "blur" },
  120. { min: 1, max: 20, message: "姓名长度不超过20个字", trigger: "blur" },
  121. ],
  122. phone: [
  123. { required: true, message: "请输入手机号", trigger: "blur" },
  124. {
  125. pattern: /^1[3-9]\d{9}$/,
  126. message: "请输入正确的手机号码",
  127. trigger: "blur",
  128. },
  129. ],
  130. crop: [{ required: true, message: "请选择种植品类", trigger: "change" }],
  131. location: [{ required: true, message: "请选择常驻点位", trigger: "change" }],
  132. };
  133. function getDefaultPoint() {
  134. return DEFAULT_POINT;
  135. }
  136. function readJson(key) {
  137. try {
  138. const raw = sessionStorage.getItem(key);
  139. return raw ? JSON.parse(raw) : null;
  140. } catch {
  141. return null;
  142. }
  143. }
  144. function saveFormDraft() {
  145. sessionStorage.setItem(
  146. FORM_KEY,
  147. JSON.stringify({ name: form.name, phone: form.phone, crop: form.crop })
  148. );
  149. }
  150. function restoreFormDraft() {
  151. const draft = readJson(FORM_KEY);
  152. if (!draft) return;
  153. if (draft.name != null) form.name = draft.name;
  154. if (draft.phone != null) form.phone = draft.phone;
  155. if (draft.crop) form.crop = draft.crop;
  156. }
  157. function utilWktToCoordinate(point) {
  158. const match = String(point).match(/POINT\s*\(([\d.\-]+)\s+([\d.\-]+)\)/i);
  159. if (!match) return null;
  160. return [Number(match[1]), Number(match[2])];
  161. }
  162. function initPreviewMap(point, showPoint = !!form.location) {
  163. if (!previewMapRef.value || !point) return;
  164. const previewPadding = [50, 0, 10, 0];
  165. const coordinate = utilWktToCoordinate(point);
  166. if (!previewMap) {
  167. previewMap = new SelectLocationMap();
  168. previewMap.initMap(point, previewMapRef.value, {
  169. enableClick: false,
  170. padding: previewPadding,
  171. showPoint,
  172. });
  173. return;
  174. }
  175. if (previewMap.kmap) {
  176. if (coordinate) {
  177. if (showPoint) {
  178. previewMap.showPoint(coordinate);
  179. } else {
  180. previewMap.hidePoint();
  181. previewMap.setMapPosition(coordinate, false);
  182. }
  183. }
  184. return;
  185. }
  186. previewMap.initMap(point, previewMapRef.value, {
  187. enableClick: false,
  188. padding: previewPadding,
  189. showPoint,
  190. });
  191. }
  192. function syncLocationFromSession() {
  193. const saved = readJson(LOCATION_KEY);
  194. if (saved?.point) {
  195. form.location = saved.point;
  196. formRef.value?.clearValidate("location");
  197. nextTick(() => initPreviewMap(saved.point, true));
  198. return;
  199. }
  200. nextTick(() => initPreviewMap(getDefaultPoint(), false));
  201. }
  202. /** 解析当前区县 code:优先选点 adcode,否则默认宁晋县 */
  203. function resolveCountyCode() {
  204. const saved = readJson(LOCATION_KEY);
  205. if (saved?.adcode) return String(saved.adcode);
  206. return DEFAULT_COUNTY_CODE;
  207. }
  208. async function fetchCropOptions() {
  209. const countyCode = resolveCountyCode();
  210. cropLoading.value = true;
  211. try {
  212. const res = await VE_API.questionnaire.countyPhenophase({
  213. county_code: countyCode,
  214. });
  215. if (res?.code != null && res.code !== 200) {
  216. cropOptions.value = [];
  217. weatherMeta.weatherRisk = "";
  218. weatherMeta.weatherStress = "";
  219. ElMessage.error(res.msg || "获取种植品类失败");
  220. return;
  221. }
  222. weatherMeta.weatherRisk = res?.data?.weather_risk || "";
  223. weatherMeta.weatherStress = res?.data?.weather_stress || "";
  224. const list = Array.isArray(res?.data?.phenophases) ? res.data.phenophases : [];
  225. const options = [];
  226. const seen = new Set();
  227. list.forEach((item) => {
  228. const name = item?.crop_category_name;
  229. if (typeof name !== "string" || !name.trim() || seen.has(name)) return;
  230. seen.add(name);
  231. options.push({
  232. name,
  233. code: item?.phenophase_code != null ? String(item.phenophase_code) : "",
  234. });
  235. });
  236. cropOptions.value = options;
  237. if (form.crop && !seen.has(form.crop)) {
  238. form.crop = undefined;
  239. }
  240. } catch {
  241. cropOptions.value = [];
  242. weatherMeta.weatherRisk = "";
  243. weatherMeta.weatherStress = "";
  244. ElMessage.error("获取种植品类失败,请稍后再试");
  245. } finally {
  246. cropLoading.value = false;
  247. }
  248. }
  249. const goSelectLocation = () => {
  250. saveFormDraft();
  251. const mapCenter = form.location || getDefaultPoint();
  252. router.push({
  253. path: "/entry_select_location",
  254. query: { mapCenter },
  255. });
  256. };
  257. function clearFormDraft() {
  258. form.name = "";
  259. form.phone = "";
  260. form.crop = undefined;
  261. form.location = "";
  262. sessionStorage.removeItem(FORM_KEY);
  263. sessionStorage.removeItem(LOCATION_KEY);
  264. sessionStorage.removeItem(STEP_KEY);
  265. }
  266. /** 根据点位反查地区名(区县优先) */
  267. async function resolveRegionName(point) {
  268. const coordinate = utilWktToCoordinate(point);
  269. if (!coordinate) return "";
  270. try {
  271. const { result } = await VE_API.old_mini_map.location({
  272. key: MAP_KEY,
  273. location: `${coordinate[1]},${coordinate[0]}`,
  274. });
  275. return (
  276. result?.ad_info?.district ||
  277. result?.ad_info?.city ||
  278. result?.address_component?.district ||
  279. result?.address_component?.city ||
  280. ""
  281. );
  282. } catch {
  283. return "";
  284. }
  285. }
  286. function toFiniteNumber(value, fallback) {
  287. const n = Number(value);
  288. return Number.isFinite(n) ? n : fallback;
  289. }
  290. function formatDateYMD(date = new Date()) {
  291. return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
  292. }
  293. /** 邀请管理员 id:优先路由参数 */
  294. function resolveAdminId() {
  295. return toFiniteNumber(route.query.adminId ?? route.query.admin_id, 1);
  296. }
  297. function resolveUserId() {
  298. return toFiniteNumber(store.state.home.miniUserId || localStorage.getItem("MINI_USER_ID"), 1);
  299. }
  300. /** 已选农机 id(当前简化流程可能为空) */
  301. function resolveMachineIds() {
  302. try {
  303. const cache = JSON.parse(sessionStorage.getItem(EQUIPMENT_KEY) || "null");
  304. if (!cache) return [];
  305. const list = Array.isArray(cache)
  306. ? cache
  307. : [...(cache.field || []), ...(cache.fruit || []), ...(cache.list || [])];
  308. return list
  309. .map((item) => Number(item?.id ?? item?.machine_id))
  310. .filter((id) => Number.isFinite(id));
  311. } catch {
  312. return [];
  313. }
  314. }
  315. /**
  316. * 组装 crops:优先已选品种草稿,否则用当前品类 + 点位
  317. * 结构对齐 add_plot_info 文档
  318. */
  319. function buildCropsPayload(point, selectedCrop, cropName) {
  320. try {
  321. const varietyList = JSON.parse(sessionStorage.getItem("ENTRY_SELECTED_VARIETY_LIST") || "[]");
  322. if (Array.isArray(varietyList) && varietyList.length) {
  323. return varietyList.map((item) => ({
  324. crop_type: item.categoryName || cropName || "",
  325. crop_id: toFiniteNumber(item.categoryId, 0),
  326. variety_list: item.id != null ? [String(item.id)] : [],
  327. phenophase:
  328. item.phenophase ||
  329. item.phenologyName ||
  330. (item.phenologyId != null ? String(item.phenologyId) : "") ||
  331. selectedCrop?.code ||
  332. "",
  333. start_time: item.startTime || formatDateYMD(),
  334. plant_area: toFiniteNumber(item.area, 0),
  335. point: item.location || point || "",
  336. }));
  337. }
  338. } catch {
  339. // ignore
  340. }
  341. return [
  342. {
  343. crop_type: cropName || "",
  344. crop_id: toFiniteNumber(selectedCrop?.cropId, 0),
  345. variety_list: [],
  346. phenophase: selectedCrop?.code || "",
  347. start_time: formatDateYMD(),
  348. plant_area: 0,
  349. point: point || "",
  350. },
  351. ];
  352. }
  353. const handleNext = async () => {
  354. if (!formRef.value || submitting.value) return;
  355. try {
  356. await formRef.value.validate();
  357. } catch {
  358. return;
  359. }
  360. const saved = readJson(LOCATION_KEY);
  361. let region = saved?.region || "";
  362. if (!region && form.location) {
  363. region = await resolveRegionName(form.location);
  364. }
  365. if (!region) {
  366. ElMessage.warning("无法识别种植点位所属地区,请重新选择");
  367. return;
  368. }
  369. const crop = form.crop;
  370. const selectedCrop = cropOptions.value.find((item) => item.name === crop);
  371. const cropCode = selectedCrop?.code || "";
  372. const point = form.location || saved?.point || "";
  373. const countyCode = toFiniteNumber(saved?.adcode || resolveCountyCode(), Number(DEFAULT_COUNTY_CODE));
  374. submitting.value = true;
  375. try {
  376. const raw = await VE_API.questionnaire.addPlotInfo({
  377. user_name: form.name,
  378. tel: form.phone,
  379. admin_id: resolveAdminId(),
  380. user_id: resolveUserId(),
  381. machine_id: resolveMachineIds(),
  382. county_code: countyCode,
  383. crops: buildCropsPayload(point, selectedCrop, crop),
  384. });
  385. // 兼容 {code,data} 或 [{code,data}, status]
  386. const res = Array.isArray(raw) ? raw[0] : raw;
  387. const code = Number(res?.code);
  388. const ok = code === 200 || code === 0 || code === 1;
  389. if (!ok) {
  390. ElMessage.error(res?.message || res?.msg || "提交失败,请稍后再试");
  391. return;
  392. }
  393. const farmData = {
  394. name: form.name,
  395. phone: form.phone,
  396. crop,
  397. cropCode,
  398. point,
  399. coordinate: saved?.coordinate || null,
  400. region,
  401. adcode: saved?.adcode || String(countyCode),
  402. weatherRisk: weatherMeta.weatherRisk,
  403. weatherStress: weatherMeta.weatherStress,
  404. farmId: res?.data?.farm_id ?? null,
  405. };
  406. localStorage.setItem(ENTRY_FARM_DATA_KEY, JSON.stringify(farmData));
  407. if (point) {
  408. localStorage.setItem("GROWTH_REPORT_MAP_POINT", point);
  409. localStorage.setItem("selectedFarmPoint", point);
  410. }
  411. localStorage.setItem(HAS_FARM_KEY, "1");
  412. VE_API.questionnaire.generateReport({ region, crop, tel:form.phone }).catch(() => {});
  413. clearFormDraft();
  414. ElMessage.success(res?.message || res?.msg || "上传成功,报告正在生成中...");
  415. router.replace("/growth_report");
  416. } catch (e) {
  417. console.error("addPlotInfo failed", e);
  418. ElMessage.error("提交失败,请稍后再试");
  419. } finally {
  420. submitting.value = false;
  421. }
  422. };
  423. onMounted(() => {
  424. restoreFormDraft();
  425. syncLocationFromSession();
  426. });
  427. onActivated(() => {
  428. restoreFormDraft();
  429. syncLocationFromSession();
  430. fetchCropOptions();
  431. });
  432. onBeforeUnmount(() => {
  433. previewMap?.clearLayer();
  434. previewMap = null;
  435. });
  436. </script>
  437. <style lang="scss" scoped>
  438. .ba-information {
  439. flex: 1;
  440. display: flex;
  441. flex-direction: column;
  442. overflow: hidden;
  443. padding-bottom: 80px;
  444. &__content {
  445. flex: 1;
  446. overflow-y: auto;
  447. padding: 8px 16px 20px;
  448. }
  449. .page-header {
  450. padding: 8px 4px 16px;
  451. .page-title {
  452. font-size: 26px;
  453. color: #005599;
  454. font-family: "PangMenZhengDao";
  455. line-height: 36px;
  456. }
  457. .page-subtitle {
  458. margin-top: 4px;
  459. font-size: 14px;
  460. color: rgba(46, 46, 46, 0.4);
  461. line-height: 20px;
  462. }
  463. }
  464. .info-card {
  465. background: #fff;
  466. border-radius: 12px;
  467. padding: 16px 14px 8px;
  468. box-shadow: 0 2px 12px rgba(33, 153, 248, 0.08);
  469. }
  470. .section-title {
  471. display: flex;
  472. align-items: center;
  473. gap: 8px;
  474. margin-bottom: 8px;
  475. font-size: 16px;
  476. font-weight: 600;
  477. color: #1a1a1a;
  478. .title-icon {
  479. width: 14px;
  480. height: 14px;
  481. flex-shrink: 0;
  482. object-fit: contain;
  483. }
  484. }
  485. .info-form {
  486. :deep(.el-form-item) {
  487. margin-bottom: 0;
  488. padding: 10px 0;
  489. }
  490. :deep(.el-form-item__label) {
  491. color: #1a1a1a;
  492. font-size: 15px;
  493. font-weight: 400;
  494. padding: 0;
  495. line-height: 32px;
  496. height: 32px;
  497. }
  498. :deep(.el-form-item__content) {
  499. justify-content: flex-end;
  500. line-height: 32px;
  501. }
  502. :deep(.el-form-item__error) {
  503. padding-top: 4px;
  504. text-align: right;
  505. }
  506. :deep(.el-input__wrapper) {
  507. box-shadow: none;
  508. background: transparent;
  509. padding: 0;
  510. .el-input__inner {
  511. text-align: right;
  512. color: #1a1a1a;
  513. font-size: 15px;
  514. &::placeholder {
  515. color: rgba(0, 0, 0, 0.25);
  516. }
  517. }
  518. }
  519. .crop-select {
  520. width: 120px;
  521. flex-shrink: 0;
  522. margin-left: auto;
  523. height: 32px;
  524. :deep(.el-select__wrapper) {
  525. box-shadow: none;
  526. background: transparent;
  527. padding: 0;
  528. height: 32px;
  529. min-height: 32px !important;
  530. width: 100%;
  531. align-items: center;
  532. flex-wrap: nowrap;
  533. justify-content: flex-end;
  534. }
  535. :deep(.el-select__selection) {
  536. position: relative;
  537. flex: 1;
  538. min-width: 0;
  539. height: 32px;
  540. display: flex;
  541. align-items: center;
  542. justify-content: flex-end;
  543. }
  544. :deep(.el-select__selected-item) {
  545. font-size: 15px;
  546. color: #1a1a1a;
  547. line-height: 32px;
  548. height: 32px;
  549. display: flex;
  550. align-items: center;
  551. justify-content: flex-end;
  552. }
  553. :deep(.el-select__placeholder) {
  554. position: absolute;
  555. inset: 0;
  556. display: flex;
  557. align-items: center;
  558. justify-content: flex-end;
  559. margin: 0;
  560. font-size: 15px;
  561. color: #1a1a1a;
  562. line-height: 32px;
  563. transform: none;
  564. }
  565. /* EP:is-transparent 表示未选中的占位态,不是隐藏文字 */
  566. :deep(.el-select__placeholder.is-transparent) {
  567. color: #2199f8;
  568. }
  569. :deep(.el-select__suffix) {
  570. display: flex;
  571. align-items: center;
  572. height: 32px;
  573. flex-shrink: 0;
  574. }
  575. :deep(.el-select__caret) {
  576. color: #2199f8;
  577. font-size: 14px;
  578. }
  579. }
  580. .location-form-item {
  581. display: block;
  582. :deep(.el-form-item__label) {
  583. float: none;
  584. display: block;
  585. text-align: left;
  586. width: auto !important;
  587. margin-bottom: 10px;
  588. height: auto;
  589. line-height: 22px;
  590. }
  591. :deep(.el-form-item__content) {
  592. margin-left: 0 !important;
  593. line-height: normal;
  594. justify-content: flex-start;
  595. }
  596. :deep(.el-form-item__error) {
  597. text-align: left;
  598. padding-top: 6px;
  599. }
  600. }
  601. }
  602. .location-block {
  603. width: 100%;
  604. .map-preview {
  605. position: relative;
  606. width: 100%;
  607. height: 140px;
  608. border-radius: 8px;
  609. overflow: hidden;
  610. background: linear-gradient(135deg, #e8eef3 0%, #d4dde6 100%);
  611. &__map {
  612. width: 100%;
  613. height: 100%;
  614. pointer-events: none;
  615. }
  616. &__mask {
  617. position: absolute;
  618. left: 0;
  619. top: 0;
  620. z-index: 2;
  621. padding: 0 12px;
  622. height: 30px;
  623. line-height: 30px;
  624. background: rgba(0, 0, 0, 0.4);
  625. color: #fff;
  626. font-size: 14px;
  627. text-align: center;
  628. width: fit-content;
  629. border-radius: 8px 0 8px 0;
  630. }
  631. }
  632. }
  633. .custom-bottom-fixed-btns {
  634. background: #fff;
  635. box-shadow: 2px 2px 5px 0px rgba(0, 0, 0, 0.4);
  636. .bottom-btn {
  637. padding: 0 30px;
  638. height: 40px;
  639. line-height: 40px;
  640. font-size: 14px;
  641. border-radius: 25px;
  642. &.disabled {
  643. opacity: 0.6;
  644. pointer-events: none;
  645. }
  646. }
  647. .primary-btn {
  648. background: #2199f8;
  649. color: #fff;
  650. }
  651. }
  652. }
  653. </style>
  654. <style lang="scss">
  655. .crop-select-popper {
  656. min-width: 120px !important;
  657. }
  658. </style>