import PageContainerBehavior from "../../core/behavior/page-container.behavior"; import { DraggableSheetBehavior, getDraggableSheetContext, } from "../../core/behavior/draggableSheet.behavior"; import { login } from "../../lib/logic"; import { useRouteQuery } from "../../utils/route-query"; import { appUpdate } from "../../lib/wx/update"; import { addPatientOnlineRecordClockIn } from "./request"; const { shared, Easing, timing } = wx.worklet; const offset = shared(0); const menus = ["shareAppMessage", "shareTimeline"]; // pages/home/home.ts import { getPatients, healthReportMethod, healthIndexMethod, getSolarTerms, getShortScienceList, getPatientDescription, getNotDealLists, getCareList, } from "./request"; import { toCertificationPage, toChats } from "./router"; import { useLocation } from "../../lib/use/use-location"; Page({ data: { isShowComplete: true, careList: [], displayList: [] as { id: number; conditioningProgramType: string; operateBy?: string; operateTime: string; frequencyType: string; // 频次类型 frequencyMeasure: string; // 总用量 arrangeDate: string; // 下一次开始日期 finishCount: number; // 完成量 conditioningProgramName: string; // 调养计划名称 conditioningProgramSupplierName: string; // 调养计划供应商名称 expanded: boolean; }[], allExpanded: false, fixedHeight: "370rpx", tabbarValue: "/pages/home/home", pageHeight: "100vh", // 默认值 popupList: [] as AnyArray, isShowPopup: false, patients: [] as (App.Patient.Model & { isDefault: "Y" | "N" })[], patient: null as App.Patient.Model | null, patientDescription: "", healthId: "", healthReport: { data: null, message: "", loading: true }, healthIndex: { data: [], message: "" }, position: {} as AnyObject, location: {} as AnyObject, solarTerms: {} as AnyObject, sheet: false, scienceList: [] as AnyArray, _loaded: false, statusList: [] as AnyArray, switchType: "", carouselLoading: {} as Record, // 用于跟踪每个轮播图的加载状态 // 轮播媒体列表 carouselMediaList: [] as Array<{ type: "image" | "video"; src: string; poster?: string; title?: string; }>, }, behaviors: [ PageContainerBehavior, DraggableSheetBehavior(".draggable-sheet-wrapper"), ], // 获取调养计划 async getCareLists() { // 保存当前的展开状态 const currentExpandedStates = this.data.displayList.map((item: any) => ({ id: item.id, expanded: item.expanded, })); const res = await getCareList(); if (res && res.length > 0) { res.forEach((item: any, index: number) => { item.carouselMediaList = []; // 确保 item.id 存在且为数字类型 if (!item.id && item.id !== 0) { item.id = index; } // 确保 id 是数字类型 item.id = Number(item.id); // 添加photo if (item.photo) { item.carouselMediaList.push({ type: "image", src: item.photo, }); } // 添加itemImgFirst if (item?.itemImgFirst) { item.carouselMediaList.push({ type: "image", src: item.itemImgFirst, }); } // 添加itemVideoFirst if (item?.itemVideoFirst) { item.carouselMediaList.push({ type: "video", src: item.itemVideoFirst, }); } // 如果有轮播图内容,设置加载状态 if (item.carouselMediaList.length > 0) { this.setData({ [`carouselLoading.${item.id}`]: true, }); // 设置超时,防止一直显示加载中 setTimeout(() => { // 检查是否还在加载状态,如果是则自动隐藏 const currentLoading = this.data.carouselLoading; if (currentLoading && currentLoading[item.id]) { this.setData({ [`carouselLoading.${item.id}`]: false, }); } }, 10000); // 10秒后自动隐藏加载状态 } else { // 如果没有轮播图内容,确保不显示加载状态 this.setData({ [`carouselLoading.${item.id}`]: false, }); } }); // 先设置 careList this.setData({ careList: res, }); await this.updateDisplayList(currentExpandedStates); setTimeout(() => { res.forEach((item: any, index: number) => { if (item.carouselMediaList && item.carouselMediaList.length > 0) { this.setData({ [`careList[${index}].carouselMediaList`]: [ ...item.carouselMediaList, ], }); // 同时更新 displayList const displayIndex = this.data.displayList.findIndex( (displayItem: any) => displayItem.id === item.id ); if (displayIndex !== -1) { this.setData({ [`displayList[${displayIndex}].carouselMediaList`]: [ ...item.carouselMediaList, ], }); } } }); }, 100); } }, async onLoad(options) { appUpdate(); const query = useRouteQuery(options.scene!); if (query.ys) wx.setStorageSync("doctorId", query.ys); this.initFabAnimated(); if (options.switchType) { this.setData({ switchType: options.switchType, }); } }, async onShow() { wx.showShareMenu({ withShareTicket: true, menus }).then(); await this.load(); console.log( this.data.switchType, "home.ts中的switchType", this.data.patient ); // 如果是从一体机扫码进来的 有switchType值就直接跳转到注册页面 if ( this.data.switchType && ((this.data.patient as any)?.isPerfectInfo ?? true) ) { wx.navigateTo({ url: "/module/user/pages/user-certification/user-certification?type=home", }); } // 如果用户没有手机号每次进入页面都提示 点击跳到注册页补充 // todo 要先判断用户有没有手机号 isPerfectInfo是true 就出来弹窗提示用户 // if ((this.data.patient as any)?.isPerfectInfo ?? true) { // wx.showModal({ // title: "提示", // content: "手机号为空,请补充", // success: (res) => { // if (res.confirm) { // wx.navigateTo({ // url: "/module/user/pages/user-certification/user-certification?type=home", // }); // } // }, // }); // } }, onHide() { wx.hideShareMenu({ menus }).then(); offset.value = timing( 0, { duration: 100, easing: (Easing).linear }, () => { "worklet"; } ); }, onShareAppMessage(_opts): WechatMiniprogram.Page.ICustomShareContent { return { title: `健康为基,从容赏生活之美`, imageUrl: `https://wx.hzliuzhi.com/media/healthManager/wx/share.jpg`, path: `/pages/home/home`, }; }, onShareTimeline() { return { title: `健康为基,从容赏生活之美`, }; }, async updateDisplayList( preserveExpandedStates?: Array<{ id: number; expanded: boolean; }> ) { const { careList, allExpanded } = this.data; let newDisplayList: any[] = allExpanded || careList.length <= 4 ? careList : careList.slice(0, 4); // 如果有保存的展开状态,则恢复它们 if (preserveExpandedStates && preserveExpandedStates.length > 0) { newDisplayList = newDisplayList.map((item: any) => { const savedState = preserveExpandedStates.find( (state) => state.id === item.id ); if (savedState) { return { ...item, expanded: savedState.expanded, }; } return item; }); } this.setData({ displayList: newDisplayList, }); }, toggleAll() { this.setData( { allExpanded: !this.data.allExpanded }, this.updateDisplayList ); }, toggleItem(e: any) { const index = e.currentTarget.dataset.index; const key = `displayList[${index}].expanded`; this.setData({ [key]: !this.data.displayList[index].expanded }); }, // 核销记录 onRecord(e: any) { const id = e.currentTarget.dataset.id; if (id) { wx.navigateTo({ url: `/module/care/pages/care/verifyRecord?id=${id}`, }); } else { wx.showToast({ title: "暂无核销记录", icon: "none", }); } }, onClose() { this.setData({ isShowPopup: false, }); }, // 打卡 pushCard(e: any) { const id = e.currentTarget.dataset.id; wx.navigateTo({ url: `/module/article/pages/punch-card/punch-card?id=${id}`, }); }, calculatePageHeight() { const systemInfo = wx.getSystemInfoSync(); const windowHeight = systemInfo.windowHeight; // 屏幕可用高度 // 获取 tabbar 高度 const query = wx.createSelectorQuery(); query .select(".t-tabbar") .boundingClientRect((rect) => { if (rect) { const tabbarHeight = rect.height; const contentHeight = windowHeight - tabbarHeight; this.setData({ pageHeight: `${contentHeight}px`, }); } }) .exec(); }, getNotDealList() { getNotDealLists().then((res) => { if (res.length > 0) { this.setData({ popupList: res, }); this.setData({ isShowPopup: true, }); } }); }, showFollowPopup() { if (this.data.popupList.length > 0) { this.setData({ isShowPopup: true, }); } }, onVisibleChange(e: { detail: { visible: any } }) { this.setData({ isShowPopup: e.detail.visible, }); }, // 诊疗随访提醒 goComplete(e: { currentTarget: { dataset: { page: string; id: number; title: string } }; }) { const { title } = e.currentTarget.dataset; let page = e.currentTarget.dataset.page; let id = e.currentTarget.dataset.id; // let page = '/module/chats/pages/index/index'; // let id = 1; if (page === "/module/chats/pages/index/index") { if (title === "健康评估") { wx.setStorageSync("isAnalysis", 4); toChats("questionnaire", 2); } else { wx.setStorageSync("isAnalysis", 2); wx.setStorageSync("workId", id); wx.navigateTo({ url: `${page}?component=questionnaire&messageType=1&id=${id}`, }); } } else { wx.navigateTo({ url: `${page}?id=${id}` }); // wx.navigateTo({ url: `/module/follow/pages/evaluation/report?id=${id}` }); } }, // 随访评估报告已出 goSeeFollowReport() { wx.navigateTo({ url: "/module/follow/pages/evaluation/report" }); }, async load(forceLogin = false) { try { await login(forceLogin); wx.showLoading({ title: "加载中" }); const { patient } = await getPatients(/*this.data.patientId*/); // if (!patient) await toCertificationPage(); if (!patient) { /*if (wx.getStorageSync("doctorId")) { toCertificationPage(); }*/ this.setData({ "healthReport.loading": false, isShowComplete: true, }); } else { this.setData({ patient }); this.observerPatient(patient); } wx.hideLoading(); } catch (error: any) { await wx .showModal({ title: `加载失败`, content: `${error?.errMsg ?? error?.message ?? ""}`, showCancel: false, confirmText: `重新加载`, }) .catch(() => {}); await this.load(true); return; } if (!this.data._loaded) { this.loadScienceList(); useLocation() .then((location) => { this.setData({ location }); }) .catch(() => {}); getSolarTerms() .then((solarTerms) => { this.setData({ solarTerms }); }) .catch(() => {}); this.setData({ _loaded: true }); } }, async _getHealthReport() { wx.showLoading({ title: "加载中" }); this.setData({ "healthReport.loading": true }); try { const data = await healthReportMethod(); if (!data) { this.setData({ isShowComplete: true, }); } else { this.setData({ isShowComplete: false, }); } this.setData({ "healthReport.data": data, "healthReport.loading": false, healthId: data?.healthAnalysisReportId, }); let arr2 = [ [ { title: "健康状态", value: data?.willillStateName ? `${data?.willillStateName}` : "", }, { title: "程度", value: data?.willillDegreeName ? `${data?.willillDegreeName}` : "", }, { title: "表现", value: data?.willillFunctionName ? `${data?.willillFunctionName}` : "", }, ], [ { title: "中医证素", value: data?.factorItemSummary ? `${data?.factorItemSummary}` : "", }, ], [ { title: "体质", value: data?.constitutionGroupName ? `${data?.constitutionGroupName}` : "", }, ], ]; this.setData({ statusList: arr2, }); // if (!data?.healthAnalysisReportId) { // this.setData({ // isShowComplete: true, // }); // } } catch (error: any) { wx.showToast({ title: error.errMsg || "加载失败", icon: "none", }); this.setData({ "healthReport.data": [], "healthReport.loading": false, "healthReport.message": error.errMsg, healthId: "", }); } wx.hideLoading(); }, async _getAbnormalHealthIndex() { this.setData({ "healthIndex.loading": true }); try { const data = await healthIndexMethod(); this.setData({ "healthIndex.data": data .map((item: AnyObject) => item.abnormalDesc) .filter(Boolean), "healthIndex.loading": false, }); } catch (error: any) { this.setData({ "healthIndex.data": [], "healthIndex.loading": false, "healthIndex.message": error.errMsg, }); } }, onBodyModel(event: WechatMiniprogram.TouchEvent) { if (event.detail?.position === "LB") { this.toReportPage(); } else if (event.detail?.position === "item0") { const report = this.data.healthReport.data as unknown as AnyObject; this.setData({ position: { LT: [ "willillState", "willillDegree", "willillSocial", "willillFunction", ] .map((key) => { const title = report[`${key}Name`]; const description = report[`${key}Description`]; return title || description ? { title, description } : null; }) .filter(Boolean), }, }); this.showDraggableSheet(); } else if (event.detail?.position === "item2") { const report = this.data.healthReport.data as unknown as AnyObject; const get = (key: string) => ({ [key]: report[key] }); this.setData({ position: { RT: { ...get("constitutionGroupName"), ...get("constitutionGroupDefinition"), ...get("faceImg"), ...get("faceAnalysisResult"), ...get("tongueAnalysisResult"), ...get("upImg"), ...get("downImg"), }, }, }); this.showDraggableSheet(); } else if (event.detail?.position === "item1") { const report = this.data.healthReport.data as unknown as AnyObject; const get = (key: string) => ({ [key]: report[key] }); this.setData({ position: { RB: { ...get("diagnoseSyndromeSummary"), ...get("diagnoseSyndromes"), ...get("factorItemSummary"), ...get("factorItems"), }, }, }); this.showDraggableSheet(); } else if (event.detail?.position === "CT") { this.setData({ position: { CT: this.data.healthIndex.data.map( (item, index) => `${index + 1}、${item}` ), }, }); this.showDraggableSheet(); } }, tabValue() { this.setData({ position: { CT: this.data.healthIndex.data.map( (item, index) => `${index + 1}、${item}` ), }, }); this.showDraggableSheet(); }, initFabAnimated() { (this).applyAnimatedStyle(".fab-wrapper", () => { "worklet"; return { right: `${Math.min(offset.value, 36) - 36}px` }; }); (this).applyAnimatedStyle(".fab-1", () => { "worklet"; return { transform: `translateY(${-offset.value}px)` }; }); (this).applyAnimatedStyle(".fab-2", () => { "worklet"; return { transform: `translateX(${-offset.value}px) translateY(${ -offset.value / 2 }px)`, }; }); (this).applyAnimatedStyle(".fab-3", () => { "worklet"; return { transform: `translateX(${-offset.value}px) translateY(${ offset.value / 2 }px)`, }; }); (this).applyAnimatedStyle(".fab-4", () => { "worklet"; return { transform: `translateY(${offset.value}px)` }; }); }, onFabTap() { const value = Math.abs(offset.value - 72); offset.value = timing( value, { duration: 500, easing: (Easing).linear }, () => { "worklet"; if (offset.value > 0) offset.value = 72; } ); }, async toChatsPage() { if (!this.data.patient?.patientId) { try { await this.load(); } catch (error: any) { wx.showModal({ title: "出错了", content: error?.errMsg ?? error?.message ?? "错误,请重试", showCancel: false, }); return; } } const page = "/module/chats/pages/index/index"; wx.navigateTo({ url: `${page}?component=guide&isShowGuide=true`, }); wx.setStorageSync("isAnalysis", 3); }, toHealthPage() { wx.navigateTo({ url: `/module/health/pages/home/home` }); }, toDietTonicPage() { wx.navigateTo({ url: `/module/article/pages/diet-list/diet-list?classify=tonic`, }); }, toDietTeaPage() { wx.navigateTo({ url: `/module/article/pages/diet-list/diet-list?classify=tea`, }); }, toSciencePage() { wx.navigateTo({ url: `/module/article/pages/science-list/science-list` }); }, toSchemePage() { const id = this.data.healthId; if (id) wx.navigateTo({ url: `/module/health/pages/scheme/scheme?id=${id}` }); else wx.showToast({ title: "暂无调理方案", icon: "none" }); }, async toReportPage() { // const { patient } = await getPatients(/*this.data.patientId*/); if (!this.data.patient) await toCertificationPage(); else { const id = this.data.healthId; if (id) wx.navigateTo({ url: `/module/health/pages/report/report?id=${id}` }); else wx.showToast({ title: "暂无分析报告", icon: "none" }); } }, onDraggableSizeUpdate(e: any) { "worklet"; if (e.pixels < 1) { wx.worklet.runOnJS(this.hideDraggableSheet.bind(this))(); } }, showDraggableSheet() { getDraggableSheetContext.call(this).scrollTo({ size: 0.5, pixels: 600, animated: true, duration: 300, easingFunction: "ease", }); this.setData({ sheet: true }); }, hideDraggableSheet(event?: any) { if (event) { getDraggableSheetContext.call(this).scrollTo({ size: 0, animated: true, duration: 300, easingFunction: "ease", }); } this.setData({ position: {}, sheet: false }); }, async loadScienceList() { try { const { data } = await getShortScienceList(); this.setData({ scienceList: data }); } catch (error) {} }, observerPatient(model: { patientId: string; sex: "0" | "1" }) { wx.setStorageSync("patientId", model.patientId); this._getHealthReport(); this._getAbnormalHealthIndex(); const patientIcon = { 0: "gender-male", 1: "gender-female" }[model.sex]; const patientIconColor = { 0: "#0f40f5", 1: "#E560B3" }[model.sex]; this.setData({ patientIcon, patientIconColor }); getPatientDescription(model).then((patientDescription) => { this.setData({ patientDescription }); // wx.setStorageSync("patientPhone", patientDescription.phone); }); // 获取未处理随访列表 this.getNotDealList(); // 获取调养计划 this.getCareLists(); }, // 轮播图加载完成 onCarouselLoaded(e: any) { const { itemId } = e.detail; if (itemId) { this.setData({ [`carouselLoading.${itemId}`]: false, }); } }, // 图片加载失败 onImageError(e: any) { const { itemId } = e.detail; // 图片加载失败时也要隐藏加载状态 if (itemId) { this.setData({ [`carouselLoading.${itemId}`]: false, }); } }, // 视频播放错误 onVideoError(e: any) { const { itemId } = e.detail; // 视频播放错误时也要隐藏加载状态 if (itemId) { this.setData({ [`carouselLoading.${itemId}`]: false, }); } }, // 没有健康分析去做健康分析 goHealthAnalyze() { wx.redirectTo({ url: `/module/chats/pages/index/index?component=guide&isShowGuide=true`, }); wx.setStorageSync("showGuideActive", 1); wx.setStorageSync("isAnalysis", 3); }, async isGoPunchcard(e: any) { const { id, signintime } = e.currentTarget.dataset; // 已经打卡了 if (signintime) { // 已打卡 跳转到打卡页面 wx.navigateTo({ url: `/module/article/pages/punch-card/punch-card?id=${id}`, }); } else { // todo 打卡 const cardId = e.currentTarget.dataset.id; await addPatientOnlineRecordClockIn(cardId); wx.showToast({ title: "打卡成功", icon: "success", duration: 1500, }); // 无感刷新调养计划,保持展开状态 await this.refreshCareListsWithState(); } }, // 无感刷新调养计划,保持展开状态和媒体加载状态 async refreshCareListsWithState() { // 保存当前的展开状态 const currentExpandedStates = this.data.displayList.map((item: any) => ({ id: item.id, expanded: item.expanded, carouselMediaList: item.carouselMediaList, // 保存媒体列表,避免重新加载 })); // 获取新数据 const res = await getCareList(); if (res && res.length > 0) { // 处理新数据,但保持媒体加载状态 res.forEach((item: any) => { // 查找对应的旧数据 const oldItem = currentExpandedStates.find( (state) => state.id === item.id ); // 如果找到旧数据且媒体已加载,保持媒体状态 if (oldItem && oldItem.carouselMediaList) { // 保持原有的媒体列表,避免重新加载 item.carouselMediaList = oldItem.carouselMediaList; } else { // 否则重新构建媒体列表 item.carouselMediaList = []; // 添加photo if (item.photo) { item.carouselMediaList.push({ type: "image", src: item.photo, }); } // 添加itemImgFirst if (item?.itemImgFirst) { item.carouselMediaList.push({ type: "image", src: item.itemImgFirst, }); } // 添加itemVideoFirst if (item?.itemVideoFirst) { item.carouselMediaList.push({ type: "video", src: item.itemVideoFirst, }); } // 如果有轮播图内容,设置加载状态 if (item.carouselMediaList.length > 0) { this.setData({ [`carouselLoading.${item.id}`]: true, }); // 设置超时,防止一直显示加载中 setTimeout(() => { // 检查是否还在加载状态,如果是则自动隐藏 const currentLoading = this.data.carouselLoading; if (currentLoading && currentLoading[item.id]) { this.setData({ [`carouselLoading.${item.id}`]: false, }); } }, 10000); // 10秒后自动隐藏加载状态 } else { // 如果没有轮播图内容,确保不显示加载状态 this.setData({ [`carouselLoading.${item.id}`]: false, }); } } // 确保 id 是数字类型 item.id = Number(item.id); }); // 更新 careList this.setData({ careList: res, }); // 更新 displayList 并恢复展开状态 const { allExpanded } = this.data; let newDisplayList: any[] = allExpanded || res.length <= 4 ? res : res.slice(0, 4); // 恢复展开状态 newDisplayList = newDisplayList.map((item: any) => { const savedState = currentExpandedStates.find( (state) => state.id === item.id ); if (savedState) { return { ...item, expanded: savedState.expanded, carouselMediaList: savedState.carouselMediaList || item.carouselMediaList, }; } return item; }); this.setData({ displayList: newDisplayList, }); } }, });