import { Post } from "../../../../lib/request/method";
import { fromHealthReportSymptom } from "../../../../utils/util";
Page({
  onLoad(options) {
    if (options.id) {
      wx.setStorageSync("careId", Number(options.id));
      this.getCareDetail(Number(options.id));
    }
    // 设置页面标题
    if (options.name && options.name !== "null") {
      this.setData({
        name: options.name,
      });
    }
  },
  data: {
    address: "",
    name: "服务包详情",
    // patientName: "",
    showAddress: false,
    careDetail: {},
    healthReports: [] as any[],
    symptomCellWidth: "300rpx",
    statusText: "未知状态",
    loading: true,
    isShowDelivery: false,
    carouselLoading: {} as Record<string | number, boolean>, // 用于跟踪每个轮播图的加载状态
  },

  // 处理症状数据，按症状名称分组，使相同症状在同一列显示
  processSymptomData(healthReports: any[]) {
    // 收集所有唯一的症状名称
    const symptomSet = new Set<string>();
    healthReports.forEach((report) => {
      if (report.symptoms && Array.isArray(report.symptoms)) {
        report.symptoms.forEach((symptom: any) => {
          symptomSet.add(symptom.name);
        });
      }
    });

    const allSymptomNames = Array.from(symptomSet);

    // 重新组织每个报告的症状数据，确保症状顺序一致
    const processedReports = healthReports.map((report) => {
      const orderedSymptoms: any[] = [];

      // 按照所有症状名称的顺序，为每个报告创建症状数组
      allSymptomNames.forEach((symptomName) => {
        // 查找当前报告中是否有这个症状
        const existingSymptom = report.symptoms?.find(
          (s: any) => s.name === symptomName
        );
        if (existingSymptom) {
          // 如果存在，添加症状信息
          orderedSymptoms.push({
            name: existingSymptom.name,
            label: existingSymptom.label ? `(${existingSymptom.label})` : "",
            value: existingSymptom.value,
          });
        } else {
          // 如果不存在，添加空占位符
          orderedSymptoms.push({
            name: "",
            label: "",
            value: 0,
          });
        }
      });

      return {
        ...report,
        symptoms: orderedSymptoms,
      };
    });
    // 计算每条报告相对于上一条的趋势（上升/下降）
    for (let i = 0; i < processedReports.length; i++) {
      const previousReport = i > 0 ? processedReports[i - 1] : null;
      const currentReport = processedReports[i];
      currentReport.symptoms = currentReport.symptoms.map(
        (sym: any, idx: number) => {
          const previousSymptom = previousReport
            ? previousReport.symptoms[idx]
            : null;
          let trend: "" | "up" | "down" = "";
          if (previousReport && sym && sym.name) {
            const currentValue = Number(sym.value) || 0;
            const previousValue = previousSymptom
              ? Number(previousSymptom.value) || 0
              : 0;
            if (currentValue > previousValue) trend = "up";
            else if (currentValue < previousValue) trend = "down";
          }
          return { ...sym, trend };
        }
      );
    }

    return processedReports;
  },
//健康咨询记录
onChatRecord(e: any) {
  const item = e.currentTarget.dataset.item;
  console.log(item,"咨询记录数据",e)
  if (item) {
  wx.navigateTo({
      url: `/module/chats/pages/consultation-record/consultation-record?item=${encodeURIComponent(JSON.stringify(item))}`,
    });
  }
},

  onCardRecord(e: any) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/module/article/pages/punch-card/punch-card?id=${id}`,
    });
  },

  // 轮播图加载完成
  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,
      });
    }
  },

  // 测试图片加载
  testImageLoading(mediaList: any[], itemId: string | number) {
    mediaList.forEach((media) => {
      if (media.type === "image") {
        wx.getImageInfo({
          src: media.src,
          success: () => {
            // 图片加载成功，隐藏加载状态
            this.setData({
              [`carouselLoading.${itemId}`]: false,
            });
          },
          fail: () => {
            // 图片加载失败，也要隐藏加载状态
            this.setData({
              [`carouselLoading.${itemId}`]: false,
            });
          },
        });
      } else if (media.type === "video") {
        // 视频不进行预加载测试
      }
    });
  },
  // 获取调理详情
  async getCareDetail(id: number) {
    wx.showLoading({
      title: "加载中",
      mask: true,
    });
    // 获取调理详情
    try {
      const res = await Post(
        `/patientCrManage/getPcrProcessById/${id}`,
        {},
        {
          transform({ data }: any) {
            return data;
          },
        }
      );

      if (res) {
        wx.hideLoading();
        this.setData({
          address: `${res?.provinceName ?? ""}${res?.cityName ?? ""}${
            res?.areaName ?? ""
          }${res?.detailAddress ?? ""}`,
        });
        if (
          !res?.provinceName &&
          !res?.cityName &&
          !res?.areaName &&
          !res?.detailAddress &&
          (!res?.liaison || !res.patientName) &&
          !res?.phone
        ) {
          this.setData({
            showAddress: false,
          });
        } else {
          this.setData({
            showAddress: true,
          });
        }
        // 设置状态文本
        const statusMap: Record<string, string> = {
          "0": "待付款",
          "1": "已作废",
          "2": "用户取消",
          "3": "未开始",
          "4": "调理中",
          "5": "已完结",
        };
        const statusText = statusMap[res.progress] || "未知状态";

        let isShowDelivery = false;
        if (res && res.items && res.items.length > 0) {
          res.items.forEach((item: any) => {
            item.carouselMediaList = [];
            // 添加photo
            if (item.conditioningProgramDetail?.photo) {
              item.carouselMediaList.push({
                type: "image",
                src: item.conditioningProgramDetail?.photo,
              });
            }
            // 添加itemImgFirst
            if (item?.conditioningProgramDetail?.itemImgFirst) {
              item.carouselMediaList.push({
                type: "image",
                src: item.conditioningProgramDetail?.itemImgFirst,
              });
            }

            // 添加itemVideoFirst
            if (item?.conditioningProgramDetail?.itemVideoFirst) {
              item.carouselMediaList.push({
                type: "video",
                src: item.conditioningProgramDetail?.itemVideoFirst,
              });
            }

            // 如果有轮播图内容，设置加载状态
            if (item.carouselMediaList.length > 0) {
              this.setData({
                [`carouselLoading.${item.id}`]: true,
              });

              // 测试图片是否可以正常加载
              this.testImageLoading(item.carouselMediaList, item.id);

              // 设置超时，防止一直显示加载中
              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,
              });
            }
          });
          // 是否显示配送
          isShowDelivery = res.items.some((item: any) => {
            return item.conditioningProgramDetail?.isDelivery === "Y";
          });
          var data = res.items.find(
            (item: any) =>
              Array.isArray(item.healthAnalysisReports) &&
              item.healthAnalysisReports.length > 0
          );
          if (data) {
            const items = data.healthAnalysisReports.map((report: any) => {
              return {
                ...report,
                symptoms: fromHealthReportSymptom(report).items,
              };
            });

            // 处理症状数据，按症状名称分组，使相同症状在同一列显示
            const processedReports = this.processSymptomData(items);

            this.setData({
              healthReports: processedReports,
            });
          }
        }
        this.setData({
          loading: false,
          careDetail: res,
          statusText,
          isShowDelivery,
        });

        // 设置页面标题
        if (res.conditioningWrapName) {
          wx.setNavigationBarTitle({
            title: res.conditioningWrapName,
          });
        }
      } else {
        wx.hideLoading();
        this.setData({
          loading: false,
          careDetail: {},
        });
      }
    } catch (error: any) {
      wx.showToast({
        title: error.message,
        icon: "none",
      });
      wx.hideLoading();
      this.setData({
        isShow: false,
        loading: false,
      });
    }
  },

  onRecord(e: any) {
    const id = e.currentTarget.dataset.id;
    // 跳转核销记录
    wx.navigateTo({
      url: `/module/care/pages/care/verifyRecord?id=${id}`,
      success: () => {},
      fail: (error) => {
        console.error("跳转失败:", error);
      },
    });
  },
  onOffline(e: any) {
    // 跳转线下操作
  },
  onReport(e: WechatMiniprogram.TouchEvent) {
    wx.navigateTo({
      url: "/module/care/pages/reportRecord/reportRecord",
    });
  },
  onSeeReport(e: WechatMiniprogram.TouchEvent) {
    const id = e.currentTarget.dataset.id;
    if (id) {
      wx.navigateTo({ url: `/module/health/pages/report/report?id=${id}` });
    } else {
      wx.showToast({
        title: "暂无数据",
        icon: "none",
      });
    }
  },
  onPreviewImage(e: WechatMiniprogram.TouchEvent) {
    const url = e.currentTarget.dataset.url;
    wx.previewImage({
      current: url,
      urls: [url],
      showmenu: true,
    });
  },

  onHide() {
    wx.removeStorageSync("careId");
  },
});
