import PageContainerBehavior from "../../../../core/behavior/page-container.behavior";
import { getOrderGoodsEvaluationMethod } from "../../request";
import { EvaluateModel } from "../../model/evaluate.model";

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: "",
    product: {} as { id: number; name: string; image: string; description?: string },
    evaluateInfo: {} as EvaluateModel,
    // 只读展示用
    score: 0,
    rateColor: "#F7BA2A",
    content: "",
    mediaList: [] as { path: string; type: "image" | "video" }[],
    videoFullscreen: false,
    showMediaCarousel: false,
    mediaCarouselCurrent: 0,
  },
  async onLoad(options: Record<string, string>) {
    console.log(options, "options===");


    let product: { id: number; name: string; image: string; description?: string } = {
      id: 0,
      name: "",
      image: "",
      description: "",
    };
    console.log(options, "options.goodsInfo===");
    if (options.goodsInfo) {
      try {
        const goods = JSON.parse(decodeURIComponent(options.goodsInfo));
        console.log(goods, "goods===");
        product = {
          id: goods.id || 0,
          name: goods.name || "",
          image: goods.image || "",
          description: goods.description || "",
        };
      } catch (_) { }
    }
    this.setData({ product });
    console.log(product, "product===");

    if (product.id) {
      try {
        const res = await getOrderGoodsEvaluationMethod("1", product.id);
        if (!res && !res.data) return;
        console.log(res, "res===");
        const mediaList: { path: string; type: "image" | "video" }[] = [];
        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,
          score: Number(res.data.complianceScore ?? 0),
          content: res.data.depict || "",
          mediaList,
        });

      } catch (error: any) {
        console.log(error, "error===");
        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("goods-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("goods-detail-video-" + index, this);
    ctx.requestFullScreen({});
  },
  /** 轮播切换：暂停所有视频，若当前项是视频则播放 */
  onMediaCarouselChange(e: WechatMiniprogram.SwiperChange) {
    const current = e.detail?.current ?? 0;
    this.setData({ mediaCarouselCurrent: current });
    this._pauseAllCarouselVideos();
    this._playVideoAtCarouselIndex(current);
  },
  onCloseMediaCarousel() {
    this._pauseAllCarouselVideos();
    this.setData({ showMediaCarousel: false });
  },
  _playVideoAtCarouselIndex(index: number) {
    const list = this.data.mediaList;
    if (index < 0 || index >= list.length || list[index].type !== "video") return;
    const ctx = wx.createVideoContext("preview-video-" + index, this);
    ctx.play();
  },
  _pauseAllCarouselVideos() {
    this.data.mediaList.forEach((item, i) => {
      if (item.type === "video") {
        const ctx = wx.createVideoContext("preview-video-" + i, this);
        ctx.pause();
      }
    });
  },
  onVideoFullscreenChange(e: WechatMiniprogram.VideoFullScreenChange) {
    const fullScreen = !!(e.detail && e.detail.fullScreen);
    this.setData({ videoFullscreen: fullScreen });
  },
});
