import PageContainerBehavior from "../../../../core/behavior/page-container.behavior";
import { OfflineEvaluateModel } from "../../model/evaluate.model";
import { getOrderGoodsEvaluationMethod } from "../../request";
function parseMediaType(url: string): "image" | "video" {
  if (!url) return "image";
  const match = /[?&]type=(image|video)\b/i.exec(url);
  if (match) return match[1].toLowerCase() as "image" | "video";
  const lower = url.toLowerCase();
  if (/\.(mp4|mov|avi|rmvb|flv|mkv|webm)$/.test(lower)) return "video";
  return "image";
}
Page({
  behaviors: [PageContainerBehavior],
  data: {
    orderId: "",
    service: {} as OfflineEvaluateModel,
    scoreServiceQuality: 0,
    scoreAttitude: 0,
    scoreEnvironment: 0,
    rateColor: "#F7BA2A",
    content: "",
    mediaList: [] as { path: string; type: "image" | "video" }[],
    videoFullscreen: false,
  },
  async onLoad(options: Record<string, string>) {
    let service = {} as OfflineEvaluateModel;
    if (options.goodsInfo) {
      const goods = JSON.parse(decodeURIComponent(options.goodsInfo));
      service = {
        lineId: goods.id || 0,
        patientConditioningRecordId: goods.patientConditioningRecordId || 0,
        patientConditioningProgramId: goods.patientConditioningProgramId || 0,
        operateTime: goods.operateTime || "",
        operateBy: goods.operateBy || "",
        conditioningProgramSupplierName: goods.conditioningProgramSupplierName || "",
        image: goods.conditioningProgramPhoto || "",
        name: goods.conditioningProgramName
      };
    }
    this.setData({
      service,
    });
    if (service.patientConditioningRecordId) {
      try {
        const res = await getOrderGoodsEvaluationMethod("2", service.lineId);
        const mediaList: { path: string; type: "image" | "video" }[] = [];
        if (res && res.data) {
          if (Array.isArray(res.data.imageVideos)) {
            res.data.imageVideos.forEach((url: string) => {
              if (!url) return;
              mediaList.push({
                path: url,
                type: parseMediaType(url),
              });
            });
          }
          this.setData({
            evaluateInfo: res.data,
            scoreServiceQuality: Number(res.data.complianceScore ?? 0),
            scoreAttitude: Number(res.data.attitudeScore ?? 0),
            scoreEnvironment: Number(res.data.environmentScore ?? 0),
            content: res.data.depict || "",
            mediaList,
          });
        }
      } catch (error: any) {
        wx.showToast({
          title: error?.errMsg || "获取评价详情失败",
          icon: "none",
        });
      }
    }
  },
  onBack() {
    wx.navigateBack();
  },
  onPreviewImage(e: WechatMiniprogram.TouchEvent) {
    const url = e.currentTarget.dataset.url as string;
    const urls = this.data.mediaList
      .filter((m) => m.type === "image")
      .map((m) => m.path);
    if (url && urls.length) {
      wx.previewImage({ current: url, urls });
    }
  },
  onPreviewVideo(e: WechatMiniprogram.TouchEvent) {
    const index = e.currentTarget.dataset.index as number;
    const ctx = wx.createVideoContext("offline-detail-video-" + index, this);
    ctx.requestFullScreen({});
  },
  /** 点击图片/视频：原生全屏预览（类似 test 页） */
  onPreviewMedia(e: WechatMiniprogram.TouchEvent) {
    const index = e.currentTarget.dataset.index as number;
    const { mediaList } = this.data;
    if (index < 0 || index >= mediaList.length) return;

    const sources = mediaList.map((m) => ({
      url: m.path,
      type: m.type as "image" | "video",
    }));

    const previewMedia = (wx as any).previewMedia as
      | ((option: { sources: { url: string; type: "image" | "video" }[]; current: number }) => void)
      | undefined;

    if (typeof previewMedia === "function") {
      previewMedia({ sources, current: index });
      return;
    }

    // 低版本兜底：图片用 previewImage，视频用 requestFullScreen
    const current = mediaList[index];
    if (current.type === "image") {
      const urls = mediaList.filter((m) => m.type === "image").map((m) => m.path);
      wx.previewImage({ current: current.path, urls });
      return;
    }
    const ctx = wx.createVideoContext("offline-detail-video-" + index, this);
    ctx.requestFullScreen({});
  },
  onVideoFullscreenChange(e: WechatMiniprogram.VideoFullScreenChange) {
    const fullScreen = !!(e.detail && e.detail.fullScreen);
    this.setData({ videoFullscreen: fullScreen });
  },
});
