restorePlantingPopup.vue 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  1. <template>
  2. <popup
  3. v-model:show="visible"
  4. round
  5. teleport="body"
  6. :z-index="20000"
  7. class="restore-planting-popup"
  8. :close-on-click-overlay="true"
  9. >
  10. <div class="popup-content">
  11. <img
  12. class="restore-planting-popup__decor"
  13. src="@/assets/img/agricultural/question.png"
  14. alt=""
  15. />
  16. <div class="restore-planting-popup__header">
  17. <div class="restore-planting-popup__title">
  18. <div>{{ t("agriFile.restoreFillQuestions") }}</div>
  19. <div>{{ t("agriFile.restorePlantingService") }}</div>
  20. </div>
  21. </div>
  22. <!-- 问题一:选择时间 -->
  23. <div v-if="questionType === 'time'" class="restore-planting-popup__card">
  24. <div class="restore-planting-popup__question">
  25. <template v-if="highlightWord && questionText.includes(highlightWord)">
  26. <span>{{ questionText.split(highlightWord)[0] }}</span>
  27. <span class="restore-planting-popup__keyword">{{ highlightWord }}</span>
  28. <span>{{ questionText.split(highlightWord).slice(1).join(highlightWord) }}</span>
  29. </template>
  30. <template v-else>{{ questionText }}</template>
  31. </div>
  32. <div class="restore-planting-popup__hint">{{ hintText }}</div>
  33. <div class="restore-planting-popup__photo">
  34. <img :src="sampleImage" alt="" />
  35. </div>
  36. <el-date-picker
  37. v-model="selectedDate"
  38. class="restore-planting-popup__date-picker"
  39. type="date"
  40. format="YYYY.MM.DD"
  41. value-format="YYYY.MM.DD"
  42. :placeholder="t('agriFile.selectTime')"
  43. :editable="false"
  44. :clearable="false"
  45. teleported
  46. popper-class="restore-planting-date-popper"
  47. style="width: 100%"
  48. />
  49. </div>
  50. <!-- 问题二:物候期选择 -->
  51. <div v-else class="restore-planting-popup__card">
  52. <div class="restore-planting-popup__question">
  53. <template v-if="phenologyHighlight && phenologyQuestion.includes(phenologyHighlight)">
  54. <span>{{ phenologyQuestion.split(phenologyHighlight)[0] }}</span>
  55. <span class="restore-planting-popup__keyword">{{ phenologyHighlight }}</span>
  56. <span>{{ phenologyQuestion.split(phenologyHighlight).slice(1).join(phenologyHighlight) }}</span>
  57. </template>
  58. <template v-else>{{ phenologyQuestion }}</template>
  59. </div>
  60. <div class="restore-planting-popup__photo restore-planting-popup__photo--guide">
  61. <img :src="phenologyImage" alt="" />
  62. <photo-provider :photo-closable="true">
  63. <photo-consumer :src="patrolGuideImage" :intro="patrolGuideImage">
  64. <div class="restore-planting-popup__guide-btn">
  65. {{ t("agriFile.viewPatrolGuide") }}
  66. </div>
  67. </photo-consumer>
  68. </photo-provider>
  69. </div>
  70. <div class="restore-planting-popup__options">
  71. <div
  72. v-for="item in phenologyOptions"
  73. :key="item.value"
  74. class="restore-planting-popup__option"
  75. :class="{ active: phenologyAnswer === item.value }"
  76. @click="handlePhenologySelect(item.value)"
  77. >
  78. <span>{{ item.label }}</span>
  79. <span v-if="phenologyAnswer === item.value" class="restore-planting-popup__option-check">
  80. <el-icon><Check /></el-icon>
  81. </span>
  82. </div>
  83. </div>
  84. </div>
  85. <div class="restore-planting-popup__actions">
  86. <div
  87. class="restore-planting-popup__btn restore-planting-popup__btn--primary"
  88. :class="{ disabled: submitting }"
  89. @click="handleConfirm"
  90. >
  91. {{ questionType === "time" ? t("agriFile.confirmNow") : t("agriFile.submitInfo") }}
  92. </div>
  93. </div>
  94. </div>
  95. </popup>
  96. </template>
  97. <script setup>
  98. import { computed, onActivated, onDeactivated, ref } from "vue";
  99. import { Popup } from "vant";
  100. import { Check } from "@element-plus/icons-vue";
  101. import { ElMessage } from "element-plus";
  102. import { useI18n } from "@/i18n";
  103. import { base_img_url2 } from "@/api/config";
  104. const { t } = useI18n();
  105. // ---------------------------------------------------------------------------
  106. // Props
  107. // ---------------------------------------------------------------------------
  108. const props = defineProps({
  109. /** 分区 id;不传则读当前选中农场缓存 */
  110. zoneId: { type: [Number, String], default: null },
  111. });
  112. // ---------------------------------------------------------------------------
  113. // 常量
  114. // ---------------------------------------------------------------------------
  115. const PHENOLOGY_PREFIX = "您的农场是否进入到 ";
  116. const DEFAULT_SAMPLE_IMAGE = require("@/assets/img/agricultural/baidian.png");
  117. const DEFAULT_PHENOLOGY_IMAGE = require("@/assets/img/common/sd-1.jpg");
  118. /** 巡园向导预览图 */
  119. const PATROL_GUIDE_IMAGE_PATH =
  120. "e84a8f1b-9842-434c-951f-068ff6963f31/6c8b7135-95b7-4c04-82ef-a2daeb674d0c/DJI_202608190758_001_6c8b7135-95b7-4c04-82ef-a2daeb674d0c/DJI_20260819080818_0085_V_code-ws0fsmg8zg8u.jpeg";
  121. const patrolGuideImage = base_img_url2 + PATROL_GUIDE_IMAGE_PATH;
  122. // ---------------------------------------------------------------------------
  123. // 页面状态
  124. // ---------------------------------------------------------------------------
  125. /** 弹窗显隐由接口数据控制,默认不展示 */
  126. const visible = ref(false);
  127. const questionType = ref("time"); // time | phenology
  128. const selectedDate = ref("");
  129. const phenologyAnswer = ref("");
  130. const submitting = ref(false);
  131. const hasDateInteract = ref(false);
  132. const hasOptionsInteract = ref(false);
  133. /** date_interact 原始数据,提交时可能用到 */
  134. const dateInteractData = ref(null);
  135. /** options_interact.interact 映射表,key 为 start_with 同类序号 */
  136. const interactMap = ref({});
  137. /** 当前展示的物候期序号(对应 interact 的 key) */
  138. const currentInteractKey = ref("");
  139. /** 用户确认「已到达」后写入,提交接口使用 */
  140. const selectedPeriodCode = ref("");
  141. const questionText = ref("");
  142. const highlightWord = ref("");
  143. const hintText = ref("");
  144. const sampleImage = ref(DEFAULT_SAMPLE_IMAGE);
  145. const phenologyQuestion = ref("");
  146. const phenologyHighlight = ref("");
  147. const phenologyImage = ref(DEFAULT_PHENOLOGY_IMAGE);
  148. // ---------------------------------------------------------------------------
  149. // 计算属性
  150. // ---------------------------------------------------------------------------
  151. const phenologyOptions = computed(() => [
  152. { value: "not_reached", label: t("agriFile.notReached") },
  153. { value: "reached", label: t("agriFile.reached") },
  154. { value: "passed", label: t("agriFile.passed") },
  155. ]);
  156. const interactKeys = computed(() =>
  157. Object.keys(interactMap.value).sort((a, b) => Number(a) - Number(b))
  158. );
  159. const getSelectedFarmId = () => {
  160. try {
  161. const farm = JSON.parse(localStorage.getItem("selectedFarmData") || "{}");
  162. return String(
  163. localStorage.getItem("selectedFarmId") || farm.farm_id || farm.id || ""
  164. );
  165. } catch {
  166. return String(localStorage.getItem("selectedFarmId") || "");
  167. }
  168. };
  169. const getSelectedZoneId = () => {
  170. try {
  171. const farm = JSON.parse(localStorage.getItem("selectedFarmData") || "{}");
  172. return farm.zone_id ?? farm.zoneId ?? null;
  173. } catch {
  174. return null;
  175. }
  176. };
  177. /** 每次实时读缓存,避免 computed 缓存旧 zone_id */
  178. const resolveZoneId = () => props.zoneId ?? getSelectedZoneId();
  179. /** 上次成功请求对应的农场/分区 */
  180. let lastFetchedFarmKey = "";
  181. /** 递增后旧请求的返回不再打开弹窗 */
  182. let requestSeq = 0;
  183. /** 当前页是否处于前台,离开后迟到的响应不展示 */
  184. let pageActive = false;
  185. const getFarmFetchKey = () => `${getSelectedFarmId()}|${resolveZoneId() ?? ""}`;
  186. // ---------------------------------------------------------------------------
  187. // 工具函数
  188. // ---------------------------------------------------------------------------
  189. /** 当天日期 YYYY-MM-DD */
  190. const formatToday = () => {
  191. const d = new Date();
  192. const y = d.getFullYear();
  193. const m = String(d.getMonth() + 1).padStart(2, "0");
  194. const day = String(d.getDate()).padStart(2, "0");
  195. return `${y}-${m}-${day}`;
  196. };
  197. /** 日期选择器 YYYY.MM.DD → 接口 YYYY-MM-DD */
  198. const toApiDate = (value) => (value ? String(value).replace(/\./g, "-") : "");
  199. /** 拼接 CDN 图片地址 */
  200. const resolveImageUrl = (path) => {
  201. if (!path) return "";
  202. if (/^https?:\/\//i.test(path)) return path;
  203. return base_img_url2 + String(path).replace(/^\//, "");
  204. };
  205. /** 从 interact_theme 引号中提取高亮词,如「来梢」 */
  206. const extractHighlightWord = (text) => {
  207. if (!text) return "";
  208. const match = String(text).match(/[“"「]([^”"」]+)[”"」]/);
  209. return match ? match[1] : "";
  210. };
  211. /** Message 需高于弹窗 z-index: 20000 */
  212. const showMessage = (message, type = "warning") => {
  213. ElMessage({
  214. message,
  215. type,
  216. customClass: "restore-planting-message",
  217. zIndex: 40000,
  218. });
  219. };
  220. const showWarning = (message) => showMessage(message, "warning");
  221. const resetForm = () => {
  222. questionType.value = hasDateInteract.value ? "time" : "phenology";
  223. selectedDate.value = "";
  224. phenologyAnswer.value = "";
  225. selectedPeriodCode.value = "";
  226. };
  227. // ---------------------------------------------------------------------------
  228. // 业务逻辑:填充问题 / 物候期切换
  229. // ---------------------------------------------------------------------------
  230. const applyDateInteract = (data) => {
  231. dateInteractData.value = data;
  232. questionText.value = data.interact_theme || "";
  233. highlightWord.value = extractHighlightWord(data.interact_theme);
  234. hintText.value = data.interact_reason || "";
  235. sampleImage.value = resolveImageUrl(data.guide_url) || DEFAULT_SAMPLE_IMAGE;
  236. };
  237. /** 按 interact key 刷新问题二文案与配图 */
  238. const applyPhenologyByKey = (key) => {
  239. const item = interactMap.value[key];
  240. if (!item) return;
  241. currentInteractKey.value = String(key);
  242. const name = item.period_name || "";
  243. phenologyHighlight.value = name;
  244. phenologyQuestion.value = `${PHENOLOGY_PREFIX}${name} ?`;
  245. phenologyImage.value = resolveImageUrl(item.url) || DEFAULT_PHENOLOGY_IMAGE;
  246. selectedPeriodCode.value = "";
  247. };
  248. /** 暂未到达 → 前一个;已过 → 后一个 */
  249. const movePhenology = (direction) => {
  250. const keys = interactKeys.value;
  251. const idx = keys.indexOf(String(currentInteractKey.value));
  252. if (idx < 0) return false;
  253. const nextIdx = direction === "prev" ? idx - 1 : idx + 1;
  254. if (nextIdx < 0 || nextIdx >= keys.length) {
  255. showWarning(direction === "prev" ? "已是最早物候期" : "已是最晚物候期");
  256. return false;
  257. }
  258. applyPhenologyByKey(keys[nextIdx]);
  259. phenologyAnswer.value = "";
  260. return true;
  261. };
  262. const applyQuestionData = (data) => {
  263. hasDateInteract.value = !!data?.date_interact;
  264. hasOptionsInteract.value = !!data?.options_interact?.interact;
  265. if (hasDateInteract.value) {
  266. applyDateInteract(data.date_interact);
  267. }
  268. if (hasOptionsInteract.value) {
  269. interactMap.value = data.options_interact.interact || {};
  270. const startKey = String(data.options_interact.start_with ?? interactKeys.value[0] ?? "");
  271. applyPhenologyByKey(startKey);
  272. }
  273. // 有时间题优先展示;仅物候题则直接进入问题二
  274. questionType.value = hasDateInteract.value ? "time" : "phenology";
  275. visible.value = hasDateInteract.value || hasOptionsInteract.value;
  276. };
  277. /** 请求接口判断是否展示,并填充问题内容 */
  278. const checkShouldShow = async () => {
  279. const seq = ++requestSeq;
  280. const zoneId = resolveZoneId();
  281. const fetchKey = getFarmFetchKey();
  282. if (!pageActive) return;
  283. if (zoneId == null || zoneId === "") {
  284. visible.value = false;
  285. lastFetchedFarmKey = fetchKey;
  286. return;
  287. }
  288. try {
  289. const res = await VE_API.questionnaire.getInitialInteraction({
  290. zone_id: zoneId,
  291. date: formatToday(),
  292. });
  293. // 已切页或已有更新的请求时,丢弃这次结果,避免弹窗叠加
  294. if (seq !== requestSeq || !pageActive) return;
  295. if (res?.code === 200 && res.data) {
  296. applyQuestionData(res.data);
  297. } else {
  298. visible.value = false;
  299. }
  300. lastFetchedFarmKey = fetchKey;
  301. } catch (e) {
  302. if (seq !== requestSeq || !pageActive) return;
  303. visible.value = false;
  304. }
  305. };
  306. // ---------------------------------------------------------------------------
  307. // 事件处理 / 生命周期
  308. // ---------------------------------------------------------------------------
  309. // 切换农场返回后重新请求初始互动
  310. onActivated(() => {
  311. pageActive = true;
  312. const fetchKey = getFarmFetchKey();
  313. if (fetchKey === lastFetchedFarmKey) return;
  314. visible.value = false;
  315. resetForm();
  316. checkShouldShow();
  317. });
  318. onDeactivated(() => {
  319. pageActive = false;
  320. requestSeq += 1;
  321. visible.value = false;
  322. });
  323. /**
  324. * 暂未到达 / 已过:立刻切到相邻物候期;
  325. * 已到达:选中并记下当前 period_code,供提交使用
  326. */
  327. const handlePhenologySelect = (value) => {
  328. if (value === "not_reached") {
  329. movePhenology("prev");
  330. return;
  331. }
  332. if (value === "passed") {
  333. movePhenology("next");
  334. return;
  335. }
  336. phenologyAnswer.value = "reached";
  337. const current = interactMap.value[currentInteractKey.value];
  338. selectedPeriodCode.value = current?.period_code || "";
  339. };
  340. /**
  341. * 组装保存感知结果载荷
  342. * @param {'time'|'phenology'} type 问题一不含 period_code;问题二不含 interact_code
  343. */
  344. const buildSubmitPayload = (type = "time") => {
  345. const payload = {
  346. zone_id: Number(resolveZoneId()) || resolveZoneId(),
  347. date: toApiDate(selectedDate.value) || formatToday(),
  348. };
  349. if (type === "time") {
  350. payload.interact_code = dateInteractData.value?.interact_code || "";
  351. } else {
  352. payload.period_code = selectedPeriodCode.value || "";
  353. }
  354. return payload;
  355. };
  356. /** 从 axios 错误中取出可读信息 */
  357. const getRequestErrorMessage = (err) => {
  358. const data = err?.response?.data;
  359. if (typeof data === "string" && data) return data;
  360. if (data?.msg) return data.msg;
  361. if (data?.message) return data.message;
  362. if (err?.message) return err.message;
  363. return "提交失败,请稍后再试";
  364. };
  365. /**
  366. * 调用保存感知结果接口
  367. * @param {'time'|'phenology'} type
  368. * @param {{ closeOnSuccess?: boolean }} options closeOnSuccess=false 时成功后不关弹窗(用于继续答问题二)
  369. */
  370. const submitInteractResult = async (type = "time", { closeOnSuccess = true } = {}) => {
  371. if (submitting.value) return false;
  372. submitting.value = true;
  373. try {
  374. const res = await VE_API.questionnaire.saveInteractResult(buildSubmitPayload(type));
  375. if (res?.code === 200) {
  376. if (closeOnSuccess) {
  377. showMessage(res.msg || "提交成功", "success");
  378. visible.value = false;
  379. resetForm();
  380. }
  381. return true;
  382. }
  383. showMessage(res?.msg || "提交失败,请稍后再试", "error");
  384. return false;
  385. } catch (err) {
  386. showMessage(getRequestErrorMessage(err), "error");
  387. return false;
  388. } finally {
  389. submitting.value = false;
  390. }
  391. };
  392. const handleConfirm = async () => {
  393. if (submitting.value) return;
  394. // 问题一:立即确认 → 提交(不含 period_code)
  395. if (questionType.value === "time") {
  396. if (!selectedDate.value) {
  397. showWarning(t("agriFile.selectTime"));
  398. return;
  399. }
  400. const ok = await submitInteractResult("time", {
  401. // 还有问题二则提交成功后继续展示,不关弹窗
  402. closeOnSuccess: !hasOptionsInteract.value,
  403. });
  404. if (ok && hasOptionsInteract.value) {
  405. questionType.value = "phenology";
  406. }
  407. return;
  408. }
  409. // 问题二:需已选择「已到达」并写入 period_code;提交不含 interact_code
  410. if (phenologyAnswer.value !== "reached" || !selectedPeriodCode.value) {
  411. const current = interactMap.value[currentInteractKey.value];
  412. if (phenologyAnswer.value === "reached" && current?.period_code) {
  413. selectedPeriodCode.value = current.period_code;
  414. } else {
  415. showWarning("请确认当前物候期是否已到达");
  416. return;
  417. }
  418. }
  419. await submitInteractResult("phenology");
  420. };
  421. defineExpose({
  422. checkShouldShow,
  423. buildSubmitPayload,
  424. selectedPeriodCode,
  425. });
  426. </script>
  427. <style scoped lang="scss">
  428. .restore-planting-popup {
  429. width: 86%;
  430. padding: 18px 14px 16px;
  431. box-sizing: border-box;
  432. background: linear-gradient(180deg, #d7ecff 0%, #ffffff 28%);
  433. overflow: visible;
  434. &__header {
  435. display: flex;
  436. align-items: flex-start;
  437. justify-content: space-between;
  438. }
  439. &__title {
  440. font-size: 22px;
  441. line-height: 25px;
  442. color: #111;
  443. div {
  444. font-family: "PangMenZhengDao";
  445. }
  446. }
  447. .popup-content {
  448. position: relative;
  449. }
  450. &__decor {
  451. position: absolute;
  452. top: -8px;
  453. right: -4px;
  454. width: 78px;
  455. height: 78px;
  456. object-fit: contain;
  457. pointer-events: none;
  458. }
  459. &__card {
  460. margin-top: 12px;
  461. padding: 10px 12px 12px;
  462. border-radius: 12px;
  463. background: #eaf5ff;
  464. box-sizing: border-box;
  465. position: relative;
  466. z-index: 2;
  467. }
  468. &__question {
  469. font-size: 15px;
  470. line-height: 24px;
  471. color: #252525;
  472. font-weight: 500;
  473. }
  474. &__keyword {
  475. color: #2199f8;
  476. }
  477. &__hint {
  478. margin-top: 4px;
  479. font-size: 12px;
  480. line-height: 16px;
  481. color: #9e9e9e;
  482. }
  483. &__photo {
  484. position: relative;
  485. margin: 12px 0;
  486. border-radius: 8px;
  487. overflow: hidden;
  488. background: #dfeaf5;
  489. img {
  490. display: block;
  491. width: 100%;
  492. height: 148px;
  493. object-fit: cover;
  494. }
  495. &--guide img {
  496. height: 132px;
  497. }
  498. }
  499. &__guide-btn {
  500. position: absolute;
  501. top: 8px;
  502. right: 8px;
  503. height: 28px;
  504. padding: 0 10px;
  505. border-radius: 14px;
  506. background: rgba(0, 0, 0, 0.55);
  507. color: #fff;
  508. font-size: 12px;
  509. display: flex;
  510. align-items: center;
  511. justify-content: center;
  512. }
  513. &__options {
  514. margin-top: 12px;
  515. display: flex;
  516. gap: 8px;
  517. }
  518. &__option {
  519. position: relative;
  520. flex: 1;
  521. height: 36px;
  522. border-radius: 8px;
  523. background: #fff;
  524. border: 1px solid transparent;
  525. display: flex;
  526. align-items: center;
  527. justify-content: center;
  528. font-size: 13px;
  529. color: #333;
  530. box-sizing: border-box;
  531. &.active {
  532. border-color: #2199f8;
  533. color: #2199f8;
  534. }
  535. }
  536. &__option-check {
  537. position: absolute;
  538. top: 0;
  539. right: 0;
  540. width: 16px;
  541. height: 16px;
  542. border-radius: 0 6px 0 6px;
  543. background: #2199f8;
  544. color: #fff;
  545. display: flex;
  546. align-items: center;
  547. justify-content: center;
  548. font-size: 10px;
  549. }
  550. &__date-picker {
  551. width: 100%;
  552. :deep(.el-input__wrapper) {
  553. height: 40px;
  554. border-radius: 8px;
  555. box-shadow: none !important;
  556. background: #fff;
  557. padding: 0 12px;
  558. }
  559. :deep(.el-input__inner) {
  560. font-size: 14px;
  561. color: #333;
  562. }
  563. :deep(.el-input__prefix),
  564. :deep(.el-input__suffix) {
  565. color: rgba(0, 0, 0, 0.35);
  566. }
  567. }
  568. &__actions {
  569. margin-top: 12px;
  570. display: flex;
  571. align-items: center;
  572. justify-content: center;
  573. }
  574. &__btn {
  575. height: 40px;
  576. line-height: 40px;
  577. padding: 0 30px;
  578. border-radius: 20px;
  579. display: flex;
  580. align-items: center;
  581. justify-content: center;
  582. font-size: 16px;
  583. font-weight: 500;
  584. box-sizing: border-box;
  585. &--primary {
  586. // flex: 1;
  587. background: linear-gradient(180deg, #76c3ff 0%, #2199f8 100%);
  588. color: #fff;
  589. &.disabled {
  590. opacity: 0.6;
  591. pointer-events: none;
  592. }
  593. }
  594. }
  595. }
  596. </style>
  597. <!-- 日期面板 / 图片预览 / Message teleport 到 body,需高于弹窗 z-index: 20000 -->
  598. <style lang="scss">
  599. .restore-planting-date-popper {
  600. z-index: 30000 !important;
  601. }
  602. .PhotoSlider__Wrapper {
  603. z-index: 30001 !important;
  604. }
  605. .el-message.restore-planting-message {
  606. z-index: 40000 !important;
  607. }
  608. </style>