ArchivesFarmTimeLine.vue 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677
  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. disableClick: {
  133. type: Boolean,
  134. default: false,
  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"]);
  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. if (!props.farmId) return;
  553. const scopeKey = farmWorkPlanScopeKey();
  554. if (isRequesting.value || lastRequestedFarmId.value === scopeKey) return;
  555. isRequesting.value = true;
  556. lastRequestedFarmId.value = scopeKey;
  557. // 更新时间戳,确保key变化,触发DOM重新渲染
  558. uniqueTimestamp.value = Date.now();
  559. // 重置测量高度,等待重新测量
  560. timelineListHeight.value = 0;
  561. // 重置空数据状态
  562. isEmpty.value = false;
  563. let savedScrollTop = 0;
  564. if (!isInitialLoad.value && timelineContainerRef.value) {
  565. savedScrollTop = timelineContainerRef.value.scrollTop || 0;
  566. }
  567. const apiFunc = props.pageType === 'agri_record' ? VE_API.monitor.getFarmWorkPlan : VE_API.monitor.getArchivesList;
  568. const params = {
  569. farmId: props.farmId,
  570. regionId: props.regionId,
  571. problemZoneId: props.problemZoneId,
  572. }
  573. if (props.pageType === 'agri_record') {
  574. params.containerId = props.containerId;
  575. }
  576. apiFunc(params)
  577. .then(async ({ data, code }) => {
  578. if (code === 0) {
  579. const list = Array.isArray(data?.solarTermsList) ? data.solarTermsList : [];
  580. const filtered = list
  581. .filter((t) => t && t.type === 1)
  582. .map((t) => ({
  583. id:
  584. t.id ??
  585. t.solarTermsId ??
  586. t.termId ??
  587. `${t.name || t.solarTermsName || t.termName || "term"}-${t.createDate || ""}`,
  588. displayName: t.name || t.solarTermsName || t.termName || "节气",
  589. createDate: t.createDate || null,
  590. progress: Number(t.progress) || 0,
  591. }));
  592. solarTerms.value = filtered;
  593. // 物候期数据
  594. const processedPhenologyList = Array.isArray(data?.phenologyList)
  595. ? await Promise.all(
  596. data.phenologyList.map(async (it) => {
  597. const reproductiveList = Array.isArray(it.reproductiveList)
  598. ? await Promise.all(
  599. it.reproductiveList.map(async (r) => {
  600. const farmWorkArrangeList = Array.isArray(r.broadcastList || r.interactionFarmWorkList)
  601. ? await Promise.all(
  602. (r.broadcastList || r.interactionFarmWorkList).map(async (fw) => {
  603. const sourceDataJson = parseSourceDataSafe(fw.sourceData);
  604. // 如果有 imageIds,获取图片 URL
  605. if (
  606. sourceDataJson &&
  607. sourceDataJson.imageIds &&
  608. Array.isArray(sourceDataJson.imageIds) &&
  609. sourceDataJson.imageIds.length > 0
  610. ) {
  611. const resFilenameList = await fetchImageUrls(
  612. {
  613. imageIds: sourceDataJson.imageIds,
  614. page: 1,
  615. limit: 100,
  616. }
  617. );
  618. sourceDataJson.resFilename = resFilenameList;
  619. // 调用 findSuitabilityByPoint 接口获取天气适宜性信息
  620. if (fw.farmId && fw.createTime) {
  621. try {
  622. const dateStr = formatDateForAPI(fw.createTime);
  623. if (dateStr) {
  624. const suitabilityRes = await VE_API.ali.findSuitabilityByPoint({
  625. farmId: fw.farmId,
  626. date: dateStr,
  627. });
  628. if (suitabilityRes && suitabilityRes.code === 0 && suitabilityRes.data) {
  629. // 将返回的数据合并到 sourceDataJson
  630. sourceDataJson.suitability = suitabilityRes.data;
  631. }
  632. }
  633. } catch (error) {
  634. console.error("获取天气适宜性信息失败:", error);
  635. }
  636. }
  637. }
  638. return {
  639. ...fw,
  640. phenologyName: r.phenologyName,
  641. sourceDataJson,
  642. containerSpaceTimeId: it.containerSpaceTimeId,
  643. };
  644. })
  645. )
  646. : [];
  647. return {
  648. ...r,
  649. farmWorkArrangeList,
  650. };
  651. })
  652. )
  653. : [];
  654. return {
  655. id: it.id ?? it.phenologyId ?? it.name ?? `${it.progress}-${it.progress2}`,
  656. progress: Number(it.progress) || 0, // 起点 %
  657. progress2: Number(it.progress2) || 0, // 终点 %
  658. phenologyName: it.phenologyName,
  659. startDate: it.startDate,
  660. startTimeMs: safeParseDate(
  661. it.startDate || it.beginDate || it.startTime || it.start || it.start_at
  662. ),
  663. reproductiveList,
  664. };
  665. })
  666. )
  667. : [];
  668. phenologyList.value = processedPhenologyList;
  669. // 使用多次 nextTick 和 requestAnimationFrame 确保DOM完全渲染
  670. nextTick(() => {
  671. requestAnimationFrame(() => {
  672. nextTick(() => {
  673. requestAnimationFrame(() => {
  674. // 测量timeline-list的实际渲染高度
  675. if (timelineListRef.value) {
  676. const height =
  677. timelineListRef.value.offsetHeight || timelineListRef.value.clientHeight;
  678. if (height > 0) {
  679. timelineListHeight.value = height;
  680. }
  681. }
  682. const hasRestoredScrollTop = restoreTimelineScrollTopWithRetry();
  683. if (isInitialLoad.value) {
  684. if (hasRestoredScrollTop) {
  685. isInitialLoad.value = false;
  686. } else {
  687. // 如果测量失败,延迟一下再尝试滚动
  688. setTimeout(() => {
  689. if (timelineListRef.value) {
  690. const height =
  691. timelineListRef.value.offsetHeight ||
  692. timelineListRef.value.clientHeight;
  693. if (height > 0) {
  694. timelineListHeight.value = height;
  695. }
  696. }
  697. if (!restoreTimelineScrollTopWithRetry()) {
  698. const currentSeason = getCurrentSeason();
  699. handleSeasonClick(currentSeason);
  700. }
  701. isInitialLoad.value = false;
  702. }, 200);
  703. }
  704. } else {
  705. if (!hasRestoredScrollTop && timelineContainerRef.value && savedScrollTop > 0) {
  706. timelineContainerRef.value.scrollTop = savedScrollTop;
  707. }
  708. }
  709. });
  710. });
  711. });
  712. });
  713. // 收集所有farmWorkId
  714. const farmWorkIds = [];
  715. const farmWorks = [];
  716. phenologyList.value.forEach((phenology) => {
  717. if (Array.isArray(phenology.reproductiveList)) {
  718. phenology.reproductiveList.forEach((reproductive) => {
  719. if (Array.isArray(reproductive.farmWorkArrangeList)) {
  720. reproductive.farmWorkArrangeList.forEach((farmWork) => {
  721. if (farmWork.farmWorkId && farmWork.isFollow !== 0) {
  722. farmWorkIds.push(farmWork.farmWorkId);
  723. farmWorks.push(farmWork);
  724. }
  725. });
  726. }
  727. });
  728. }
  729. });
  730. // 调用验证方法,传入所有ids
  731. if (farmWorkIds.length > 0) {
  732. batchValidatePesticideFertilizerQuotes(farmWorkIds, farmWorks);
  733. }
  734. // 判断是否为空数据:没有节气或没有物候期数据
  735. if (solarTerms.value.length === 0 && phenologyList.value.length === 0) {
  736. isEmpty.value = true;
  737. } else {
  738. isEmpty.value = false;
  739. }
  740. } else {
  741. // 接口返回错误码,显示暂无数据
  742. isEmpty.value = true;
  743. solarTerms.value = [];
  744. phenologyList.value = [];
  745. }
  746. })
  747. .catch((error) => {
  748. console.error("获取农事规划数据失败:", error);
  749. ElMessage.error("获取农事规划数据失败");
  750. // 接口报错,显示暂无数据
  751. isEmpty.value = true;
  752. solarTerms.value = [];
  753. phenologyList.value = [];
  754. })
  755. .finally(() => {
  756. // 请求完成,重置请求标志
  757. isRequesting.value = false;
  758. });
  759. };
  760. const updateFarmWorkPlan = () => {
  761. solarTerms.value = [];
  762. phenologyList.value = [];
  763. isEmpty.value = false;
  764. getFarmWorkPlan();
  765. };
  766. watch(
  767. () => props.regionId,
  768. (val, oldVal) => {
  769. // 如果 farmId 没有值,则不触发
  770. if (!val) return;
  771. // 如果 farmId 变化了,重置上次请求的 farmId,允许请求新数据
  772. if (val !== oldVal) {
  773. lastRequestedFarmId.value = null;
  774. }
  775. // getFarmWorkPlan 内部已经有防重复请求的检查,这里直接调用即可
  776. isInitialLoad.value = true;
  777. updateFarmWorkPlan();
  778. },
  779. { immediate: true }
  780. );
  781. const showPhenologyName = computed(() => {
  782. return !props.problemZoneId;
  783. });
  784. watch(
  785. () => props.problemZoneId,
  786. (val, oldVal) => {
  787. if (!props.farmId) return;
  788. if (val !== oldVal) {
  789. lastRequestedFarmId.value = null;
  790. }
  791. isInitialLoad.value = true;
  792. updateFarmWorkPlan();
  793. },
  794. );
  795. const handleStatusDetail = (fw) => {
  796. // 跳转前记录当前滚动位置
  797. saveTimelineScrollTop();
  798. if (props.pageType === 'agri_plan') {
  799. if (fw?.sourceData && fw?.id) {
  800. router.push({
  801. path: "/agricultural_detail",
  802. query: {
  803. id: fw?.id,
  804. content: fw?.content
  805. },
  806. });
  807. }
  808. } else {
  809. router.push({
  810. path: "/work_detail",
  811. query: {
  812. miniJson: JSON.stringify({
  813. paramsPage: JSON.stringify({
  814. farmId: props.farmId,
  815. farmWorkLibId: fw?.farmWorkLibId,
  816. recordId: fw?.farmWorkRecordId,
  817. typeId: props.typeId
  818. }),
  819. }),
  820. },
  821. });
  822. }
  823. };
  824. // 格式化日期为 MM-DD 格式
  825. const formatDate = (dateStr) => {
  826. if (!dateStr) return "--";
  827. const date = new Date(dateStr);
  828. if (Number.isNaN(date.getTime())) return dateStr;
  829. const m = `${date.getMonth() + 1}`.padStart(2, "0");
  830. const d = `${date.getDate()}`.padStart(2, "0");
  831. return `${m}-${d}`;
  832. };
  833. // 格式化日期为 YYYY-MM-DD 格式(用于接口调用)
  834. const formatDateForAPI = (dateStr) => {
  835. if (!dateStr) return null;
  836. const date = new Date(dateStr);
  837. if (Number.isNaN(date.getTime())) return null;
  838. const y = date.getFullYear();
  839. const m = `${date.getMonth() + 1}`.padStart(2, "0");
  840. const d = `${date.getDate()}`.padStart(2, "0");
  841. return `${y}-${m}-${d}`;
  842. };
  843. // 获取下一个即将到来的节气(当前节气)的 progress
  844. const getNextTermProgress = () => {
  845. if (!solarTerms.value || solarTerms.value.length === 0) return Infinity;
  846. const now = new Date();
  847. now.setHours(0, 0, 0, 0);
  848. let nextTermProgress = Infinity;
  849. // 找到当前日期之后的下一个节气(当前节气)
  850. solarTerms.value.forEach((term) => {
  851. const termDate = safeParseDate(term.createDate);
  852. if (!isNaN(termDate)) {
  853. const termDateObj = new Date(termDate);
  854. termDateObj.setHours(0, 0, 0, 0);
  855. // 找到大于等于当前日期的第一个节气
  856. if (termDateObj >= now) {
  857. const termProgress = Number(term.progress) || 0;
  858. if (termProgress < nextTermProgress) {
  859. nextTermProgress = termProgress;
  860. }
  861. }
  862. }
  863. });
  864. // 如果没有找到未来的节气,说明所有节气都已过,返回 Infinity(所有物候期都显示蓝色)
  865. return nextTermProgress === Infinity ? Infinity : nextTermProgress;
  866. };
  867. // 根据物候期的 progress 判断它所属节气的 progress
  868. const getPhenologyTermProgress = (phenologyProgress) => {
  869. if (!solarTerms.value || solarTerms.value.length === 0) return -1;
  870. const progress = Number(phenologyProgress) || 0;
  871. // 找到物候期所属的节气(progress 最接近且小于等于的节气)
  872. let matchedTermProgress = -1;
  873. solarTerms.value.forEach((term) => {
  874. const termProgress = Number(term.progress) || 0;
  875. if (progress >= termProgress && termProgress > matchedTermProgress) {
  876. matchedTermProgress = termProgress;
  877. }
  878. });
  879. // 如果物候期的 progress 小于所有节气,返回第一个节气的 progress
  880. if (matchedTermProgress === -1 && solarTerms.value.length > 0) {
  881. const firstTermProgress = Number(solarTerms.value[0].progress) || 0;
  882. return firstTermProgress;
  883. }
  884. return matchedTermProgress;
  885. };
  886. const flowStatusStr = {
  887. '3': '待认证',
  888. '-1': '已过期',
  889. '-2': '已过期',
  890. '5': '已认证',
  891. }
  892. // 右侧农事卡片展示用日期(与模板 left-date 一致:规划 createTime、记录 recommendDate)
  893. const getFarmWorkTimelineDateMs = (fw) => {
  894. const primary = props.pageType === "agri_plan" ? fw?.createTime : fw?.recommendDate ?? fw?.createTime;
  895. let ms = safeParseDate(primary);
  896. if (Number.isNaN(ms) || ms <= 0) {
  897. ms = safeParseDate(props.pageType === "agri_plan" ? fw?.recommendDate : fw?.createTime);
  898. }
  899. return ms;
  900. };
  901. const isFarmWorkDateOnOrBeforeToday = (ms) => {
  902. if (Number.isNaN(ms) || ms <= 0) return false;
  903. const today = new Date();
  904. today.setHours(0, 0, 0, 0);
  905. const d = new Date(ms);
  906. d.setHours(0, 0, 0, 0);
  907. return d.getTime() <= today.getTime();
  908. };
  909. // 单张卡片:有有效展示日期且晚于今天 → 未来农事,右侧应置灰(与 left-date 同一套字段)
  910. const isFarmWorkTimelineStrictlyFuture = (fw) => {
  911. const ms = getFarmWorkTimelineDateMs(fw);
  912. if (Number.isNaN(ms) || ms <= 0) return false;
  913. return !isFarmWorkDateOnOrBeforeToday(ms);
  914. };
  915. // 右侧 arrange-card:未来日期置灰;解析不到日期时回退物候期节气/待认证规则(与旧版整段逻辑一致)
  916. // 无农事展示日期时的置灰回退:仅用节气/物候期 + 待认证(不含「任一行农事≤今天」),避免右侧卡片被外层标题连带误判
  917. const isPhenologyActiveWithoutFarmWorkDates = (phenology) =>
  918. agriRecordHasPendingAuthInPhenology(phenology) || shouldShowBlueBase(phenology);
  919. const shouldGrayFarmWorkCard = (fw, phenology) => {
  920. if (isFarmWorkTimelineStrictlyFuture(fw)) return true;
  921. const ms = getFarmWorkTimelineDateMs(fw);
  922. if (!Number.isNaN(ms) && ms > 0) {
  923. return false;
  924. }
  925. return !isPhenologyActiveWithoutFarmWorkDates(phenology);
  926. };
  927. // 某一生育期行下是否存在「农事时间 ≤ 今天」的卡片(与右侧 left-date 字段一致)
  928. const reproductiveHasFarmWorkOnOrBeforeToday = (reproductive) => {
  929. const fws = Array.isArray(reproductive?.farmWorkArrangeList) ? reproductive.farmWorkArrangeList : [];
  930. for (const fw of fws) {
  931. if (isFarmWorkDateOnOrBeforeToday(getFarmWorkTimelineDateMs(fw))) {
  932. return true;
  933. }
  934. }
  935. return false;
  936. };
  937. // 物候期内是否至少有一行生育期因「农事≤今天」而高亮(用于最外层物候期标题与内层对齐)
  938. const phenologyHasFarmWorkOnOrBeforeToday = (phenology) => {
  939. const reproductives = Array.isArray(phenology?.reproductiveList) ? phenology.reproductiveList : [];
  940. return reproductives.some((r) => reproductiveHasFarmWorkOnOrBeforeToday(r));
  941. };
  942. // 该生育期下:存在农事且「凡有有效展示日期的卡片」全部严格晚于今天 → 左侧本行不因节气规则变蓝(与右侧 future-card 一致)
  943. const reproductiveAllDatedFarmWorksStrictlyFuture = (reproductive) => {
  944. const fws = Array.isArray(reproductive?.farmWorkArrangeList) ? reproductive.farmWorkArrangeList : [];
  945. if (fws.length === 0) return false;
  946. const dated = fws.filter((fw) => {
  947. const ms = getFarmWorkTimelineDateMs(fw);
  948. return !Number.isNaN(ms) && ms > 0;
  949. });
  950. if (dated.length === 0) return false;
  951. return dated.every((fw) => isFarmWorkTimelineStrictlyFuture(fw));
  952. };
  953. // 物候期内:至少有一条农事带有效日期,且全部带有效日期的农事均为「严格未来」(无一 ≤ 今天)→ 最外层标题不因节气单独变蓝
  954. const phenologyAllDatedFarmWorksStrictlyFuture = (phenology) => {
  955. const reproductives = Array.isArray(phenology?.reproductiveList) ? phenology.reproductiveList : [];
  956. let anyDated = false;
  957. for (const r of reproductives) {
  958. const fws = Array.isArray(r?.farmWorkArrangeList) ? r.farmWorkArrangeList : [];
  959. for (const fw of fws) {
  960. const ms = getFarmWorkTimelineDateMs(fw);
  961. if (Number.isNaN(ms) || ms <= 0) continue;
  962. anyDated = true;
  963. if (isFarmWorkDateOnOrBeforeToday(ms)) return false;
  964. }
  965. }
  966. return anyDated;
  967. };
  968. // 仅农事记录页(agri_record):该物候期内存在待认证农事时,左侧最外层物候期与各生育期/物候期文案均高亮为蓝;农事规划(agri_plan)不生效
  969. const agriRecordHasPendingAuthInPhenology = (phenology) => {
  970. if (props.pageType !== "agri_record") return false;
  971. return (Array.isArray(phenology?.reproductiveList) ? phenology.reproductiveList : []).some((reproductive) =>
  972. (Array.isArray(reproductive?.farmWorkArrangeList) ? reproductive.farmWorkArrangeList : []).some((fw) => {
  973. const s = fw?.flowStatus;
  974. return s === 3 || s === "3";
  975. })
  976. );
  977. };
  978. // 单行生育期下是否有待认证农事(仅农事记录页)
  979. const reproductiveHasPendingAuthFarmWork = (reproductive) => {
  980. if (props.pageType !== "agri_record") return false;
  981. return (Array.isArray(reproductive?.farmWorkArrangeList) ? reproductive.farmWorkArrangeList : []).some((fw) => {
  982. const s = fw?.flowStatus;
  983. return s === 3 || s === "3";
  984. });
  985. };
  986. // 物候期底色/节气规则(不含「农事卡片日期」「待认证」扩展)
  987. const shouldShowBlueBase = (phenology) => {
  988. // 优先使用物候期真实日期判断:未来日期不应显示蓝色
  989. const phenologyTimeMs =
  990. Number(phenology?.startTimeMs) ||
  991. safeParseDate(phenology?.startDate || phenology?.beginDate || phenology?.startTime || phenology?.start || phenology?.start_at);
  992. if (!Number.isNaN(phenologyTimeMs) && phenologyTimeMs > 0) {
  993. const today = new Date();
  994. today.setHours(0, 0, 0, 0);
  995. return phenologyTimeMs <= today.getTime();
  996. }
  997. // 日期缺失时,回退到 progress 规则(兼容老数据)
  998. // 获取下一个即将到来的节气(当前节气)的 progress
  999. const nextTermProgress = getNextTermProgress();
  1000. // 如果所有节气都已过(nextTermProgress === Infinity),所有物候期都显示蓝色
  1001. if (nextTermProgress === Infinity) {
  1002. return true;
  1003. }
  1004. // 根据物候期的 progress 判断它属于哪个节气
  1005. const phenologyProgress = Math.min(Number(phenology?.progress) || 0, Number(phenology?.progress2) || 0);
  1006. const phenologyTermProgress = getPhenologyTermProgress(phenologyProgress);
  1007. // 找到下一个节气的完整信息,用于判断物候期是否属于当前节气
  1008. let nextTerm = null;
  1009. solarTerms.value.forEach((term) => {
  1010. const termProgress = Number(term.progress) || 0;
  1011. if (termProgress === nextTermProgress) {
  1012. nextTerm = term;
  1013. }
  1014. });
  1015. // 如果物候期所属的节气的 progress < 下一个节气的 progress,显示蓝色
  1016. // 如果物候期所属的节气的 progress === 下一个节气的 progress,也显示蓝色(当前节气)
  1017. // 也就是说,只有属于当前节气或之前节气的物候期才显示蓝色
  1018. if (phenologyTermProgress === -1) {
  1019. return false;
  1020. }
  1021. // 如果物候期正好属于下一个节气,需要判断它的 progress 是否在下一个节气的范围内
  1022. if (phenologyTermProgress === nextTermProgress && nextTerm) {
  1023. // 如果物候期的 progress 小于等于下一个节气的 progress,说明它属于当前节气,显示蓝色
  1024. return phenologyProgress <= nextTermProgress;
  1025. }
  1026. // 如果物候期所属的节气的 progress < 下一个节气的 progress,显示蓝色
  1027. return phenologyTermProgress < nextTermProgress;
  1028. };
  1029. // 最外层物候期标题:与内层生育期对齐——任一生育行因农事≤今天变蓝;农事记录下有待认证则整段标题也蓝;否则按节气规则(右侧卡片仍按单卡日期置灰)
  1030. const shouldShowBlue = (phenology) => {
  1031. if (phenologyHasFarmWorkOnOrBeforeToday(phenology)) return true;
  1032. if (agriRecordHasPendingAuthInPhenology(phenology)) return true;
  1033. if (phenologyAllDatedFarmWorksStrictlyFuture(phenology)) return false;
  1034. return shouldShowBlueBase(phenology);
  1035. };
  1036. // 左侧生育期/物候期文案:
  1037. // 1) 本行有农事<=今天:蓝;
  1038. // 2) 本行全部有效日期农事均为未来且本行无待认证:灰(与右侧 future-card 一致);
  1039. // 3) 农事记录下物候期内有待认证:蓝;
  1040. // 4) 其余走节气/日期底色规则。
  1041. const shouldShowBlueLeft = (phenology, reproductive) => {
  1042. if (reproductiveHasFarmWorkOnOrBeforeToday(reproductive)) return true;
  1043. if (reproductiveAllDatedFarmWorksStrictlyFuture(reproductive) && !reproductiveHasPendingAuthFarmWork(reproductive)) {
  1044. return false;
  1045. }
  1046. if (agriRecordHasPendingAuthInPhenology(phenology)) return true;
  1047. return shouldShowBlueBase(phenology);
  1048. };
  1049. defineExpose({
  1050. updateFarmWorkPlan,
  1051. });
  1052. // 使用 ResizeObserver 监听高度变化,确保在DOM完全渲染后获取准确高度
  1053. const setupResizeObserver = () => {
  1054. if (!timelineListRef.value || typeof ResizeObserver === "undefined") {
  1055. return;
  1056. }
  1057. // 如果已经存在观察者,先断开
  1058. if (resizeObserver) {
  1059. resizeObserver.disconnect();
  1060. }
  1061. // 创建新的观察者
  1062. resizeObserver = new ResizeObserver((entries) => {
  1063. for (const entry of entries) {
  1064. const height = entry.contentRect.height;
  1065. if (height > 0 && height !== timelineListHeight.value) {
  1066. timelineListHeight.value = height;
  1067. }
  1068. }
  1069. });
  1070. // 开始观察
  1071. resizeObserver.observe(timelineListRef.value);
  1072. };
  1073. // 组件挂载后设置 ResizeObserver
  1074. onMounted(() => {
  1075. nextTick(() => {
  1076. requestAnimationFrame(() => {
  1077. setupResizeObserver();
  1078. restoreTimelineScrollTopWithRetry();
  1079. });
  1080. });
  1081. });
  1082. // 组件卸载前清理 ResizeObserver
  1083. onUnmounted(() => {
  1084. saveTimelineScrollTop();
  1085. if (resizeObserver) {
  1086. resizeObserver.disconnect();
  1087. resizeObserver = null;
  1088. }
  1089. });
  1090. onActivated(() => {
  1091. nextTick(() => {
  1092. requestAnimationFrame(() => {
  1093. restoreTimelineScrollTopWithRetry();
  1094. });
  1095. });
  1096. });
  1097. onDeactivated(() => {
  1098. saveTimelineScrollTop();
  1099. });
  1100. onBeforeRouteLeave(() => {
  1101. saveTimelineScrollTop();
  1102. });
  1103. // 在数据更新后重新设置 ResizeObserver
  1104. watch(
  1105. () => phenologyList.value.length,
  1106. () => {
  1107. nextTick(() => {
  1108. requestAnimationFrame(() => {
  1109. setupResizeObserver();
  1110. });
  1111. });
  1112. }
  1113. );
  1114. </script>
  1115. <style scoped lang="scss">
  1116. .timeline-container {
  1117. height: 100%;
  1118. overflow: auto;
  1119. position: relative;
  1120. box-sizing: border-box;
  1121. .timeline-list {
  1122. position: relative;
  1123. }
  1124. .timeline-middle-line {
  1125. position: absolute;
  1126. left: 13px;
  1127. /* 位于节气文字列中间(列宽约30px) */
  1128. top: 0;
  1129. bottom: 0;
  1130. width: 2px;
  1131. background: #e8e8e8;
  1132. z-index: 1;
  1133. }
  1134. .phenology-bar {
  1135. align-items: stretch;
  1136. justify-content: center;
  1137. box-sizing: border-box;
  1138. position: relative;
  1139. .phenology-title {
  1140. width: 18px;
  1141. height: 99.5%;
  1142. color: #fff;
  1143. font-size: 12px;
  1144. position: absolute;
  1145. // left: 39px;
  1146. left: -1px;
  1147. z-index: 10;
  1148. text-align: center;
  1149. display: flex;
  1150. align-items: center;
  1151. &.phenology-blue {
  1152. background: #2199f8;
  1153. }
  1154. &.phenology-red {
  1155. background: #f1f1f1;
  1156. color: #808080;
  1157. }
  1158. }
  1159. .reproductive-item {
  1160. font-size: 12px;
  1161. text-align: center;
  1162. word-break: break-all;
  1163. writing-mode: vertical-rl;
  1164. text-orientation: upright;
  1165. letter-spacing: 3px;
  1166. width: 100%;
  1167. line-height: 23px;
  1168. color: inherit;
  1169. position: relative;
  1170. .phenology-name {
  1171. width: 18px;
  1172. line-height: 16px;
  1173. height: 100%;
  1174. color: #fff;
  1175. padding: 4px 0;
  1176. font-size: 12px;
  1177. box-sizing: border-box;
  1178. &.mr {
  1179. margin-right: 3px;
  1180. }
  1181. &.single {
  1182. width: 39px;
  1183. line-height: 39px;
  1184. // z-index: 10;
  1185. // position: relative;
  1186. }
  1187. &.phenology-blue {
  1188. background: #2199f8;
  1189. }
  1190. &.phenology-red {
  1191. background: #f1f1f1;
  1192. color: #808080;
  1193. }
  1194. &.text-blue {
  1195. background: rgba(33, 153, 248, 0.15);
  1196. color: #2199f8;
  1197. border: 1px solid #2199f8;
  1198. line-height: 16px;
  1199. box-sizing: border-box;
  1200. }
  1201. &.text-red {
  1202. background: rgba(128, 128, 128, 0.15);
  1203. color: #808080;
  1204. border: 1px solid rgba(128, 128, 128, 0.35);
  1205. line-height: 16px;
  1206. box-sizing: border-box;
  1207. }
  1208. }
  1209. .arranges {
  1210. display: flex;
  1211. max-width: calc(100vw - 88px);
  1212. min-width: calc(100vw - 78px);
  1213. gap: 5px;
  1214. letter-spacing: 0px;
  1215. &.arranges-min{
  1216. max-width: calc(100vw - 58px);
  1217. }
  1218. // min-height: 90px;
  1219. .arrange-card {
  1220. width: 95%;
  1221. border: 0.5px solid #2199f8;
  1222. border-radius: 8px;
  1223. background: #fff;
  1224. box-sizing: border-box;
  1225. position: relative;
  1226. padding: 8px 15px 8px 10px;
  1227. writing-mode: horizontal-tb;
  1228. margin-bottom: 10px;
  1229. // &.last-card {
  1230. // margin-bottom: 0;
  1231. // }
  1232. .card-content {
  1233. color: #242424;
  1234. display: flex;
  1235. justify-content: space-between;
  1236. align-items: center;
  1237. font-size: 14px;
  1238. .card-left {
  1239. width: calc(100% - 45px);
  1240. .left-info {
  1241. display: flex;
  1242. align-items: center;
  1243. gap: 6px;
  1244. .left-date {
  1245. color: #2199f8;
  1246. border: 1px solid #2199f8;
  1247. padding: 1px 0;
  1248. border-radius: 2px;
  1249. font-size: 12px;
  1250. width: 45px;
  1251. box-sizing: border-box;
  1252. }
  1253. .text {
  1254. display: flex;
  1255. align-items: center;
  1256. gap: 2px;
  1257. width: calc(100% - 50px);
  1258. }
  1259. }
  1260. .title-text {
  1261. margin-top: 5px;
  1262. width: fit-content;
  1263. max-width: 100%;
  1264. text-align: left;
  1265. color: #2199F8;
  1266. padding: 0 6px;
  1267. border-radius: 2px;
  1268. font-size: 12px;
  1269. box-sizing: border-box;
  1270. background: rgba(33, 153, 248, 0.1);
  1271. }
  1272. &.agri-record-card {
  1273. .title-wrap {
  1274. display: flex;
  1275. align-items: flex-end;
  1276. gap: 6px;
  1277. .expert-info {
  1278. display: flex;
  1279. align-items: center;
  1280. gap: 2px;
  1281. font-size: 12px;
  1282. color: #B7B7B7;
  1283. }
  1284. .blue-tag{
  1285. color: #2199F8;
  1286. background: rgba(33, 153, 248, 0.1);
  1287. }
  1288. }
  1289. }
  1290. }
  1291. .card-right {
  1292. display: flex;
  1293. align-items: center;
  1294. position: relative;
  1295. img {
  1296. width: 45px;
  1297. height: 45px;
  1298. border-radius: 4px;
  1299. object-fit: cover;
  1300. }
  1301. .num {
  1302. position: absolute;
  1303. width: 18px;
  1304. height: 18px;
  1305. box-sizing: border-box;
  1306. top: -4px;
  1307. right: -6px;
  1308. background: #BFBFBF;
  1309. color: #fff;
  1310. font-size: 12px;
  1311. border-radius: 50%;
  1312. display: flex;
  1313. align-items: center;
  1314. justify-content: center;
  1315. }
  1316. }
  1317. }
  1318. &::before {
  1319. content: "";
  1320. position: absolute;
  1321. left: -5px;
  1322. top: 50%;
  1323. transform: translateY(-50%);
  1324. width: 0;
  1325. height: 0;
  1326. border-top: 5px solid transparent;
  1327. border-bottom: 5px solid transparent;
  1328. border-right: 5px solid #2199f8;
  1329. }
  1330. }
  1331. .arrange-card.normal-style {
  1332. opacity: 0.3;
  1333. }
  1334. .arrange-card.status-normal {
  1335. border-color: #2199f8;
  1336. &::before {
  1337. border-right-color: #2199f8;
  1338. }
  1339. }
  1340. .arrange-card.status-warning {
  1341. border-color: #FF4E4E;
  1342. .card-left {
  1343. .left-info {
  1344. .left-date {
  1345. color: #FF4E4E;
  1346. border-color: #FF4E4E;
  1347. }
  1348. }
  1349. .title-text {
  1350. color: #FF4E4E;
  1351. background: rgba(255, 78, 78, 0.1);
  1352. }
  1353. }
  1354. &::before {
  1355. border-right-color: #FF4E4E;
  1356. }
  1357. }
  1358. .arrange-card.status-warning.status-warning-agri-record {
  1359. border-color: #bbbbbb;
  1360. .card-left {
  1361. .left-info {
  1362. .left-date {
  1363. color: #bbbbbb;
  1364. border-color: #bbbbbb;
  1365. }
  1366. }
  1367. .text-name,.text-icon {
  1368. color: #bbbbbb;
  1369. }
  1370. }
  1371. &::before {
  1372. border-right-color: #bbbbbb;
  1373. }
  1374. }
  1375. .arrange-card.status-complete {
  1376. border-color: #FF943D;
  1377. .card-left {
  1378. .left-info {
  1379. .left-date {
  1380. color: #FF943D;
  1381. border-color: #FF943D;
  1382. }
  1383. }
  1384. .title-text {
  1385. color: #FF943D;
  1386. background: rgba(255, 149, 61, 0.1);
  1387. }
  1388. }
  1389. &::before {
  1390. border-right-color: #FF943D;
  1391. }
  1392. }
  1393. .arrange-card.status-act {
  1394. border-color: #FF953D;
  1395. .card-left {
  1396. .left-info {
  1397. .left-date {
  1398. color: #FF953D;
  1399. border-color: #FF953D;
  1400. }
  1401. }
  1402. .title-text {
  1403. color: #fff;
  1404. background: #FF953D;
  1405. }
  1406. }
  1407. &::before {
  1408. border-right-color: #FF953D;
  1409. }
  1410. }
  1411. .arrange-card.status-default {
  1412. border-color: #BBBBBB;
  1413. .card-left {
  1414. .left-info {
  1415. .left-date {
  1416. color: #BBBBBB;
  1417. border-color: #BBBBBB;
  1418. }
  1419. .text-name,
  1420. .text-icon {
  1421. color: #BBBBBB;
  1422. }
  1423. }
  1424. .title-text {
  1425. color: #fff;
  1426. background: #BBBBBB;
  1427. }
  1428. }
  1429. &::before {
  1430. border-right-color: #BBBBBB;
  1431. }
  1432. }
  1433. // 未来节气对应的农事卡片:跟随左侧物候期的“未开始”灰色样式
  1434. .arrange-card.future-card {
  1435. border-color: #e4e4e4;
  1436. .card-content {
  1437. color: rgba(36, 36, 36, 0.5);
  1438. }
  1439. .card-left {
  1440. .left-info {
  1441. .left-date {
  1442. color: #CACACA;
  1443. border-color: #e4e4e4;
  1444. }
  1445. }
  1446. }
  1447. &::before {
  1448. border-right-color: #e4e4e4;
  1449. }
  1450. }
  1451. .arrange-card.status-warning-bg {
  1452. border-color: #FF943D;
  1453. .card-content {
  1454. color: #000;
  1455. }
  1456. .card-left {
  1457. .left-info {
  1458. .left-date {
  1459. color: #FF943D;
  1460. border-color: #FF943D;
  1461. }
  1462. }
  1463. .title-text {
  1464. color: #fff;
  1465. background: #FF943D;;
  1466. }
  1467. }
  1468. &::before {
  1469. border-right-color: #FF943D;
  1470. }
  1471. }
  1472. }
  1473. }
  1474. }
  1475. .reproductive-item+.reproductive-item {
  1476. padding-top: 3px;
  1477. }
  1478. .phenology-bar+.phenology-bar {
  1479. padding-top: 3px;
  1480. }
  1481. .timeline-term {
  1482. position: absolute;
  1483. width: 34px;
  1484. display: flex;
  1485. align-items: flex-start;
  1486. flex-direction: column;
  1487. z-index: 2;
  1488. /* 置于中线之上 */
  1489. color: rgba(174, 174, 174, 0.6);
  1490. .term-name {
  1491. display: inline-block;
  1492. width: 100%;
  1493. min-height: 20px;
  1494. line-height: 26px;
  1495. background: #fff;
  1496. font-size: 12px;
  1497. }
  1498. }
  1499. .empty-state {
  1500. display: flex;
  1501. justify-content: center;
  1502. align-items: center;
  1503. min-height: 200px;
  1504. width: 100%;
  1505. }
  1506. }
  1507. </style>