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

function withMediaType(url: string, type: "image" | "video") {
  if (!url) return url;
  const hasQuery = url.includes("?");
  const hasHash = url.includes("#");
  if (hasHash) {
    const [base, hash] = url.split("#");
    return `${base}${hasQuery ? "&" : "?"}type=${type}#${hash ?? ""}`;
  }
  return `${url}${hasQuery ? "&" : "?"}type=${type}`;
}
Page({
  behaviors: [PageContainerBehavior],
  data: {
    orderId: "",
    product: {} as { name: string; image: string; description?: string, patientConditioningRecordId?: number, patientConditioningProgramId?: number },
    score: 0,
    rateColor: "#F7BA2A",
    content: "",
    evaluateInfo: {} as EvaluateModel,
    mediaList: [] as { path: string; type: "image" | "video" }[],
    canPublish: false,
    videoFullscreen: false,
  },
  onLoad(options: Record<string, string>) {
    console.log(options, "options===");
    // const orderId = options.orderId || options.id || "";
    let product: { name: string; image: string; description?: string, patientConditioningRecordId?: number, patientConditioningProgramId?: number } = {
      name: "",
      image: "",
      description: "",
      patientConditioningRecordId: 0,
      patientConditioningProgramId: 0,
    };
    if (options.goodsInfo) {
      const goods = JSON.parse(decodeURIComponent(options.goodsInfo));
      console.log(goods, "goods===");
      product = {
        name: goods.name || "",
        image: goods.image || "",
        description: goods.description || "",
        patientConditioningRecordId: goods.patientConditioningRecordId || 0,
        patientConditioningProgramId: goods.id || 0,
      };
    }
    this.setData({
      // orderId,
      product,
      canPublish: this._checkCanPublish(0, ""),
    });
  },
  _checkCanPublish(score: number, _content: string): boolean {
    return score > 0;
  },
  onScoreChange(e: WechatMiniprogram.CustomEvent<{ value: number }>) {
    const score = e.detail?.value ?? 0;
    this.setData({
      score,
      canPublish: this._checkCanPublish(score, this.data.content),
    });
  },
  onContentInput(e: WechatMiniprogram.Input) {
    const content = e.detail?.value ?? "";
    this.setData({
      content,
      canPublish: this._checkCanPublish(this.data.score, content),
    });
  },
  onChooseMedia() {
    const current = this.data.mediaList.length;
    if (current >= 9) {
      wx.showToast({ title: "图片和视频总数不能超过9个", icon: "none" });
      return;
    }
    const remain = 9 - current;
    wx.chooseMedia({
      count: remain,
      mediaType: ["image", "video"],
      sourceType: ["album", "camera"],
      maxDuration: 30,
      camera: "back",
      success: (res) => {
        const list = res.tempFiles.map((f) => ({
          path: f.tempFilePath,
          type: (f.fileType === "video" ? "video" : "image") as "image" | "video",
        }));
        const oldLength = this.data.mediaList.length;
        const next = [...this.data.mediaList, ...list].slice(0, 9);
        this.setData({ mediaList: next });

        // 选取本地媒体后，调用上传接口上传到服务器
        list.forEach((item, idx) => {
          const index = oldLength + idx;
          upload<string, any>({
            params: { name: "file", file: item.path },
            transform({ data }: any): string {
              return (data as any)?.url || (data as any);
            },
          }).then(
            (url) => {
              const key = `mediaList[${index}].path`;
              this.setData({ [key]: url });
            },
            (error: any) => {
              wx.showToast({
                title: error?.errMsg || "上传失败",
                icon: "none",
              });
              const mediaList = this.data.mediaList.filter((_, i) => i !== index);
              this.setData({ mediaList });
            }
          );
        });
      },
    });
  },
  onRemoveMedia(e: WechatMiniprogram.TouchEvent) {
    const index = e.currentTarget.dataset.index as number;
    const mediaList = this.data.mediaList.filter((_, i) => i !== index);
    this.setData({ mediaList });
  },
  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 videoContext = wx.createVideoContext("goods-video-" + index, this);
    videoContext.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-video-" + index, this);
    ctx.requestFullScreen({});
  },
  onVideoFullscreenChange(e: WechatMiniprogram.VideoFullScreenChange) {
    const fullScreen = !!(e.detail && e.detail.fullScreen);
    this.setData({ videoFullscreen: fullScreen });
  },
  onRemoveProduct() {
    this.setData({
      product: { name: "", image: "", description: "", patientConditioningRecordId: 0, patientConditioningProgramId: 0 },
    });
  },
  async onPublish() {
    if (!this.data.canPublish) {
      wx.showToast({ title: "请先完成评分", icon: "none" });
      return;
    }

    console.log(this.data.product,"90000")
    const data = {
      patientConditioningProgramId: this.data.product.patientConditioningProgramId,
      patientConditioningRecordId: this.data.product.patientConditioningRecordId,
      complianceScore: this.data.score,
      depict: this.data.content,
      imageVideos: this.data.mediaList.map((m) => withMediaType(m.path, m.type)),
    };
    console.log(data,"评价数据")
    try {
      wx.showLoading({ title: "发布中..." });
      await evaluateOrderGoodsMethod(data);
      wx.hideLoading();
      wx.showToast({ title: "发布成功", icon: "success" });
      wx.redirectTo({
        url: `/module/article/pages/order-list/order-list`,
      });
    } catch (error: any) {
      wx.hideLoading();
      wx.showToast({ title: error.errMsg || "发布失败", icon: "none" });
    }
  },
});
