ArchivesFarmTimeLine.vue 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693
  1. <template>
  2. <div class="timeline-container" ref="timelineContainerRef">
  3. <div class="timeline-list" ref="timelineListRef">
  4. <empty v-if="isEmpty" image="https://birdseye-img.sysuimars.com/birdseye-look-mini/custom-empty-image.png"
  5. image-size="80" description="暂无数据" class="empty-state" />
  6. <template v-else>
  7. <!-- <div class="timeline-middle-line"></div>
  8. <div v-for="(t, tIdx) in phenologyStartDates" :key="`term-${uniqueTimestamp}-${tIdx}`"
  9. class="timeline-term" :style="getTermStyle(t, tIdx)">
  10. <span class="term-name">{{ formatDate(t.startDate) }}</span>
  11. </div> -->
  12. <div v-for="(p, idx) in phenologyList" :key="`phenology-${uniqueTimestamp}-${idx}`"
  13. class="phenology-bar">
  14. <div class="phenology-title"
  15. :class="{ 'phenology-red': !shouldShowBlue(p), 'phenology-blue': shouldShowBlue(p) }"
  16. v-if="shouldShowPhenologyBarTitle(idx)">
  17. {{ p.phenologyName }}
  18. </div>
  19. <div v-for="(r, rIdx) in Array.isArray(p.reproductiveList) ? p.reproductiveList : []"
  20. :key="`reproductive-${uniqueTimestamp}-${idx}-${rIdx}`" class="reproductive-item">
  21. <div class="arranges" :class="{'arranges-min':!showPhenologyName}">
  22. <div v-for="(fw, aIdx) in Array.isArray(r.farmWorkArrangeList) ? r.farmWorkArrangeList : []"
  23. :key="`arrange-${uniqueTimestamp}-${idx}-${rIdx}-${aIdx}`" class="arrange-card" :class="[
  24. getArrangeStatusClass(fw),
  25. {
  26. 'last-card':
  27. aIdx === r.farmWorkArrangeList.length - 1 &&
  28. rIdx !== r.farmWorkArrangeList.length - 1,
  29. },
  30. // 按单张农事展示日期置灰:晚于今天为 future-card;无日期时回退物候期规则
  31. { 'future-card': shouldGrayFarmWorkCard(fw, p) },
  32. ]" @click="handleRowClick(fw)">
  33. <div class="card-content">
  34. <div class="card-left"
  35. :style="{ width: fw.sourceDataJson && fw.sourceDataJson.resFilename ? 'calc(100% - 45px)' : '100%' }"
  36. v-if="pageType === 'agri_plan'">
  37. <div class="left-info">
  38. <div class="left-date">{{ formatDate(fw.createTime) }}</div>
  39. <div class="text" @click.stop="handleStatusDetail(fw)">
  40. <span class="van-ellipsis">{{ fw.title }}</span>
  41. <!-- <el-icon v-if="shouldShowBlue(p)">
  42. <ArrowRight />
  43. </el-icon> -->
  44. </div>
  45. <!-- <div class="text green van-ellipsis" v-if="fw?.sourceType === 7">
  46. 执行者:{{ fw.sourceDataJson.executorName }}
  47. </div> -->
  48. </div>
  49. <div class="title-text van-ellipsis"
  50. v-if="!shouldGrayFarmWorkCard(fw, p) && fw.sourceType != 4">{{ fw.content }}</div>
  51. </div>
  52. <div class="card-left agri-record-card" v-else>
  53. <div class="left-info">
  54. <div class="left-date">{{ formatDate(fw.recommendDate) }}</div>
  55. <div class="text van-ellipsis" @click.stop="handleStatusDetail(fw)">
  56. <span class="text-name">{{ fw.farmWorkName }}</span>
  57. <el-icon class="text-icon">
  58. <ArrowRight />
  59. </el-icon>
  60. </div>
  61. </div>
  62. <div class="title-wrap van-ellipsis" v-if="fw.flowStatus != null && fw.flowStatus != 0 && fw.flowStatus != -2">
  63. <div class="title-text">{{ flowStatusStr[fw.flowStatus] }}</div>
  64. <div class="title-text blue-tag" v-if="fw?.executionLimitDays >= 0">限时溯源</div>
  65. </div>
  66. </div>
  67. <div class="card-right"
  68. v-if="fw.sourceDataJson && fw.sourceDataJson.resFilename && fw.sourceDataJson.resFilename.length > 0"
  69. @click.stop="handleImageClick(fw)">
  70. <img v-if="fw.sourceType === 7"
  71. :src="base_img_url2 + fw.sourceDataJson?.executeImageUrls?.[0]" alt="" />
  72. <img v-else :src="base_img_url2 + fw.sourceDataJson?.resFilename?.[0]?.filename"
  73. alt="" />
  74. <div class="num" v-if="fw?.sourceDataJson?.imageIds">
  75. {{ fw?.sourceDataJson?.imageIds?.length ||
  76. fw?.sourceDataJson?.executeImageUrls?.length || 0 }}
  77. </div>
  78. </div>
  79. </div>
  80. </div>
  81. </div>
  82. <template v-if="showPhenologyName">
  83. <template v-if="r.name === p.phenologyName">
  84. <div class="phenology-name text-blue"
  85. :class="{ 'phenology-red': !shouldShowBlueLeft(p, r), 'phenology-blue': shouldShowBlueLeft(p, r) }"
  86. :style="r.phenologyName === getNextPhenologyName(idx, rIdx) ? 'padding: 6px 0;' : ''">
  87. {{ r.name }}
  88. </div>
  89. </template>
  90. <template v-else>
  91. <template v-if="p.phenologyName === getNextPhenologyName(idx, rIdx)">
  92. <div class="phenology-name"
  93. :class="{ 'text-red': !shouldShowBlueLeft(p, r), 'text-blue': shouldShowBlueLeft(p, r) }">
  94. {{ r.name }}
  95. </div>
  96. </template>
  97. <template v-else>
  98. <div class="phenology-name"
  99. :class="{ 'text-red': !shouldShowBlueLeft(p, r), 'text-blue': shouldShowBlueLeft(p, r) }">
  100. {{ r.name }}
  101. </div>
  102. <div class="phenology-name mr" :class="{
  103. 'phenology-red': !shouldShowBlueLeft(p, r),
  104. 'phenology-blue': shouldShowBlueLeft(p, r),
  105. }">
  106. {{ p.phenologyName }}
  107. </div>
  108. </template>
  109. </template>
  110. </template>
  111. </div>
  112. </div>
  113. </template>
  114. </div>
  115. </div>
  116. </template>
  117. <script setup>
  118. import { ref, nextTick, watch, onMounted, onUnmounted, onActivated, onDeactivated, computed } from "vue";
  119. import { useRouter, useRoute, onBeforeRouteLeave } from "vue-router";
  120. import { ElMessage } from "element-plus";
  121. import { Empty, showImagePreview } from "vant";
  122. import { base_img_url2 } from "@/api/config";
  123. const router = useRouter();
  124. const route = useRoute();
  125. const props = defineProps({
  126. // 农场 ID,用于请求农事规划数据
  127. farmId: {
  128. type: [String, Number],
  129. default: null,
  130. },
  131. // 年份
  132. year: {
  133. type: [Number, String],
  134. default: new Date().getFullYear(),
  135. },
  136. // 是否是标准农事
  137. isStandard: {
  138. type: Boolean,
  139. default: false,
  140. },
  141. // 方案ID
  142. schemeId: {
  143. type: [Number, String],
  144. default: null,
  145. },
  146. // 类型:agri_record / agri_plan
  147. pageType: {
  148. type: String,
  149. default: "agri_plan",
  150. },
  151. // 区域ID
  152. regionId: {
  153. type: [Number, String],
  154. default: null,
  155. },
  156. // 容器ID
  157. containerId: {
  158. type: [Number, String],
  159. default: null,
  160. },
  161. // 类型ID
  162. typeId: {
  163. type: [Number, String],
  164. default: null,
  165. },
  166. // 问题分区ID
  167. problemZoneId: {
  168. type: [Number, String],
  169. default: null,
  170. },
  171. });
  172. const farmWorkType = {
  173. 0: "预警农事",
  174. 1: "标准农事",
  175. 2: "建议农事",
  176. 3: "自建农事",
  177. };
  178. const emits = defineEmits(["row-click", "card-click"]);
  179. const solarTerms = ref([]);
  180. const phenologyList = ref([]);
  181. // 从物候期列表中提取起始时间,用于时间轴显示
  182. const phenologyStartDates = computed(() => {
  183. if (!phenologyList.value || phenologyList.value.length === 0) {
  184. return [];
  185. }
  186. // 从每个物候期中提取起始时间,并去重排序
  187. const startDatesMap = new Map();
  188. phenologyList.value.forEach((phenology) => {
  189. if (phenology.startDate) {
  190. const dateKey = phenology.startDate;
  191. // 如果该日期还没有添加过,或者需要更新信息
  192. if (!startDatesMap.has(dateKey)) {
  193. startDatesMap.set(dateKey, {
  194. startDate: phenology.startDate,
  195. id: phenology.id || `phenology-${dateKey}`,
  196. });
  197. }
  198. }
  199. });
  200. // 转换为数组并按时间排序
  201. const result = Array.from(startDatesMap.values()).sort((a, b) => {
  202. const timeA = safeParseDate(a.startDate);
  203. const timeB = safeParseDate(b.startDate);
  204. if (isNaN(timeA) || isNaN(timeB)) return 0;
  205. return timeA - timeB;
  206. });
  207. return result;
  208. });
  209. const timelineContainerRef = ref(null);
  210. const timelineListRef = ref(null);
  211. const getTimelineScrollKey = () =>
  212. `timelineScrollTop:${props.pageType}:${props.farmId ?? "none"}:${props.regionId ?? "none"}:${props.containerId ?? "none"}:${route.path}`;
  213. const saveTimelineScrollTop = () => {
  214. if (!timelineContainerRef.value) return;
  215. const scrollTop = timelineContainerRef.value.scrollTop || 0;
  216. sessionStorage.setItem(getTimelineScrollKey(), scrollTop.toString());
  217. };
  218. const restoreTimelineScrollTop = () => {
  219. if (!timelineContainerRef.value) return false;
  220. const savedScrollTop = sessionStorage.getItem(getTimelineScrollKey());
  221. if (savedScrollTop == null) return false;
  222. const scrollTop = Number(savedScrollTop);
  223. if (Number.isNaN(scrollTop)) return false;
  224. const maxScrollTop = Math.max(
  225. 0,
  226. (timelineContainerRef.value.scrollHeight || 0) - (timelineContainerRef.value.clientHeight || 0)
  227. );
  228. timelineContainerRef.value.scrollTop = Math.min(scrollTop, maxScrollTop);
  229. return true;
  230. };
  231. const restoreTimelineScrollTopWithRetry = (retryCount = 4) => {
  232. const restored = restoreTimelineScrollTop();
  233. if (restored || retryCount <= 0) return restored;
  234. setTimeout(() => {
  235. restoreTimelineScrollTopWithRetry(retryCount - 1);
  236. }, 60);
  237. return false;
  238. };
  239. // 标记是否为首次加载
  240. const isInitialLoad = ref(true);
  241. // 存储timeline-list的实际渲染高度
  242. const timelineListHeight = ref(0);
  243. // 生成唯一的时间戳,用于确保key的唯一性
  244. const uniqueTimestamp = ref(Date.now());
  245. // ResizeObserver 实例,用于监听高度变化
  246. let resizeObserver = null;
  247. // 标记是否为空数据
  248. const isEmpty = ref(false);
  249. // 标记是否正在请求数据,防止重复请求
  250. const isRequesting = ref(false);
  251. // 记录上一次请求的 regionId + problemZoneId,避免相同参数重复请求
  252. const lastRequestedFarmId = ref(null);
  253. const farmWorkPlanScopeKey = () =>
  254. JSON.stringify([props.regionId ?? null, props.problemZoneId ?? null]);
  255. // 获取当前季节
  256. const getCurrentSeason = () => {
  257. const month = new Date().getMonth() + 1; // 1-12
  258. if (month >= 1 && month <= 5) {
  259. return "spring"; // 春季:3-5月
  260. } else if (month >= 6 && month <= 8) {
  261. return "summer"; // 夏季:6-8月
  262. } else if (month >= 9 && month <= 10) {
  263. return "autumn"; // 秋季:9-10月
  264. } else {
  265. return "winter"; // 冬季:11-2月
  266. }
  267. };
  268. // 安全解析时间到时间戳(ms)
  269. /** 解析 sourceData JSON,避免大整数(如雪花 ID)被 JSON.parse 精度丢失(>2^53 会变成 500 结尾等) */
  270. const parseSourceDataSafe = (str) => {
  271. if (!str) return null;
  272. try {
  273. const fixed = str.replace(/"imageIds"\s*:\s*\[([^\]]*)\]/g, (_, arr) => {
  274. const quoted = arr.split(",").map((s) => {
  275. const t = s.trim().replace(/^["']|["']$/g, "");
  276. return /^\d+$/.test(t) ? `"${t}"` : s.trim();
  277. }).join(",");
  278. return `"imageIds":[${quoted}]`;
  279. });
  280. return JSON.parse(fixed);
  281. } catch {
  282. return null;
  283. }
  284. };
  285. const safeParseDate = (val) => {
  286. if (!val) return NaN;
  287. if (val instanceof Date) return val.getTime();
  288. if (typeof val === "number") return val;
  289. if (typeof val === "string") {
  290. // 兼容 "YYYY-MM-DD HH:mm:ss" -> Safari
  291. const s = val.replace(/-/g, "/").replace("T", " ");
  292. const d = new Date(s);
  293. return isNaN(d.getTime()) ? NaN : d.getTime();
  294. }
  295. return NaN;
  296. };
  297. const batchValidateData = ref({});
  298. const allTrue = ref(false);
  299. const invalidIds = ref([]);
  300. const invalidArr = ref([]);
  301. // 验证农事卡片药肥报价信息是否完整
  302. const batchValidatePesticideFertilizerQuotes = (ids, items) => {
  303. if (props.isStandard) {
  304. return;
  305. }
  306. VE_API.monitor
  307. .batchValidatePesticideFertilizerQuotes({ ids, schemeId: props.schemeId })
  308. .then(({ data, code }) => {
  309. if (code === 0) {
  310. batchValidateData.value = data || {};
  311. allTrue.value = Object.values(data).every((value) => value === true);
  312. invalidIds.value = Object.keys(data).filter((key) => data[key] !== true);
  313. // 清空之前的arrangeIds
  314. invalidArr.value = [];
  315. // 遍历items,判断farmWorkId是否在invalidIds中,如果对应上了就把item.id push进去
  316. items.forEach((item) => {
  317. // 判断item.farmWorkId是否在invalidIds数组中(需要转换为字符串进行比较)
  318. const farmWorkIdStr = String(item.farmWorkId);
  319. if (invalidIds.value.includes(farmWorkIdStr)) {
  320. invalidArr.value.push({
  321. arrangeId: item.id,
  322. farmWorkId: item.farmWorkId,
  323. });
  324. }
  325. });
  326. }
  327. })
  328. .catch(() => { });
  329. };
  330. // 获取图片 URL 列表
  331. const fetchImageUrls = async (params) => {
  332. try {
  333. const res = await VE_API.ali.getTreeImageList(params);
  334. if (res.code === 0 && Array.isArray(res.data)) {
  335. return res.data.map((item) => {
  336. if (item.filename) {
  337. return {
  338. ...item,
  339. cloudFilename: item.filename, // 兼容组件
  340. };
  341. }
  342. return null;
  343. }).filter(item => item !== null);
  344. }
  345. return [];
  346. } catch (error) {
  347. console.error("获取图片列表失败:", error);
  348. return [];
  349. }
  350. };
  351. // 与 albumCarouselItem.getPhotoSrc 一致:拼 CDN 前缀;无水印预览用 Vant ImagePreview
  352. const resolveFarmWorkImagePath = (photo) => {
  353. if (photo == null) return "";
  354. if (typeof photo === "string") return photo;
  355. return photo.cloudFilename || photo.filename || "";
  356. };
  357. const buildFarmWorkPreviewUrls = (fw) => {
  358. const sd = fw?.sourceDataJson;
  359. if (!sd) return [];
  360. const toFullUrl = (path) => {
  361. if (!path) return "";
  362. if (/^https?:\/\//i.test(path)) return path;
  363. return base_img_url2 + path;
  364. };
  365. if (fw.sourceType === 7) {
  366. const arr = sd.executeImageUrls || [];
  367. return arr.map((p) => toFullUrl(resolveFarmWorkImagePath(p))).filter(Boolean);
  368. }
  369. const arr = sd.resFilename || [];
  370. return arr.map((p) => toFullUrl(resolveFarmWorkImagePath(p))).filter(Boolean);
  371. };
  372. const handleImageClick = (fw) => {
  373. const images = buildFarmWorkPreviewUrls(fw);
  374. if (!images.length) return;
  375. showImagePreview({
  376. images,
  377. startPosition: 0,
  378. closeable: true,
  379. showIndex: true,
  380. });
  381. };
  382. // 顶部物候标题:相邻两段 phenologyName 相同时只显示一次(保留第一段)
  383. const shouldShowPhenologyBarTitle = (idx) => {
  384. const list = phenologyList.value;
  385. if (!list?.length || idx < 0 || idx >= list.length) return false;
  386. if (idx === 0) return true;
  387. return list[idx]?.phenologyName !== list[idx - 1]?.phenologyName;
  388. };
  389. // 获取下一个reproductive-item的phenologyName
  390. const getNextPhenologyName = (currentPhenologyIdx, currentReproductiveIdx) => {
  391. const currentPhenology = phenologyList.value[currentPhenologyIdx];
  392. if (!currentPhenology || !Array.isArray(currentPhenology.reproductiveList)) {
  393. return null;
  394. }
  395. // 如果当前reproductive-item不是最后一个,获取同一个物候期的下一个
  396. if (currentReproductiveIdx < currentPhenology.reproductiveList.length - 1) {
  397. const nextReproductive = currentPhenology.reproductiveList[currentReproductiveIdx + 1];
  398. return nextReproductive?.phenologyName || null;
  399. }
  400. // 如果当前reproductive-item是最后一个,获取下一个物候期的第一个reproductive-item
  401. if (currentPhenologyIdx < phenologyList.value.length - 1) {
  402. const nextPhenology = phenologyList.value[currentPhenologyIdx + 1];
  403. if (
  404. nextPhenology &&
  405. Array.isArray(nextPhenology.reproductiveList) &&
  406. nextPhenology.reproductiveList.length > 0
  407. ) {
  408. const firstReproductive = nextPhenology.reproductiveList[0];
  409. return firstReproductive?.phenologyName || null;
  410. }
  411. }
  412. return null;
  413. };
  414. // 计算物候期需要的实际高度(基于农事数量)
  415. const getPhenologyRequiredHeight = (item) => {
  416. // 统计该物候期内的农事数量
  417. let farmWorkCount = 0;
  418. if (Array.isArray(item.reproductiveList)) {
  419. item.reproductiveList.forEach((reproductive) => {
  420. if (Array.isArray(reproductive.farmWorkArrangeList)) {
  421. farmWorkCount += reproductive.farmWorkArrangeList.length;
  422. }
  423. });
  424. }
  425. // 如果没有农事,给一个最小高度
  426. if (farmWorkCount === 0) {
  427. return 50; // 最小50px
  428. }
  429. // 每个农事卡片的高度(根据实际内容,卡片高度可能因内容而异)
  430. // 卡片包含:padding(8px*2) + header(约25px) + content margin(4px+2px) + content(约25-30px) = 约72-77px
  431. // 考虑到内容可能换行,实际高度可能更高,设置为120px更安全,避免卡片重叠
  432. const farmWorkCardHeight = 120; // 卡片高度估算,确保能容纳内容且不重叠
  433. // 卡片之间的间距(与CSS中的gap保持一致)
  434. const cardGap = 12;
  435. // 计算总高度:卡片数量 * 卡片高度 + (卡片数量 - 1) * 间距
  436. // 如果有多个卡片,需要加上它们之间的间距
  437. const totalHeight = farmWorkCount * farmWorkCardHeight + (farmWorkCount > 1 ? (farmWorkCount - 1) * cardGap : 0);
  438. // 返回精确的总高度,只保留最小高度限制,不添加额外余量
  439. return Math.max(totalHeight, 50); // 最小50px,精确匹配农事卡片高度
  440. };
  441. // 计算所有物候期的累积位置和总高度
  442. const calculatePhenologyPositions = () => {
  443. let currentTop = 10; // 起始位置,留出顶部间距
  444. const positions = new Map();
  445. // 按progress排序物候期,确保按时间顺序排列
  446. const sortedPhenologyList = [...phenologyList.value].sort((a, b) => {
  447. const aProgress = Math.min(Number(a?.progress) || 0, Number(a?.progress2) || 0);
  448. const bProgress = Math.min(Number(b?.progress) || 0, Number(b?.progress2) || 0);
  449. return aProgress - bProgress;
  450. });
  451. sortedPhenologyList.forEach((phenology) => {
  452. const height = getPhenologyRequiredHeight(phenology);
  453. // 使用与数据生成时相同的ID生成逻辑
  454. const itemId =
  455. phenology.id ?? phenology.phenologyId ?? phenology.name ?? `${phenology.progress}-${phenology.progress2}`;
  456. positions.set(itemId, {
  457. top: currentTop,
  458. height: height,
  459. });
  460. currentTop += height; // 紧挨着下一个物候期,不留间距
  461. });
  462. return {
  463. positions,
  464. totalHeight: currentTop, // 总高度 = 最后一个物候期的底部位置,不添加额外间距
  465. };
  466. };
  467. // 计算所有农事的总高度(基于物候期紧挨排列)
  468. const calculateTotalHeightByFarmWorks = () => {
  469. const { totalHeight } = calculatePhenologyPositions();
  470. // 如果有物候期数据,直接使用计算出的总高度
  471. // totalHeight 已经包含了从 10 开始的起始位置和所有物候期的高度
  472. if (totalHeight > 10) {
  473. // 确保总高度至少能容纳所有物候期起始时间(每个至少50px)
  474. const baseHeight = (phenologyStartDates.value?.length || 0) * 50;
  475. // 返回物候期总高度和基础高度的较大值,确保物候期起始时间能正常显示
  476. return Math.max(totalHeight, baseHeight);
  477. }
  478. // 如果没有物候期数据,返回基础高度
  479. const baseHeight = (phenologyStartDates.value?.length || 0) * 50;
  480. return baseHeight || 100; // 至少返回100px,避免为0
  481. };
  482. const getTermStyle = (t, index) => {
  483. // 优先使用实际测量的timeline-list高度,如果没有测量到则使用计算值作为后备
  484. const totalHeight = timelineListHeight.value > 0 ? timelineListHeight.value : calculateTotalHeightByFarmWorks();
  485. // 获取物候期起始时间总数(使用新数组)
  486. const termCount = phenologyStartDates.value?.length || 1;
  487. // 等分高度:总高度 / 物候期起始时间数量
  488. const termHeight = totalHeight / termCount;
  489. // 计算top位置:索引 * 每个物候期起始时间的高度
  490. const top = index * termHeight;
  491. return {
  492. position: "absolute",
  493. top: `${top}px`,
  494. left: 0,
  495. width: "35px",
  496. height: `${termHeight}px`, // 高度等分,使用实际测量的高度
  497. display: "flex",
  498. alignItems: "center",
  499. };
  500. };
  501. // 点击季节 → 滚动到对应节气(立春/立夏/立秋/立冬)
  502. const handleSeasonClick = (seasonValue) => {
  503. const mapping = {
  504. spring: "立春",
  505. summer: "立夏",
  506. autumn: "立秋",
  507. winter: "立冬",
  508. };
  509. const targetName = mapping[seasonValue];
  510. if (!targetName) return;
  511. // 查找对应的节气
  512. const targetIndex = solarTerms.value.findIndex((t) => (t?.displayName || "") === targetName);
  513. if (targetIndex === -1) return;
  514. // 计算目标节气的top位置
  515. const totalHeight = timelineListHeight.value > 0 ? timelineListHeight.value : calculateTotalHeightByFarmWorks();
  516. const termCount = solarTerms.value?.length || 1;
  517. const termHeight = totalHeight / termCount;
  518. const targetTop = targetIndex * termHeight;
  519. // 滚动到目标位置
  520. const wrap = timelineContainerRef.value;
  521. if (!wrap) return;
  522. const viewH = wrap.clientHeight || 0;
  523. const maxScroll = Math.max(0, wrap.scrollHeight - viewH);
  524. // 将目标位置稍微靠上(使用 0.1 视口高度做偏移)
  525. let scrollTop = Math.max(0, targetTop - viewH * 0.1);
  526. if (scrollTop > maxScroll) scrollTop = maxScroll;
  527. wrap.scrollTo({ top: scrollTop, behavior: "smooth" });
  528. };
  529. // 农事状态样式映射
  530. const getArrangeStatusClass = (fw) => {
  531. const t = props.pageType === 'agri_record' ? fw?.flowStatus : fw?.sourceType;
  532. if (props.pageType === 'agri_record') {
  533. if (t == null || t == 0 || t == -2) return "status-default";
  534. // 农事记录:内容仍用 status-warning 的红字/红标签,外边框与箭头改为灰色
  535. if (t == -1) return "status-warning status-warning-agri-record";
  536. if (t == 3) return "status-warning-bg";
  537. if (t == 5) return "status-normal";
  538. return "status-act";
  539. } else {
  540. if (t == 10) return "status-complete";
  541. if (t == 11) return "status-warning";
  542. return "status-normal";
  543. }
  544. };
  545. const handleRowClick = (item) => {
  546. // 跳转前记录当前滚动位置
  547. saveTimelineScrollTop();
  548. emits("row-click", item);
  549. };
  550. // 获取农事规划数据
  551. const getFarmWorkPlan = () => {
  552. phenologyList.value = [];
  553. if (!props.farmId) return;
  554. const scopeKey = farmWorkPlanScopeKey();
  555. if (isRequesting.value || lastRequestedFarmId.value === scopeKey) return;
  556. isRequesting.value = true;
  557. lastRequestedFarmId.value = scopeKey;
  558. // 更新时间戳,确保key变化,触发DOM重新渲染
  559. uniqueTimestamp.value = Date.now();
  560. // 重置测量高度,等待重新测量
  561. timelineListHeight.value = 0;
  562. // 重置空数据状态
  563. isEmpty.value = false;
  564. let savedScrollTop = 0;
  565. if (!isInitialLoad.value && timelineContainerRef.value) {
  566. savedScrollTop = timelineContainerRef.value.scrollTop || 0;
  567. }
  568. const apiFunc = props.pageType === 'agri_record' ? VE_API.monitor.getFarmWorkPlan : VE_API.monitor.getArchivesList;
  569. const params = {
  570. farmId: props.farmId,
  571. regionId: props.regionId,
  572. problemZoneId: props.problemZoneId,
  573. year: props.year,
  574. }
  575. if (props.pageType === 'agri_record') {
  576. params.containerId = props.containerId;
  577. }
  578. apiFunc(params)
  579. .then(async ({ data, code }) => {
  580. if (code === 0) {
  581. const list = Array.isArray(data?.solarTermsList) ? data.solarTermsList : [];
  582. const filtered = list
  583. .filter((t) => t && t.type === 1)
  584. .map((t) => ({
  585. id:
  586. t.id ??
  587. t.solarTermsId ??
  588. t.termId ??
  589. `${t.name || t.solarTermsName || t.termName || "term"}-${t.createDate || ""}`,
  590. displayName: t.name || t.solarTermsName || t.termName || "节气",
  591. createDate: t.createDate || null,
  592. progress: Number(t.progress) || 0,
  593. }));
  594. solarTerms.value = filtered;
  595. // 物候期数据
  596. const processedPhenologyList = Array.isArray(data?.phenologyList)
  597. ? await Promise.all(
  598. data.phenologyList.map(async (it) => {
  599. const reproductiveList = Array.isArray(it.reproductiveList)
  600. ? await Promise.all(
  601. it.reproductiveList.map(async (r) => {
  602. const farmWorkArrangeList = Array.isArray(r.broadcastList || r.interactionFarmWorkList)
  603. ? await Promise.all(
  604. (r.broadcastList || r.interactionFarmWorkList).map(async (fw) => {
  605. const sourceDataJson = parseSourceDataSafe(fw.sourceData);
  606. // 如果有 imageIds,获取图片 URL
  607. if (
  608. sourceDataJson &&
  609. sourceDataJson.imageIds &&
  610. Array.isArray(sourceDataJson.imageIds) &&
  611. sourceDataJson.imageIds.length > 0
  612. ) {
  613. const resFilenameList = await fetchImageUrls(
  614. {
  615. imageIds: sourceDataJson.imageIds,
  616. page: 1,
  617. limit: 100,
  618. }
  619. );
  620. sourceDataJson.resFilename = resFilenameList;
  621. // 调用 findSuitabilityByPoint 接口获取天气适宜性信息
  622. if (fw.farmId && fw.createTime) {
  623. try {
  624. const dateStr = formatDateForAPI(fw.createTime);
  625. if (dateStr) {
  626. const suitabilityRes = await VE_API.ali.findSuitabilityByPoint({
  627. farmId: fw.farmId,
  628. date: dateStr,
  629. });
  630. if (suitabilityRes && suitabilityRes.code === 0 && suitabilityRes.data) {
  631. // 将返回的数据合并到 sourceDataJson
  632. sourceDataJson.suitability = suitabilityRes.data;
  633. }
  634. }
  635. } catch (error) {
  636. console.error("获取天气适宜性信息失败:", error);
  637. }
  638. }
  639. }
  640. return {
  641. ...fw,
  642. phenologyName: r.phenologyName,
  643. sourceDataJson,
  644. containerSpaceTimeId: it.containerSpaceTimeId,
  645. };
  646. })
  647. )
  648. : [];
  649. return {
  650. ...r,
  651. farmWorkArrangeList,
  652. };
  653. })
  654. )
  655. : [];
  656. return {
  657. id: it.id ?? it.phenologyId ?? it.name ?? `${it.progress}-${it.progress2}`,
  658. progress: Number(it.progress) || 0, // 起点 %
  659. progress2: Number(it.progress2) || 0, // 终点 %
  660. phenologyName: it.phenologyName,
  661. startDate: it.startDate,
  662. startTimeMs: safeParseDate(
  663. it.startDate || it.beginDate || it.startTime || it.start || it.start_at
  664. ),
  665. reproductiveList,
  666. };
  667. })
  668. )
  669. : [];
  670. phenologyList.value = processedPhenologyList;
  671. // 使用多次 nextTick 和 requestAnimationFrame 确保DOM完全渲染
  672. nextTick(() => {
  673. requestAnimationFrame(() => {
  674. nextTick(() => {
  675. requestAnimationFrame(() => {
  676. // 测量timeline-list的实际渲染高度
  677. if (timelineListRef.value) {
  678. const height =
  679. timelineListRef.value.offsetHeight || timelineListRef.value.clientHeight;
  680. if (height > 0) {
  681. timelineListHeight.value = height;
  682. }
  683. }
  684. const hasRestoredScrollTop = restoreTimelineScrollTopWithRetry();
  685. if (isInitialLoad.value) {
  686. if (hasRestoredScrollTop) {
  687. isInitialLoad.value = false;
  688. } else {
  689. // 如果测量失败,延迟一下再尝试滚动
  690. setTimeout(() => {
  691. if (timelineListRef.value) {
  692. const height =
  693. timelineListRef.value.offsetHeight ||
  694. timelineListRef.value.clientHeight;
  695. if (height > 0) {
  696. timelineListHeight.value = height;
  697. }
  698. }
  699. if (!restoreTimelineScrollTopWithRetry()) {
  700. const currentSeason = getCurrentSeason();
  701. handleSeasonClick(currentSeason);
  702. }
  703. isInitialLoad.value = false;
  704. }, 200);
  705. }
  706. } else {
  707. if (!hasRestoredScrollTop && timelineContainerRef.value && savedScrollTop > 0) {
  708. timelineContainerRef.value.scrollTop = savedScrollTop;
  709. }
  710. }
  711. });
  712. });
  713. });
  714. });
  715. // 收集所有farmWorkId
  716. const farmWorkIds = [];
  717. const farmWorks = [];
  718. phenologyList.value.forEach((phenology) => {
  719. if (Array.isArray(phenology.reproductiveList)) {
  720. phenology.reproductiveList.forEach((reproductive) => {
  721. if (Array.isArray(reproductive.farmWorkArrangeList)) {
  722. reproductive.farmWorkArrangeList.forEach((farmWork) => {
  723. if (farmWork.farmWorkId && farmWork.isFollow !== 0) {
  724. farmWorkIds.push(farmWork.farmWorkId);
  725. farmWorks.push(farmWork);
  726. }
  727. });
  728. }
  729. });
  730. }
  731. });
  732. // 调用验证方法,传入所有ids
  733. if (farmWorkIds.length > 0) {
  734. batchValidatePesticideFertilizerQuotes(farmWorkIds, farmWorks);
  735. }
  736. // 判断是否为空数据:没有节气或没有物候期数据
  737. if (solarTerms.value.length === 0 && phenologyList.value.length === 0) {
  738. isEmpty.value = true;
  739. } else {
  740. isEmpty.value = false;
  741. }
  742. } else {
  743. // 接口返回错误码,显示暂无数据
  744. isEmpty.value = true;
  745. solarTerms.value = [];
  746. phenologyList.value = [];
  747. }
  748. })
  749. .catch((error) => {
  750. console.error("获取农事规划数据失败:", error);
  751. ElMessage.error("获取农事规划数据失败");
  752. // 接口报错,显示暂无数据
  753. isEmpty.value = true;
  754. solarTerms.value = [];
  755. phenologyList.value = [];
  756. })
  757. .finally(() => {
  758. // 请求完成,重置请求标志
  759. isRequesting.value = false;
  760. });
  761. };
  762. const updateFarmWorkPlan = () => {
  763. solarTerms.value = [];
  764. phenologyList.value = [];
  765. isEmpty.value = false;
  766. getFarmWorkPlan();
  767. };
  768. watch(
  769. () => props.regionId,
  770. (val, oldVal) => {
  771. // 如果 farmId 没有值,则不触发
  772. if (!val) return;
  773. // 如果 farmId 变化了,重置上次请求的 farmId,允许请求新数据
  774. if (val !== oldVal) {
  775. lastRequestedFarmId.value = null;
  776. }
  777. // getFarmWorkPlan 内部已经有防重复请求的检查,这里直接调用即可
  778. isInitialLoad.value = true;
  779. updateFarmWorkPlan();
  780. },
  781. { immediate: true }
  782. );
  783. watch(
  784. () => props.year,
  785. (val, oldVal) => {
  786. if (!props.farmId) return;
  787. if (val !== oldVal) {
  788. lastRequestedFarmId.value = null;
  789. }
  790. isInitialLoad.value = true;
  791. updateFarmWorkPlan();
  792. },
  793. );
  794. const showPhenologyName = computed(() => {
  795. return !props.problemZoneId;
  796. });
  797. watch(
  798. () => props.problemZoneId,
  799. (val, oldVal) => {
  800. if (!props.farmId) return;
  801. if (val !== oldVal) {
  802. lastRequestedFarmId.value = null;
  803. }
  804. isInitialLoad.value = true;
  805. updateFarmWorkPlan();
  806. },
  807. );
  808. const handleStatusDetail = (fw) => {
  809. // 跳转前记录当前滚动位置
  810. saveTimelineScrollTop();
  811. emits('card-click');
  812. if (props.pageType === 'agri_plan') {
  813. if (fw?.sourceData && fw?.id) {
  814. router.push({
  815. path: "/agricultural_detail",
  816. query: {
  817. id: fw?.id,
  818. content: fw?.content
  819. },
  820. });
  821. }
  822. } else {
  823. router.push({
  824. path: "/work_detail",
  825. query: {
  826. miniJson: JSON.stringify({
  827. paramsPage: JSON.stringify({
  828. farmId: props.farmId,
  829. farmWorkLibId: fw?.farmWorkLibId,
  830. recordId: fw?.farmWorkRecordId,
  831. typeId: props.typeId
  832. }),
  833. }),
  834. },
  835. });
  836. }
  837. };
  838. // 格式化日期为 MM-DD 格式
  839. const formatDate = (dateStr) => {
  840. if (!dateStr) return "--";
  841. const date = new Date(dateStr);
  842. if (Number.isNaN(date.getTime())) return dateStr;
  843. const m = `${date.getMonth() + 1}`.padStart(2, "0");
  844. const d = `${date.getDate()}`.padStart(2, "0");
  845. return `${m}-${d}`;
  846. };
  847. // 格式化日期为 YYYY-MM-DD 格式(用于接口调用)
  848. const formatDateForAPI = (dateStr) => {
  849. if (!dateStr) return null;
  850. const date = new Date(dateStr);
  851. if (Number.isNaN(date.getTime())) return null;
  852. const y = date.getFullYear();
  853. const m = `${date.getMonth() + 1}`.padStart(2, "0");
  854. const d = `${date.getDate()}`.padStart(2, "0");
  855. return `${y}-${m}-${d}`;
  856. };
  857. // 获取下一个即将到来的节气(当前节气)的 progress
  858. const getNextTermProgress = () => {
  859. if (!solarTerms.value || solarTerms.value.length === 0) return Infinity;
  860. const now = new Date();
  861. now.setHours(0, 0, 0, 0);
  862. let nextTermProgress = Infinity;
  863. // 找到当前日期之后的下一个节气(当前节气)
  864. solarTerms.value.forEach((term) => {
  865. const termDate = safeParseDate(term.createDate);
  866. if (!isNaN(termDate)) {
  867. const termDateObj = new Date(termDate);
  868. termDateObj.setHours(0, 0, 0, 0);
  869. // 找到大于等于当前日期的第一个节气
  870. if (termDateObj >= now) {
  871. const termProgress = Number(term.progress) || 0;
  872. if (termProgress < nextTermProgress) {
  873. nextTermProgress = termProgress;
  874. }
  875. }
  876. }
  877. });
  878. // 如果没有找到未来的节气,说明所有节气都已过,返回 Infinity(所有物候期都显示蓝色)
  879. return nextTermProgress === Infinity ? Infinity : nextTermProgress;
  880. };
  881. // 根据物候期的 progress 判断它所属节气的 progress
  882. const getPhenologyTermProgress = (phenologyProgress) => {
  883. if (!solarTerms.value || solarTerms.value.length === 0) return -1;
  884. const progress = Number(phenologyProgress) || 0;
  885. // 找到物候期所属的节气(progress 最接近且小于等于的节气)
  886. let matchedTermProgress = -1;
  887. solarTerms.value.forEach((term) => {
  888. const termProgress = Number(term.progress) || 0;
  889. if (progress >= termProgress && termProgress > matchedTermProgress) {
  890. matchedTermProgress = termProgress;
  891. }
  892. });
  893. // 如果物候期的 progress 小于所有节气,返回第一个节气的 progress
  894. if (matchedTermProgress === -1 && solarTerms.value.length > 0) {
  895. const firstTermProgress = Number(solarTerms.value[0].progress) || 0;
  896. return firstTermProgress;
  897. }
  898. return matchedTermProgress;
  899. };
  900. const flowStatusStr = {
  901. '3': '待认证',
  902. '-1': '已过期',
  903. '-2': '已过期',
  904. '5': '已认证',
  905. }
  906. // 右侧农事卡片展示用日期(与模板 left-date 一致:规划 createTime、记录 recommendDate)
  907. const getFarmWorkTimelineDateMs = (fw) => {
  908. const primary = props.pageType === "agri_plan" ? fw?.createTime : fw?.recommendDate ?? fw?.createTime;
  909. let ms = safeParseDate(primary);
  910. if (Number.isNaN(ms) || ms <= 0) {
  911. ms = safeParseDate(props.pageType === "agri_plan" ? fw?.recommendDate : fw?.createTime);
  912. }
  913. return ms;
  914. };
  915. const isFarmWorkDateOnOrBeforeToday = (ms) => {
  916. if (Number.isNaN(ms) || ms <= 0) return false;
  917. const today = new Date();
  918. today.setHours(0, 0, 0, 0);
  919. const d = new Date(ms);
  920. d.setHours(0, 0, 0, 0);
  921. return d.getTime() <= today.getTime();
  922. };
  923. // 单张卡片:有有效展示日期且晚于今天 → 未来农事,右侧应置灰(与 left-date 同一套字段)
  924. const isFarmWorkTimelineStrictlyFuture = (fw) => {
  925. const ms = getFarmWorkTimelineDateMs(fw);
  926. if (Number.isNaN(ms) || ms <= 0) return false;
  927. return !isFarmWorkDateOnOrBeforeToday(ms);
  928. };
  929. // 右侧 arrange-card:未来日期置灰;解析不到日期时回退物候期节气/待认证规则(与旧版整段逻辑一致)
  930. // 无农事展示日期时的置灰回退:仅用节气/物候期 + 待认证(不含「任一行农事≤今天」),避免右侧卡片被外层标题连带误判
  931. const isPhenologyActiveWithoutFarmWorkDates = (phenology) =>
  932. agriRecordHasPendingAuthInPhenology(phenology) || shouldShowBlueBase(phenology);
  933. const shouldGrayFarmWorkCard = (fw, phenology) => {
  934. if (isFarmWorkTimelineStrictlyFuture(fw)) return true;
  935. const ms = getFarmWorkTimelineDateMs(fw);
  936. if (!Number.isNaN(ms) && ms > 0) {
  937. return false;
  938. }
  939. return !isPhenologyActiveWithoutFarmWorkDates(phenology);
  940. };
  941. // 某一生育期行下是否存在「农事时间 ≤ 今天」的卡片(与右侧 left-date 字段一致)
  942. const reproductiveHasFarmWorkOnOrBeforeToday = (reproductive) => {
  943. const fws = Array.isArray(reproductive?.farmWorkArrangeList) ? reproductive.farmWorkArrangeList : [];
  944. for (const fw of fws) {
  945. if (isFarmWorkDateOnOrBeforeToday(getFarmWorkTimelineDateMs(fw))) {
  946. return true;
  947. }
  948. }
  949. return false;
  950. };
  951. // 物候期内是否至少有一行生育期因「农事≤今天」而高亮(用于最外层物候期标题与内层对齐)
  952. const phenologyHasFarmWorkOnOrBeforeToday = (phenology) => {
  953. const reproductives = Array.isArray(phenology?.reproductiveList) ? phenology.reproductiveList : [];
  954. return reproductives.some((r) => reproductiveHasFarmWorkOnOrBeforeToday(r));
  955. };
  956. // 该生育期下:存在农事且「凡有有效展示日期的卡片」全部严格晚于今天 → 左侧本行不因节气规则变蓝(与右侧 future-card 一致)
  957. const reproductiveAllDatedFarmWorksStrictlyFuture = (reproductive) => {
  958. const fws = Array.isArray(reproductive?.farmWorkArrangeList) ? reproductive.farmWorkArrangeList : [];
  959. if (fws.length === 0) return false;
  960. const dated = fws.filter((fw) => {
  961. const ms = getFarmWorkTimelineDateMs(fw);
  962. return !Number.isNaN(ms) && ms > 0;
  963. });
  964. if (dated.length === 0) return false;
  965. return dated.every((fw) => isFarmWorkTimelineStrictlyFuture(fw));
  966. };
  967. // 物候期内:至少有一条农事带有效日期,且全部带有效日期的农事均为「严格未来」(无一 ≤ 今天)→ 最外层标题不因节气单独变蓝
  968. const phenologyAllDatedFarmWorksStrictlyFuture = (phenology) => {
  969. const reproductives = Array.isArray(phenology?.reproductiveList) ? phenology.reproductiveList : [];
  970. let anyDated = false;
  971. for (const r of reproductives) {
  972. const fws = Array.isArray(r?.farmWorkArrangeList) ? r.farmWorkArrangeList : [];
  973. for (const fw of fws) {
  974. const ms = getFarmWorkTimelineDateMs(fw);
  975. if (Number.isNaN(ms) || ms <= 0) continue;
  976. anyDated = true;
  977. if (isFarmWorkDateOnOrBeforeToday(ms)) return false;
  978. }
  979. }
  980. return anyDated;
  981. };
  982. // 仅农事记录页(agri_record):该物候期内存在待认证农事时,左侧最外层物候期与各生育期/物候期文案均高亮为蓝;农事规划(agri_plan)不生效
  983. const agriRecordHasPendingAuthInPhenology = (phenology) => {
  984. if (props.pageType !== "agri_record") return false;
  985. return (Array.isArray(phenology?.reproductiveList) ? phenology.reproductiveList : []).some((reproductive) =>
  986. (Array.isArray(reproductive?.farmWorkArrangeList) ? reproductive.farmWorkArrangeList : []).some((fw) => {
  987. const s = fw?.flowStatus;
  988. return s === 3 || s === "3";
  989. })
  990. );
  991. };
  992. // 单行生育期下是否有待认证农事(仅农事记录页)
  993. const reproductiveHasPendingAuthFarmWork = (reproductive) => {
  994. if (props.pageType !== "agri_record") return false;
  995. return (Array.isArray(reproductive?.farmWorkArrangeList) ? reproductive.farmWorkArrangeList : []).some((fw) => {
  996. const s = fw?.flowStatus;
  997. return s === 3 || s === "3";
  998. });
  999. };
  1000. // 物候期底色/节气规则(不含「农事卡片日期」「待认证」扩展)
  1001. const shouldShowBlueBase = (phenology) => {
  1002. // 优先使用物候期真实日期判断:未来日期不应显示蓝色
  1003. const phenologyTimeMs =
  1004. Number(phenology?.startTimeMs) ||
  1005. safeParseDate(phenology?.startDate || phenology?.beginDate || phenology?.startTime || phenology?.start || phenology?.start_at);
  1006. if (!Number.isNaN(phenologyTimeMs) && phenologyTimeMs > 0) {
  1007. const today = new Date();
  1008. today.setHours(0, 0, 0, 0);
  1009. return phenologyTimeMs <= today.getTime();
  1010. }
  1011. // 日期缺失时,回退到 progress 规则(兼容老数据)
  1012. // 获取下一个即将到来的节气(当前节气)的 progress
  1013. const nextTermProgress = getNextTermProgress();
  1014. // 如果所有节气都已过(nextTermProgress === Infinity),所有物候期都显示蓝色
  1015. if (nextTermProgress === Infinity) {
  1016. return true;
  1017. }
  1018. // 根据物候期的 progress 判断它属于哪个节气
  1019. const phenologyProgress = Math.min(Number(phenology?.progress) || 0, Number(phenology?.progress2) || 0);
  1020. const phenologyTermProgress = getPhenologyTermProgress(phenologyProgress);
  1021. // 找到下一个节气的完整信息,用于判断物候期是否属于当前节气
  1022. let nextTerm = null;
  1023. solarTerms.value.forEach((term) => {
  1024. const termProgress = Number(term.progress) || 0;
  1025. if (termProgress === nextTermProgress) {
  1026. nextTerm = term;
  1027. }
  1028. });
  1029. // 如果物候期所属的节气的 progress < 下一个节气的 progress,显示蓝色
  1030. // 如果物候期所属的节气的 progress === 下一个节气的 progress,也显示蓝色(当前节气)
  1031. // 也就是说,只有属于当前节气或之前节气的物候期才显示蓝色
  1032. if (phenologyTermProgress === -1) {
  1033. return false;
  1034. }
  1035. // 如果物候期正好属于下一个节气,需要判断它的 progress 是否在下一个节气的范围内
  1036. if (phenologyTermProgress === nextTermProgress && nextTerm) {
  1037. // 如果物候期的 progress 小于等于下一个节气的 progress,说明它属于当前节气,显示蓝色
  1038. return phenologyProgress <= nextTermProgress;
  1039. }
  1040. // 如果物候期所属的节气的 progress < 下一个节气的 progress,显示蓝色
  1041. return phenologyTermProgress < nextTermProgress;
  1042. };
  1043. // 最外层物候期标题:与内层生育期对齐——任一生育行因农事≤今天变蓝;农事记录下有待认证则整段标题也蓝;否则按节气规则(右侧卡片仍按单卡日期置灰)
  1044. const shouldShowBlue = (phenology) => {
  1045. if (phenologyHasFarmWorkOnOrBeforeToday(phenology)) return true;
  1046. if (agriRecordHasPendingAuthInPhenology(phenology)) return true;
  1047. if (phenologyAllDatedFarmWorksStrictlyFuture(phenology)) return false;
  1048. return shouldShowBlueBase(phenology);
  1049. };
  1050. // 左侧生育期/物候期文案:
  1051. // 1) 本行有农事<=今天:蓝;
  1052. // 2) 本行全部有效日期农事均为未来且本行无待认证:灰(与右侧 future-card 一致);
  1053. // 3) 农事记录下物候期内有待认证:蓝;
  1054. // 4) 其余走节气/日期底色规则。
  1055. const shouldShowBlueLeft = (phenology, reproductive) => {
  1056. if (reproductiveHasFarmWorkOnOrBeforeToday(reproductive)) return true;
  1057. if (reproductiveAllDatedFarmWorksStrictlyFuture(reproductive) && !reproductiveHasPendingAuthFarmWork(reproductive)) {
  1058. return false;
  1059. }
  1060. if (agriRecordHasPendingAuthInPhenology(phenology)) return true;
  1061. return shouldShowBlueBase(phenology);
  1062. };
  1063. defineExpose({
  1064. updateFarmWorkPlan,
  1065. });
  1066. // 使用 ResizeObserver 监听高度变化,确保在DOM完全渲染后获取准确高度
  1067. const setupResizeObserver = () => {
  1068. if (!timelineListRef.value || typeof ResizeObserver === "undefined") {
  1069. return;
  1070. }
  1071. // 如果已经存在观察者,先断开
  1072. if (resizeObserver) {
  1073. resizeObserver.disconnect();
  1074. }
  1075. // 创建新的观察者
  1076. resizeObserver = new ResizeObserver((entries) => {
  1077. for (const entry of entries) {
  1078. const height = entry.contentRect.height;
  1079. if (height > 0 && height !== timelineListHeight.value) {
  1080. timelineListHeight.value = height;
  1081. }
  1082. }
  1083. });
  1084. // 开始观察
  1085. resizeObserver.observe(timelineListRef.value);
  1086. };
  1087. // 组件挂载后设置 ResizeObserver
  1088. onMounted(() => {
  1089. nextTick(() => {
  1090. requestAnimationFrame(() => {
  1091. setupResizeObserver();
  1092. restoreTimelineScrollTopWithRetry();
  1093. });
  1094. });
  1095. });
  1096. // 组件卸载前清理 ResizeObserver
  1097. onUnmounted(() => {
  1098. saveTimelineScrollTop();
  1099. if (resizeObserver) {
  1100. resizeObserver.disconnect();
  1101. resizeObserver = null;
  1102. }
  1103. });
  1104. onActivated(() => {
  1105. nextTick(() => {
  1106. requestAnimationFrame(() => {
  1107. restoreTimelineScrollTopWithRetry();
  1108. });
  1109. });
  1110. });
  1111. onDeactivated(() => {
  1112. saveTimelineScrollTop();
  1113. });
  1114. onBeforeRouteLeave(() => {
  1115. saveTimelineScrollTop();
  1116. });
  1117. // 在数据更新后重新设置 ResizeObserver
  1118. watch(
  1119. () => phenologyList.value.length,
  1120. () => {
  1121. nextTick(() => {
  1122. requestAnimationFrame(() => {
  1123. setupResizeObserver();
  1124. });
  1125. });
  1126. }
  1127. );
  1128. </script>
  1129. <style scoped lang="scss">
  1130. .timeline-container {
  1131. height: 100%;
  1132. overflow: auto;
  1133. position: relative;
  1134. box-sizing: border-box;
  1135. .timeline-list {
  1136. position: relative;
  1137. }
  1138. .timeline-middle-line {
  1139. position: absolute;
  1140. left: 13px;
  1141. /* 位于节气文字列中间(列宽约30px) */
  1142. top: 0;
  1143. bottom: 0;
  1144. width: 2px;
  1145. background: #e8e8e8;
  1146. z-index: 1;
  1147. }
  1148. .phenology-bar {
  1149. align-items: stretch;
  1150. justify-content: center;
  1151. box-sizing: border-box;
  1152. position: relative;
  1153. .phenology-title {
  1154. width: 18px;
  1155. height: 99.5%;
  1156. color: #fff;
  1157. font-size: 12px;
  1158. position: absolute;
  1159. // left: 39px;
  1160. left: -1px;
  1161. z-index: 10;
  1162. text-align: center;
  1163. display: flex;
  1164. align-items: center;
  1165. &.phenology-blue {
  1166. background: #2199f8;
  1167. }
  1168. &.phenology-red {
  1169. background: #f1f1f1;
  1170. color: #808080;
  1171. }
  1172. }
  1173. .reproductive-item {
  1174. font-size: 12px;
  1175. text-align: center;
  1176. word-break: break-all;
  1177. writing-mode: vertical-rl;
  1178. text-orientation: upright;
  1179. letter-spacing: 3px;
  1180. width: 100%;
  1181. line-height: 23px;
  1182. color: inherit;
  1183. position: relative;
  1184. .phenology-name {
  1185. width: 18px;
  1186. line-height: 16px;
  1187. height: 100%;
  1188. color: #fff;
  1189. padding: 4px 0;
  1190. font-size: 12px;
  1191. box-sizing: border-box;
  1192. &.mr {
  1193. margin-right: 3px;
  1194. }
  1195. &.single {
  1196. width: 39px;
  1197. line-height: 39px;
  1198. // z-index: 10;
  1199. // position: relative;
  1200. }
  1201. &.phenology-blue {
  1202. background: #2199f8;
  1203. }
  1204. &.phenology-red {
  1205. background: #f1f1f1;
  1206. color: #808080;
  1207. }
  1208. &.text-blue {
  1209. background: rgba(33, 153, 248, 0.15);
  1210. color: #2199f8;
  1211. border: 1px solid #2199f8;
  1212. line-height: 16px;
  1213. box-sizing: border-box;
  1214. }
  1215. &.text-red {
  1216. background: rgba(128, 128, 128, 0.15);
  1217. color: #808080;
  1218. border: 1px solid rgba(128, 128, 128, 0.35);
  1219. line-height: 16px;
  1220. box-sizing: border-box;
  1221. }
  1222. }
  1223. .arranges {
  1224. display: flex;
  1225. max-width: calc(100vw - 88px);
  1226. min-width: calc(100vw - 78px);
  1227. gap: 5px;
  1228. letter-spacing: 0px;
  1229. &.arranges-min{
  1230. max-width: calc(100vw - 58px);
  1231. }
  1232. // min-height: 90px;
  1233. .arrange-card {
  1234. width: 95%;
  1235. border: 0.5px solid #2199f8;
  1236. border-radius: 8px;
  1237. background: #fff;
  1238. box-sizing: border-box;
  1239. position: relative;
  1240. padding: 8px 15px 8px 10px;
  1241. writing-mode: horizontal-tb;
  1242. margin-bottom: 10px;
  1243. // &.last-card {
  1244. // margin-bottom: 0;
  1245. // }
  1246. .card-content {
  1247. color: #242424;
  1248. display: flex;
  1249. justify-content: space-between;
  1250. align-items: center;
  1251. font-size: 14px;
  1252. .card-left {
  1253. width: calc(100% - 45px);
  1254. .left-info {
  1255. display: flex;
  1256. align-items: center;
  1257. gap: 6px;
  1258. .left-date {
  1259. color: #2199f8;
  1260. border: 1px solid #2199f8;
  1261. padding: 1px 0;
  1262. border-radius: 2px;
  1263. font-size: 12px;
  1264. width: 45px;
  1265. box-sizing: border-box;
  1266. }
  1267. .text {
  1268. display: flex;
  1269. align-items: center;
  1270. gap: 2px;
  1271. width: calc(100% - 50px);
  1272. }
  1273. }
  1274. .title-text {
  1275. margin-top: 5px;
  1276. width: fit-content;
  1277. max-width: 100%;
  1278. text-align: left;
  1279. color: #2199F8;
  1280. padding: 0 6px;
  1281. border-radius: 2px;
  1282. font-size: 12px;
  1283. box-sizing: border-box;
  1284. background: rgba(33, 153, 248, 0.1);
  1285. }
  1286. &.agri-record-card {
  1287. .title-wrap {
  1288. display: flex;
  1289. align-items: flex-end;
  1290. gap: 6px;
  1291. .expert-info {
  1292. display: flex;
  1293. align-items: center;
  1294. gap: 2px;
  1295. font-size: 12px;
  1296. color: #B7B7B7;
  1297. }
  1298. .blue-tag{
  1299. color: #2199F8;
  1300. background: rgba(33, 153, 248, 0.1);
  1301. }
  1302. }
  1303. }
  1304. }
  1305. .card-right {
  1306. display: flex;
  1307. align-items: center;
  1308. position: relative;
  1309. img {
  1310. width: 45px;
  1311. height: 45px;
  1312. border-radius: 4px;
  1313. object-fit: cover;
  1314. }
  1315. .num {
  1316. position: absolute;
  1317. width: 18px;
  1318. height: 18px;
  1319. box-sizing: border-box;
  1320. top: -4px;
  1321. right: -6px;
  1322. background: #BFBFBF;
  1323. color: #fff;
  1324. font-size: 12px;
  1325. border-radius: 50%;
  1326. display: flex;
  1327. align-items: center;
  1328. justify-content: center;
  1329. }
  1330. }
  1331. }
  1332. &::before {
  1333. content: "";
  1334. position: absolute;
  1335. left: -5px;
  1336. top: 50%;
  1337. transform: translateY(-50%);
  1338. width: 0;
  1339. height: 0;
  1340. border-top: 5px solid transparent;
  1341. border-bottom: 5px solid transparent;
  1342. border-right: 5px solid #2199f8;
  1343. }
  1344. }
  1345. .arrange-card.normal-style {
  1346. opacity: 0.3;
  1347. }
  1348. .arrange-card.status-normal {
  1349. border-color: #2199f8;
  1350. &::before {
  1351. border-right-color: #2199f8;
  1352. }
  1353. }
  1354. .arrange-card.status-warning {
  1355. border-color: #FF4E4E;
  1356. .card-left {
  1357. .left-info {
  1358. .left-date {
  1359. color: #FF4E4E;
  1360. border-color: #FF4E4E;
  1361. }
  1362. }
  1363. .title-text {
  1364. color: #FF4E4E;
  1365. background: rgba(255, 78, 78, 0.1);
  1366. }
  1367. }
  1368. &::before {
  1369. border-right-color: #FF4E4E;
  1370. }
  1371. }
  1372. .arrange-card.status-warning.status-warning-agri-record {
  1373. border-color: #bbbbbb;
  1374. .card-left {
  1375. .left-info {
  1376. .left-date {
  1377. color: #bbbbbb;
  1378. border-color: #bbbbbb;
  1379. }
  1380. }
  1381. .text-name,.text-icon {
  1382. color: #bbbbbb;
  1383. }
  1384. }
  1385. &::before {
  1386. border-right-color: #bbbbbb;
  1387. }
  1388. }
  1389. .arrange-card.status-complete {
  1390. border-color: #FF943D;
  1391. .card-left {
  1392. .left-info {
  1393. .left-date {
  1394. color: #FF943D;
  1395. border-color: #FF943D;
  1396. }
  1397. }
  1398. .title-text {
  1399. color: #FF943D;
  1400. background: rgba(255, 149, 61, 0.1);
  1401. }
  1402. }
  1403. &::before {
  1404. border-right-color: #FF943D;
  1405. }
  1406. }
  1407. .arrange-card.status-act {
  1408. border-color: #FF953D;
  1409. .card-left {
  1410. .left-info {
  1411. .left-date {
  1412. color: #FF953D;
  1413. border-color: #FF953D;
  1414. }
  1415. }
  1416. .title-text {
  1417. color: #fff;
  1418. background: #FF953D;
  1419. }
  1420. }
  1421. &::before {
  1422. border-right-color: #FF953D;
  1423. }
  1424. }
  1425. .arrange-card.status-default {
  1426. border-color: #BBBBBB;
  1427. .card-left {
  1428. .left-info {
  1429. .left-date {
  1430. color: #BBBBBB;
  1431. border-color: #BBBBBB;
  1432. }
  1433. .text-name,
  1434. .text-icon {
  1435. color: #BBBBBB;
  1436. }
  1437. }
  1438. .title-text {
  1439. color: #fff;
  1440. background: #BBBBBB;
  1441. }
  1442. }
  1443. &::before {
  1444. border-right-color: #BBBBBB;
  1445. }
  1446. }
  1447. // 未来节气对应的农事卡片:跟随左侧物候期的“未开始”灰色样式
  1448. .arrange-card.future-card {
  1449. border-color: #e4e4e4;
  1450. .card-content {
  1451. color: rgba(36, 36, 36, 0.5);
  1452. }
  1453. .card-left {
  1454. .left-info {
  1455. .left-date {
  1456. color: #CACACA;
  1457. border-color: #e4e4e4;
  1458. }
  1459. }
  1460. }
  1461. &::before {
  1462. border-right-color: #e4e4e4;
  1463. }
  1464. }
  1465. .arrange-card.status-warning-bg {
  1466. border-color: #FF943D;
  1467. .card-content {
  1468. color: #000;
  1469. }
  1470. .card-left {
  1471. .left-info {
  1472. .left-date {
  1473. color: #FF943D;
  1474. border-color: #FF943D;
  1475. }
  1476. }
  1477. .title-text {
  1478. color: #fff;
  1479. background: #FF943D;;
  1480. }
  1481. }
  1482. &::before {
  1483. border-right-color: #FF943D;
  1484. }
  1485. }
  1486. }
  1487. }
  1488. }
  1489. .reproductive-item+.reproductive-item {
  1490. padding-top: 3px;
  1491. }
  1492. .phenology-bar+.phenology-bar {
  1493. padding-top: 3px;
  1494. }
  1495. .timeline-term {
  1496. position: absolute;
  1497. width: 34px;
  1498. display: flex;
  1499. align-items: flex-start;
  1500. flex-direction: column;
  1501. z-index: 2;
  1502. /* 置于中线之上 */
  1503. color: rgba(174, 174, 174, 0.6);
  1504. .term-name {
  1505. display: inline-block;
  1506. width: 100%;
  1507. min-height: 20px;
  1508. line-height: 26px;
  1509. background: #fff;
  1510. font-size: 12px;
  1511. }
  1512. }
  1513. .empty-state {
  1514. display: flex;
  1515. justify-content: center;
  1516. align-items: center;
  1517. min-height: 200px;
  1518. width: 100%;
  1519. }
  1520. }
  1521. </style>